Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,3 +415,7 @@ The authenticated control API serves upstream GGUF drafters independently of cha
| GET /models/llamacpp-upstream/*modelId/drafter/selection | Read just the selected ID for chat routing. |

The data folder holds `llamacpp/drafters/<sha256>.gguf` and its inventory in `llamacpp/drafters/index.json`. Each model installation can contain `upstream-drafter.json` with its selected content ID and target-file identity. Legacy installations default to no DSpark selection.

### Local LoRA import

On the loopback control listener, `GET /atomic/v1/loras/import-models?format=gguf|safetensors` returns installed candidates as `{ mode, model }[]`. `POST /atomic/v1/loras/import` accepts `{ path, mode, model }` and returns the installed artifact. A local artifact has `source: "local"`, a filename, size, SHA-256, mode and target. Import does not select it. Clients use the existing choices API to activate an adapter.
5 changes: 5 additions & 0 deletions docs/decisions/2026-12-01-import-local-lora-weights.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Import local LoRA weights into Core storage

The desktop file picker passes an absolute path and an installed base model to the loopback control API. Core inspects a staged copy, compares declared checkpoint metadata when available, and registers the validated weights by SHA-256. A local inventory entry stores its filename and source. Existing Hugging Face records keep their published provenance. When the checkpoint has no identifiable repository, local compatibility is scoped to the selected installation and its signature.

Import and selection are distinct operations. Import never reloads a session. Removing an imported adapter removes the managed copy and clears its selections. The user owns the original.
1 change: 1 addition & 0 deletions docs/decisions/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,4 @@ add a new one that says which record it supersedes.
- [2026-11-23 — Compact overflowing chat history on every engine](2026-11-23-compact-overflowing-chat-history-on-every-engine.md)
- [2026-11-23 — Map every engine's context overflow to one error](2026-11-23-map-every-engines-context-overflow-to-one-error.md)
- [2026-11-23 — Default every engine to the largest window that fits](2026-11-23-default-every-engine-to-the-largest-window-that-fits.md)
- [2026-12-01 — Import local LoRA weights into Core storage](2026-12-01-import-local-lora-weights.md)
15 changes: 15 additions & 0 deletions src/core/create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,21 @@ describe('LoRA checkpoint discovery through the owner', () => {
expect(await cached.json()).toMatchObject({ target, results: result.results })
})

it('offers only installed chat and media bases to the LoRA import dialog', async () => {
await data.writeModel('my-chat')
await data.writeModel('embed', { embedding: true })
const incomplete = await data.writeModel('partial')
await rm(join(incomplete, 'model.gguf'))
const core = await createCore()
const bases = (format: string) =>
fetch(core.control.url + '/atomic/v1/loras/import-models?format=' + format, {
headers: { authorization: 'Bearer ' + core.controlToken },
})
expect(await (await bases('gguf')).json()).toEqual([{ model: 'my-chat', mode: 'chat' }])
expect(await (await bases('safetensors')).json()).toEqual([])
expect((await bases('zip')).status).toBe(400)
})

it('derives the base of a quantized media model from its declared provenance and respects the mode', async () => {
const core = await createCore({
fetch: async () => Response.json({ tags: ['base_model:quantized:black-forest-labs/FLUX.1-schnell'] }),
Expand Down
27 changes: 21 additions & 6 deletions src/core/create.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import type { AtomicCatalogEntry } from '../client/model-catalog.js'
import type { AtomicModelCatalog } from '../client/model-catalog.js'
/**
* The dependency wiring behind `AtomicCore.create()`: take the instance lock, open every store, build
* the runtimes and backend services, start the control listener, construct the facade, reap what a
* previous owner left running and only then publish the endpoint.
*/

import { lstat } from 'node:fs/promises'
import { lstat, stat } from 'node:fs/promises'
import catalogBaseline from '../client/model-catalog-baseline.json' with { type: 'json' }
import { FifoLock } from '../runtime/shared/fifo-lock.js'
import { LoraService } from '../drafters/lora-service.js'
import { installedMediaBases } from '../drafters/lora-import.js'
import { catalogLoras } from '../drafters/lora-catalog.js'
import { DrafterDiscovery, repoId } from '../drafters/catalog.js'
import {
Expand Down Expand Up @@ -316,23 +317,37 @@ export async function createAtomicCore(
attachmentMutations
)
const mediaCheckpoints = new DrafterDiscovery(options.fetch ?? fetch)
let loraModels: Pick<AtomicModelCatalog, 'models'> = catalogBaseline
const loras: LoraService = new LoraService(
layout.root,
downloader,
options.fetch ?? fetch,
catalogLoras(catalogBaseline),
(model, previous) => drafters.checkpoint(model, previous),
(model, rollback) => upstreamRuntime.recreateSession(model, rollback),
async () => catalogLoras(await loadHostModelCatalog(options.env, options.fetch)),
async () => {
loraModels = await loadHostModelCatalog(options.env, options.fetch)
return catalogLoras(loraModels)
},
async (mode, model) => {
const entry = (catalogBaseline.models as Record<string, AtomicCatalogEntry>)[
'diffusion:' + model.split(':')[0]
]
const entry = loraModels.models['diffusion:' + model.split(':')[0]]
if (entry?.kind !== 'diffusion' || entry.definition.modality !== mode) return
const transformer = entry.definition.transformer as { repo?: string } | undefined
if (repoId(transformer?.repo))
return mediaCheckpoints.checkpoint(transformer.repo).catch(() => undefined)
},
async (format) => {
if (format === 'safetensors') return installedMediaBases(loraModels, await diffusion.listModelFiles())
const registry = registries.get(LOCAL_PROVIDER) as ModelRegistry
const rows = await registry.listChatModels()
const installed = await Promise.all(
rows.map(async ({ id, yml }) => {
const info = await stat(registry.resolvePaths(yml).modelPath).catch(() => undefined)
return info?.isFile() ? [{ model: id, mode: 'chat' as const }] : []
})
)
return installed.flat()
},
attachmentMutations
)
const llamacppRuntime = (provider: LlamacppProviderId) =>
Expand Down
19 changes: 19 additions & 0 deletions src/drafters/lora-import.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect, it } from 'vitest'
import { installedMediaBases } from './lora-import.js'

it('offers a diffusion base only when the quant and all required companions are present', () => {
const definition = {
id: 'frames',
modality: 'video',
transformer: { quants: [{ id: 'q4', filename: 'quants/base.gguf', bytes: 5 }] },
vae: { repo: 'org/vae', filename: 'files/vae.bin', bytes: 3 },
text_encoders: [{ field: 'llm_vision', repo: 'org/optional', filename: 'clip.gguf', bytes: 10 }],
}
const catalog = { models: { frames: { kind: 'diffusion', format: 'diffusion', variants: {}, definition } } }
const files = [
{ relativePath: 'frames/base.gguf', bytes: 5 },
{ relativePath: 'shared/org--vae/vae.bin', bytes: 3 },
]
expect(installedMediaBases(catalog, files)).toEqual([{ model: 'frames:q4', mode: 'video' }])
expect(installedMediaBases(catalog, files.slice(0, 1))).toEqual([])
})
130 changes: 130 additions & 0 deletions src/drafters/lora-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { open } from 'node:fs/promises'
import { basename } from 'node:path'
import type { AtomicModelCatalog } from '../client/index.js'
import { AtomicCoreError } from '../contracts/index.js'
import { readGgufTensorSummaryChunked } from '../models/index.js'
import { repoId } from './catalog.js'
import { hasLoraTensors, type LoraMode } from './lora-catalog.js'

export interface LoraImportModel {
mode: LoraMode
model: string
}

interface MediaFile {
repo: string
filename: string
bytes: number
field?: string
}

/** Use the transformer's quant and the required companions of the default generation workflow. */
export function installedMediaBases(
catalog: Pick<AtomicModelCatalog, 'models'>,
files: { relativePath: string; bytes: number }[]
): LoraImportModel[] {
const sizes = new Map(files.map((file) => [file.relativePath, file.bytes]))
const models: LoraImportModel[] = []
for (const { kind, definition } of Object.values(catalog.models)) {
const { id, modality, vae, audio_vae, text_encoders } = definition
if (kind !== 'diffusion' || typeof id !== 'string' || (modality !== 'image' && modality !== 'video'))
continue
const transformer = definition.transformer as { quants?: (MediaFile & { id: string })[] } | undefined
const companions = [vae, audio_vae, ...(Array.isArray(text_encoders) ? text_encoders : [])].filter(
Boolean
) as MediaFile[]
if (
!companions.every(
(f) =>
f.field === 'llm_vision' ||
sizes.get('shared/' + f.repo.replaceAll('/', '--') + '/' + basename(f.filename)) === f.bytes
)
)
continue
for (const q of transformer?.quants ?? []) {
if (sizes.get(id + '/' + basename(q.filename)) === q.bytes)
models.push({ mode: modality, model: id + ':' + q.id })
}
}
return models
}

function baseRepo(value: unknown) {
if (typeof value !== 'string') return
const repo = value.replace(/^https:\/\/huggingface\.co\//i, '').replace(/\/$/, '')
return repoId(repo) ? repo : undefined
}

const corrupt = () =>
new AtomicCoreError('MODEL_FILE_CORRUPT', 'The file does not contain complete, supported LoRA weights.')

export async function inspectAdapter(path: string, mode: LoraMode) {
const handle = await open(path, 'r')
try {
const { size } = await handle.stat()
const prefix = async (count: number) => {
const buffer = Buffer.alloc(Math.min(size, count))
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
return buffer.subarray(0, bytesRead)
}
if (mode === 'chat') {
const info = await readGgufTensorSummaryChunked(prefix, {
fileSize: size,
chunkSize: 65536,
growth: 'doubling',
})
if (
info.metadata['general.type'] !== 'adapter' ||
info.metadata['adapter.type'] !== 'lora' ||
!info.tensorCount ||
info.dataOffset >= size ||
info.types.some(
(t) =>
!t.bytes ||
t.elements !== t.sizedElements ||
(t.type === 0 && t.bytes < 4 * t.elements) ||
(t.type === 1 && t.bytes < 2 * t.elements)
)
)
throw corrupt()
return baseRepo(info.metadata['general.base_model.0.repo_url'])
}
const first = await prefix(8)
if (first.length !== 8) throw corrupt()
const length = Number(first.readBigUInt64LE())
if (length <= 0 || length > 8 * 1024 * 1024 || length + 8 >= size) throw corrupt()
const header = JSON.parse((await prefix(length + 8)).subarray(8).toString('utf8'))
if (!hasLoraTensors(header)) throw corrupt()
const tensors = Object.entries(header).filter(([key]) => key !== '__metadata__')
const ranges = tensors
.map(([, value]) => {
const tensor = value as { data_offsets?: unknown; shape?: unknown; dtype?: unknown }
const offsets = tensor?.data_offsets
if (
!Array.isArray(tensor?.shape) ||
!tensor.shape.every((dim) => Number.isSafeInteger(dim) && dim >= 0) ||
typeof tensor.dtype !== 'string' ||
!Array.isArray(offsets) ||
offsets.length !== 2 ||
!offsets.every(Number.isSafeInteger) ||
offsets[0] < 0 ||
offsets[1] < offsets[0]
)
throw corrupt()
return offsets as [number, number]
})
.sort((a, b) => a[0] - b[0] || a[1] - b[1])
let end = 0
for (const [start, next] of ranges) {
if (start !== end) throw corrupt()
end = next
}
if (end !== size - length - 8) throw corrupt()
return baseRepo(header.__metadata__?.['modelspec.base_model'] ?? header.__metadata__?.ss_sd_model_name)
} catch (e) {
if (e instanceof Error && 'code' in e) throw e
throw corrupt()
} finally {
await handle.close()
}
}
96 changes: 93 additions & 3 deletions src/drafters/lora-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { it, expect, vi } from 'vitest'
import { createHash } from 'node:crypto'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { buildGguf } from '../../test/helpers/gguf-builder.js'
Expand All @@ -10,7 +10,10 @@ import type { LoraArtifact } from './lora-catalog.js'
it('restores a failed reload, persists one binding per installation and clears it on removal', async () => {
const root = await mkdtemp(join(tmpdir(), 'atomic-chat-lora-'))
try {
const bytes = buildGguf({ metadata: { 'general.type': 'adapter', 'adapter.type': 'lora' }, tensors: [] })
const bytes = buildGguf({
metadata: { 'general.type': 'adapter', 'adapter.type': 'lora' },
tensors: [{ name: 'q.weight.lora_a', dims: [4, 4], type: 1, bitsPerWeight: 16 }],
})
const row: LoraArtifact = {
mode: 'chat',
repo: 'author/adapter',
Expand Down Expand Up @@ -46,7 +49,8 @@ it('restores a failed reload, persists one binding per installation and clears i
async (model) => ({ target: model === 'B' ? 'other/base' : row.target, signature: model }),
restart,
async () => catalog,
async () => undefined
async () => undefined,
async () => []
)
const first = service()
expect(await first.search('', undefined, false, 'Quant/Base-GGUF')).toMatchObject({
Expand Down Expand Up @@ -77,3 +81,89 @@ it('restores a failed reload, persists one binding per installation and clears i
await rm(root, { recursive: true, force: true })
}
})

it.each(['chat', 'image', 'video'] as const)(
'imports %s weights without activating them and preserves the source',
async (mode) => {
const root = await mkdtemp(join(tmpdir(), 'atomic-import-'))
try {
const target = 'author/base'
const catalog = {
files: [],
families: new Map<string, string>(),
familyRepos: new Map<string, string>(),
sources: new Map<string, string>(),
}
const downloader = new Downloader({
dataFolder: root,
platform: 'darwin',
emit: () => {},
fetch,
sleep: async () => {},
})
const restart = vi.fn()
const base = (model: string) => (model === 'one' ? target : 'author/other')
const make = () =>
new LoraService(
root,
downloader,
fetch,
catalog,
async (model) => ({ signature: model, target: base(model) }),
restart,
async () => catalog,
async (_, model) => base(model),
async () => ['one', 'two'].map((model) => ({ model, mode }))
)
const service = make()
const path = join(root, mode === 'chat' ? 'patch.gguf' : 'patch.safetensors')
const gguf = buildGguf({
metadata: {
'general.type': 'adapter',
'adapter.type': 'lora',
'general.base_model.0.repo_url': 'https://huggingface.co/' + target,
},
tensors: [{ name: 'q.weight.lora_a', dims: [4, 4], type: 1, bitsPerWeight: 16 }],
})
const header = Buffer.from(
JSON.stringify({ 'blk.lora_A.weight': { shape: [1, 1], dtype: 'F32', data_offsets: [0, 4] } })
)
const prefix = Buffer.alloc(8)
prefix.writeBigUInt64LE(BigInt(header.length))
const bytes = mode === 'chat' ? gguf : Buffer.concat([prefix, header, Buffer.alloc(4)])
await writeFile(path, bytes)
await expect(service.importFile(path, mode, 'missing')).rejects.toThrow('installed')
if (mode === 'chat')
await expect(service.importFile(path, mode, 'two')).rejects.toThrow('different base')
const [row, duplicate] = await Promise.all([
service.importFile(path, mode, 'one'),
service.importFile(path, mode, 'one'),
])
expect(duplicate).toEqual(row)
expect(row).toMatchObject({
source: 'local',
mode,
target,
sha256: createHash('sha256').update(bytes).digest('hex'),
})
expect(await make().choices(mode, 'one')).toMatchObject({ adapterId: null, files: [row] })
expect(restart).not.toHaveBeenCalled()
await expect(service.importFile(path, mode, 'two')).rejects.toThrow('different base')
await make().select(mode, 'one', row.sha256)
expect(await make().resolve(mode, 'one')).toContain(row.sha256)
await service.remove(row.sha256)
expect((await service.search('patch')).results).toEqual([])
expect(await readFile(path)).toEqual(bytes)
await writeFile(path, bytes.subarray(0, bytes.length - 1))
await expect(service.importFile(path, mode, 'one')).rejects.toThrow()
if (mode === 'chat') {
await writeFile(path, buildGguf({ metadata: { 'general.type': 'model' }, tensors: [] }))
await expect(service.importFile(path, mode, 'one')).rejects.toThrow()
}
await expect(service.importFile(join(root, 'missing.gguf'), mode, 'one')).rejects.toThrow()
expect((await service.list()).files).toEqual([])
} finally {
await rm(root, { recursive: true, force: true })
}
}
)
Loading
Loading