- ['managed', 'foundry', 'litert', 'geniex', 'fastflowlm'].includes(engineFamily(e))
+ ['managed', 'foundry', 'litert', 'geniex', 'fastflowlm', 'strata'].includes(engineFamily(e))
))
b(
`setup-engine:${engine}`,
diff --git a/src/tui/workspace/state.ts b/src/tui/workspace/state.ts
index bbce1015..9675a8a1 100644
--- a/src/tui/workspace/state.ts
+++ b/src/tui/workspace/state.ts
@@ -87,7 +87,7 @@ export interface WorkspaceState extends WorkspaceReturnState {
returnOverlay?: WorkspaceState['overlay']
} | null
libraryRemove: string
- removeModelStore?: 'geniex' | 'fastflowlm' | undefined
+ removeModelStore?: 'geniex' | 'fastflowlm' | 'strata' | undefined
modelLoad?: { provider: string; model: string } | null
modelVision: boolean | null
loadError: { provider: string; model: string; message: string } | null
@@ -114,6 +114,7 @@ export interface WorkspaceState extends WorkspaceReturnState {
secret: string
/** `providers`: every provider the core says lists the model; `provider` the first. */
installed: {
+ disabled_reason?: string | null
id: string
provider: string
name: string
diff --git a/src/workspace-service/models/download-removal.ts b/src/workspace-service/models/download-removal.ts
index 4c337ba7..7ae45d30 100644
--- a/src/workspace-service/models/download-removal.ts
+++ b/src/workspace-service/models/download-removal.ts
@@ -125,6 +125,7 @@ export async function removeDownload(
options,
installed
)
+ if (owner === 'strata') return downloads.strata.discard(id)
if (owner === 'fastflowlm') return downloads.fastflowlm.discard(id)
if (owner === 'geniex') {
const journal = downloads.geniex.journal
diff --git a/src/workspace-service/models/model-downloads.ts b/src/workspace-service/models/model-downloads.ts
index 146dc87e..c3c24002 100644
--- a/src/workspace-service/models/model-downloads.ts
+++ b/src/workspace-service/models/model-downloads.ts
@@ -1,3 +1,4 @@
+import { StrataSetups } from '../strata/setups.js'
import { FlmSetups } from '../fastflowlm/setups.js'
import type { EngineDownloads } from '../engines/engine-downloads.js'
import { join } from 'node:path'
@@ -37,6 +38,11 @@ export function modelDownloads(
downloader,
geniex: new GenieSetups(options, downloader),
fastflowlm: new FlmSetups(options, downloader),
+ strata: new StrataSetups(
+ options,
+ downloader,
+ engines ? (taskId) => engines.ensure('strata', 'strata-engine-' + taskId) : undefined
+ ),
artifacts: new ArtifactService(options, catalog, request, downloader, engines?.ensure.bind(engines)),
managed: new ManagedModelSetups({
...(options.errors ? { errors: options.errors } : {}),
diff --git a/src/workspace-service/models/model-operations.ts b/src/workspace-service/models/model-operations.ts
index c31d25a9..6b2b90ed 100644
--- a/src/workspace-service/models/model-operations.ts
+++ b/src/workspace-service/models/model-operations.ts
@@ -1,3 +1,4 @@
+import { installedStrata } from '../strata/installed.js'
import { flmInstalled } from '../fastflowlm/operations.js'
/**
* The `models.*` operations of the workspace: the catalog, Hub search (Foundry Local's and LiteRT-LM's
@@ -7,6 +8,7 @@ import { flmInstalled } from '../fastflowlm/operations.js'
*/
import { searchCatalog } from './catalog-search.js'
+import { strataCatalog } from '../strata/catalog.js'
import { randomUUID } from 'node:crypto'
import { basename, isAbsolute, join, resolve } from 'node:path'
import { AtomicCoreError } from '@atomic-chat/core'
@@ -99,6 +101,8 @@ export async function modelOperation(
}
)
case 'models.catalog':
+ if (input['engine'] === 'strata')
+ return strataCatalog(d.options, String(input['query'] ?? ''), input['refresh'] === true)
if (input['engine'] === 'litert-lm') return liteRtSearch(liteRtDeps(d), { huggingface: false })
if (isManagedEngine(String(input['engine'] ?? ''))) return managedCatalog(link, String(input['engine']))
return d.catalog.list(
@@ -107,6 +111,8 @@ export async function modelOperation(
input['refresh'] === true
)
case 'models.search':
+ if (input['engine'] === 'strata')
+ return strataCatalog(d.options, String(input['query'] ?? ''), input['refresh'] === true)
if (input['engine'] === 'litert-lm')
return liteRtSearch(liteRtDeps(d), { query: String(input['query'] ?? ''), huggingface: true })
if (input['engine'] === 'foundry-local')
@@ -142,6 +148,7 @@ export async function modelOperation(
[
...(await installedModels(paths.layout)),
...(await flmInstalled(d.options)),
+ ...(await installedStrata(d.options)),
...(await new ModelRegistry(paths.layout, 'mlx').list()).map((m) => ({
id: m.id,
name: String(m.yml.name ?? m.id),
diff --git a/src/workspace-service/service.ts b/src/workspace-service/service.ts
index cfd7094e..6b710d6c 100644
--- a/src/workspace-service/service.ts
+++ b/src/workspace-service/service.ts
@@ -1,3 +1,4 @@
+import { strataOperation } from './strata/operations.js'
import type { FastFlowLmOperation } from '@atomic-chat/core/contracts'
import { flmOperation } from './fastflowlm/operations.js'
import { suspendDownloadingApi } from './snapshot/download-api.js'
@@ -52,6 +53,11 @@ export class WorkspaceService {
private reminders: EmailReminders
private readonly shared = new SnapshotCache(() => this.readCore(), { now: Date.now, maxAgeMs: 1000 })
constructor(private options: WorkspaceServiceOptions) {
+ const catalogUrl = options.env?.['ATOMIC_MODEL_CATALOG_URL']
+ if (catalogUrl && options.env?.['ATC_MODEL_CATALOG_URL'] === undefined) {
+ // Keep the existing workspace override first and share the core override as its fallback.
+ options = this.options = { ...options, env: { ...options.env, ATC_MODEL_CATALOG_URL: catalogUrl } }
+ }
this.features = new WorkspaceFeatureService(
options.paths.atcDir,
options.fetch ?? fetch,
@@ -86,7 +92,10 @@ export class WorkspaceService {
return this.downloads.fastflowlm.mutations.recover().then(() => this.downloads.artifacts.migrate())
}
/** Stops watching; the server calls it on shutdown, and it may be passed on unbound. */
- readonly stop = (): void => this.reminders.stop()
+ readonly stop = (): void => {
+ this.reminders.stop()
+ this.downloads.strata.stop()
+ }
event(name: string, payload: unknown): void {
this.metrics.event(name, payload)
this.loads.event(name, payload)
@@ -115,6 +124,7 @@ export class WorkspaceService {
...(await this.downloads.managed.list()),
...(await this.downloads.foundry.list()),
...(await this.downloads.geniex.journal.list()),
+ ...(await this.downloads.strata.list()),
...(await this.downloads.fastflowlm.journal.list()),
...(await this.downloads.litert.models.list())
)
@@ -177,6 +187,8 @@ export class WorkspaceService {
if (feature !== NOT_CORE) return feature
const cloud = await cloudOperation(link, paths, this.request, operation, input)
if (cloud !== NOT_CORE) return sanitized(cloud)
+ const strata = strataOperation(this.downloads.strata, operation, input)
+ if (strata !== NOT_CORE) return sanitized(await strata)
const flm = await flmOperation(this.options, this.downloads.fastflowlm, operation, input)
if (flm !== NOT_CORE) return flm
const genie = this.downloads.geniex
diff --git a/src/workspace-service/setup-journal.ts b/src/workspace-service/setup-journal.ts
index 168fe46d..3d2a1cf3 100644
--- a/src/workspace-service/setup-journal.ts
+++ b/src/workspace-service/setup-journal.ts
@@ -25,7 +25,7 @@ export interface SetupPlan {
}
export type SetupStage =
- 'queued' | 'downloading' | 'verifying' | 'ready' | 'failed' | 'cancelled' | 'interrupted'
+ 'queued' | 'downloading' | 'verifying' | 'preparing' | 'ready' | 'failed' | 'cancelled' | 'interrupted'
export interface SetupJob {
id: string
@@ -57,7 +57,7 @@ export interface SetupJournalDeps
> {
run: (job: J, worker: Worker) => Promise
}
-const ACTIVE: readonly SetupStage[] = ['queued', 'downloading', 'verifying']
+const ACTIVE: readonly SetupStage[] = ['queued', 'downloading', 'verifying', 'preparing']
/**
* Plan by digest, job by request id, one lane per id. The provider keeps `run`: the bytes, the
diff --git a/src/workspace-service/strata/catalog.test.ts b/src/workspace-service/strata/catalog.test.ts
new file mode 100644
index 00000000..b179b26f
--- /dev/null
+++ b/src/workspace-service/strata/catalog.test.ts
@@ -0,0 +1,66 @@
+import { expect, it, vi } from 'vitest'
+import fixture from '../../../test/fixtures/strata/catalog.json' with { type: 'json' }
+import { fakeCoreLink } from '../../../test/helpers/fake-core-link.js'
+import { tmpDataFolder } from '../../../test/helpers/tmp-data-folder.js'
+import { catalogFixture } from '../../../test/helpers/model-catalog-fixture.js'
+import { defaultConfig } from '../../config/index.js'
+import { strataCatalog } from './catalog.js'
+import { strataPlan } from './plan.js'
+
+it('groups published quants for the core backend and keeps exact variant IDs for plans', async () => {
+ const { paths, cleanup } = tmpDataFolder()
+ const document = catalogFixture()
+ const strata = structuredClone(fixture)
+ const collection = strata.collections['strata-models']
+ const example = collection.entries[0]!
+ const entry = structuredClone(strata.models[example.model as keyof typeof strata.models])
+ const definition = entry.definition
+ const original = definition.variant_id
+ const alternate = 'iq2-xs-dflash2'
+ const cuda = 'windows-x64-cuda13'
+ const metal = 'macos-arm64-metal'
+ const extra = {
+ ...entry,
+ variants: { [alternate]: { family: definition.family } },
+ definition: {
+ ...definition,
+ variant_id: alternate,
+ name: 'Qwen3.8-Flash-Next IQ2_XS',
+ compatible_variants: [cuda],
+ },
+ }
+ const key = 'fixture:strata:alternate'
+ Object.assign(document.models, strata.models, { [key]: extra })
+ Object.assign(document.collections, strata.collections)
+ document.collections['strata-models']!.entries!.push({ ...example, model: key, variant: alternate })
+ const link = fakeCoreLink()
+ link.responses['POST /models/strata/check'] = { verdict: 'ok' }
+ const options = {
+ paths,
+ link,
+ config: defaultConfig(),
+ fetch: vi.fn(async () => Response.json(document)),
+ }
+ try {
+ link.responses['POST /engine-builds/strata/catalog'] = { host_backend_id: metal }
+ expect((await strataCatalog(options, '', false)).models).toMatchObject([
+ { recommended: true, variants: [{ id: original, label: 'IQ3_XXS' }] },
+ ])
+ link.responses['POST /engine-builds/strata/catalog'] = {
+ active: { backend_id: cuda },
+ host_backend_id: metal,
+ }
+ expect((await strataCatalog(options, alternate, false)).models).toMatchObject([
+ {
+ recommended: false,
+ model_id: original,
+ variants: [{ id: original }, { id: alternate, label: 'IQ2_XS' }],
+ },
+ ])
+ expect((await strataPlan(options, 'strata/' + alternate)).variant_id).toBe(alternate)
+ link.responses['POST /engine-builds/strata/catalog'] = { host_backend_id: null }
+ expect((await strataCatalog(options, '', false)).models).toEqual([])
+ } finally {
+ cleanup()
+ }
+})
diff --git a/src/workspace-service/strata/catalog.ts b/src/workspace-service/strata/catalog.ts
new file mode 100644
index 00000000..baf6c9a6
--- /dev/null
+++ b/src/workspace-service/strata/catalog.ts
@@ -0,0 +1,109 @@
+import { projectStrataCollection } from '@atomic-chat/core/client'
+import type {
+ EngineBuildCatalog,
+ StrataCheckResult,
+ StrataModelDescriptor,
+} from '@atomic-chat/core/contracts'
+import type { WorkspaceServiceOptions } from '../service-options.js'
+import { unifiedCatalog } from '../models/unified-catalog.js'
+
+const recommendedQwen = 'iq3-xxs-dflash2'
+const defaults = new Set([recommendedQwen, 'ud-q4-k-xl-mtp', 'ista-2-00bpw-dspark'])
+
+export async function strataCatalogSource(options: WorkspaceServiceOptions, refresh: boolean) {
+ const result = await unifiedCatalog(
+ options.paths.cacheDir,
+ options.fetch ?? fetch,
+ refresh,
+ options.env?.['ATC_MODEL_CATALOG_URL']
+ )
+ return { ...result, descriptors: projectStrataCollection(result.catalog).models }
+}
+
+export async function checkStrataVariant(
+ { link }: WorkspaceServiceOptions,
+ descriptor: StrataModelDescriptor
+) {
+ const check = await link.request('POST', '/models/strata/check', { descriptor })
+ return {
+ id: descriptor.variant_id,
+ name: descriptor.name,
+ category: 'text' as const,
+ description: check.reason ?? '',
+ source: { provider: 'strata', format: 'strata', descriptor, check },
+ }
+}
+
+function groupKey({ family, variant_id: id }: StrataModelDescriptor) {
+ const release = family === 'qwen38' ? /^(unsloth|swift|coder|gyro|nvfp4)-/.exec(id)?.[1] : undefined
+ return release ? `${family}/${release}` : family
+}
+
+const quantSuffix =
+ /(?:UD-)?(?:IQ|Q)\d[\w-]+$|Gyro-\w+$|NVFP4(?:[ -]\w+)?$|(?:ISTA-DAS )?(?:\d+\.\d+ bpw|Coder)$/i
+function quantName({ name, family }: StrataModelDescriptor) {
+ const suffix = name.match(quantSuffix)?.[0]
+ if (family === 'deepseek41' && suffix?.startsWith('UD-')) return `Unsloth ${suffix}`
+ return suffix ?? name
+}
+
+export async function strataCatalog(options: WorkspaceServiceOptions, query: string, refresh: boolean) {
+ const [result, builds] = await Promise.all([
+ strataCatalogSource(options, refresh),
+ options.link.request(
+ 'POST',
+ '/engine-builds/strata/catalog',
+ refresh ? { force: true } : {}
+ ),
+ ])
+ const backend = builds.active?.backend_id ?? builds.host_backend_id
+ const groups = new Map()
+ for (const descriptor of result.descriptors) {
+ if (!backend || !descriptor.compatible_variants.includes(backend)) continue
+ const key = groupKey(descriptor)
+ const group = groups.get(key)
+ if (group) group.push(descriptor)
+ else groups.set(key, [descriptor])
+ }
+ const search = query.trim().toLowerCase()
+ const visible = [...groups.values()].filter((group) =>
+ group.some(({ name, family, variant_id }) =>
+ `${name} ${family} strata/${variant_id}`.toLowerCase().includes(search)
+ )
+ )
+ const checked = await Promise.all(
+ visible.map((group) => Promise.all(group.map((descriptor) => checkStrataVariant(options, descriptor))))
+ )
+ const models = checked.map((group) => {
+ const primary = group.find(({ id }) => defaults.has(id)) ?? group[0]!
+ const { descriptor, check } = primary.source
+ const recommended = backend === 'macos-arm64-metal' && primary.id === recommendedQwen
+ return {
+ model_id: primary.id,
+ name: primary.name,
+ default_variant: primary.id,
+ license: descriptor.license,
+ gated: descriptor.gated,
+ context_length: descriptor.context_length,
+ ...(check.capabilities ?? descriptor.capabilities),
+ recommended,
+ summary: check.verdict === 'insufficient-disk' ? check.reason : null,
+ variants: group.map(({ id, source: { descriptor, check } }) => ({
+ id,
+ label: quantName(descriptor),
+ size_bytes: descriptor.requirements.download_bytes,
+ summary: check.reason ?? '',
+ context_length: descriptor.context_length,
+ ...(check.capabilities ?? descriptor.capabilities),
+ verdict: check,
+ })),
+ }
+ })
+ return {
+ rows: checked.flat(),
+ models: models.sort((a, b) => Number(b.recommended) - Number(a.recommended)),
+ cached: result.source !== 'remote',
+ updated_at: result.fetchedAt ?? 0,
+ ...(result.error ? { error: result.error } : {}),
+ }
+}
diff --git a/src/workspace-service/strata/installed.ts b/src/workspace-service/strata/installed.ts
new file mode 100644
index 00000000..3ab8b6d8
--- /dev/null
+++ b/src/workspace-service/strata/installed.ts
@@ -0,0 +1,33 @@
+import type { StrataMaintenance, StrataPreparationOperation } from '@atomic-chat/core/contracts'
+import { StrataRegistry } from '@atomic-chat/core/models'
+import type { WorkspaceServiceOptions } from '../service-options.js'
+
+export async function installedStrata({ link, paths }: WorkspaceServiceOptions) {
+ const entries = await new StrataRegistry(paths.layout).list()
+ if (!entries.length) return []
+ const [preparations, maintenance] = await Promise.all([
+ link.request('GET', '/strata/preparations'),
+ link.request('GET', '/models/strata/maintenance'),
+ ])
+ return entries.map(({ id, yml, strata }) => {
+ const latest = preparations.findLast(
+ (op) => op.model_id === id && op.source_digest === strata.source_digest
+ )
+ const held = maintenance.some((op) => op.model_id === id && op.state !== 'completed')
+ const status = held
+ ? 'Under maintenance'
+ : latest?.state === 'ready'
+ ? null
+ : latest && ['queued', 'preparing', 'verifying'].includes(latest.state)
+ ? 'Preparing model'
+ : 'Preparation required'
+ return {
+ id,
+ name: String(yml.name ?? id),
+ provider: 'strata',
+ store: 'strata',
+ size_bytes: yml.size_bytes,
+ disabled_reason: status,
+ }
+ })
+}
diff --git a/src/workspace-service/strata/maintenance.ts b/src/workspace-service/strata/maintenance.ts
new file mode 100644
index 00000000..1b488e55
--- /dev/null
+++ b/src/workspace-service/strata/maintenance.ts
@@ -0,0 +1,157 @@
+import { StrataPreparationFailed } from './preparation.js'
+import { lstat, mkdir, rm } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import type { StrataMaintenance as Guard, StrataMaintenanceRequest } from '@atomic-chat/core/contracts'
+import { ModelRegistry } from '@atomic-chat/core/models'
+import { AtcError } from '../../errors/index.js'
+import { readDocument, replaceFile, writeDocument } from '../../terminal-data/index.js'
+import type { WorkspaceServiceOptions } from '../service-options.js'
+
+const route = '/models/strata/maintenance'
+export const STRATA_OWNED_FILE = '.atc-strata.json'
+
+type Mutation = {
+ request: StrataMaintenanceRequest
+ jobId?: string
+ rolledBack?: boolean
+}
+
+async function exists(path: string) {
+ try {
+ const stat = await lstat(path)
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Unsafe Strata model directory.')
+ return true
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
+ throw error
+ }
+}
+
+export class StrataMaintenance {
+ constructor(private readonly options: WorkspaceServiceOptions) {}
+
+ private paths(id: string) {
+ if (!/^[a-z0-9][a-z0-9._-]{0,179}$/i.test(id)) throw new AtcError('ATC_USAGE', 'Invalid Strata model ID.')
+ const { paths } = this.options
+ const provider = paths.layout.provider('strata')
+ return {
+ target: join(provider.modelsDir, id),
+ backup: join(provider.root, 'recovery', id),
+ state: join(paths.atcDir, 'strata-maintenance', id + '.json'),
+ }
+ }
+
+ async pending(modelId: string) {
+ return Boolean(await readDocument(this.paths(modelId).state, null))
+ }
+
+ private async assertOwned(target: string, id: string) {
+ if (!(await exists(target))) throw new AtcError('ATC_USAGE', 'This Strata model is not installed.')
+ const owner = await readDocument<{ model_id: string } | null>(join(target, STRATA_OWNED_FILE), null)
+ if (owner?.model_id !== id)
+ throw new AtcError('ATC_USAGE', 'This Strata model directory is managed by another installation.')
+ }
+
+ private async begin(mutation: Mutation) {
+ const guard = await this.options.link.request('POST', route, mutation.request)
+ if (guard.state !== 'completed' && !guard.ready_to_mutate)
+ throw new Error('Strata did not confirm that the model stopped.')
+ return guard
+ }
+
+ private async finish(guard: Guard, paths: ReturnType) {
+ if (guard.state !== 'completed')
+ await this.options.link.request(
+ 'POST',
+ route + '/' + encodeURIComponent(guard.operation_id) + '/complete',
+ {}
+ )
+ await rm(paths.backup, { recursive: true, force: true })
+ await rm(paths.state, { force: true })
+ }
+
+ async replaceIfNeeded(
+ id: string,
+ jobId: string,
+ digest: string,
+ stage: string,
+ hasDifferentInstall: boolean,
+ prepare: (guard: string) => Promise
+ ) {
+ const p = this.paths(id)
+ let mutation = await readDocument(p.state, null)
+ if (mutation?.request.action === 'remove' || (mutation && mutation.jobId !== jobId))
+ throw new AtcError('ATC_USAGE', 'Finish the previous Strata maintenance operation first.')
+ if (!mutation && !hasDifferentInstall) return false
+ if (!mutation) {
+ await this.assertOwned(p.target, id)
+ mutation = {
+ request: {
+ request_id: 'atc-strata-maintenance-' + crypto.randomUUID(),
+ model_id: id,
+ action: 'replace',
+ target_source_digest: digest,
+ },
+ jobId,
+ }
+ await writeDocument(p.state, mutation)
+ }
+ const guard = await this.begin(mutation)
+ if (mutation.rolledBack || guard.state === 'completed') {
+ await this.finish(guard, p)
+ if (mutation.rolledBack)
+ throw new AtcError('ATC_USAGE', 'The previous Strata installation was restored. Retry to replace it.')
+ return true
+ }
+ const existingDigest = async () =>
+ (await new ModelRegistry(this.options.paths.layout, 'strata').find(id))?.yml.strata?.source_digest
+ try {
+ if ((await existingDigest()) !== digest) {
+ if (!(await exists(p.backup))) {
+ await this.assertOwned(p.target, id)
+ await mkdir(dirname(p.backup), { recursive: true })
+ await replaceFile(p.target, p.backup)
+ }
+ if (await exists(p.target)) throw new Error('Both Strata install and backup need recovery.')
+ await replaceFile(stage, p.target)
+ }
+ await prepare(guard.operation_id)
+ } catch (error) {
+ if (!(error instanceof StrataPreparationFailed)) throw error
+ // A crashed server leaves the guard and both directories in place for the same request ID.
+ // A confirmed preparation failure restores the previous directory while the guard holds load.
+ if (await exists(p.backup)) {
+ if ((await existingDigest()) === digest) await replaceFile(p.target, stage)
+ if (!(await exists(p.target))) await replaceFile(p.backup, p.target)
+ }
+ mutation.rolledBack = true
+ await writeDocument(p.state, mutation)
+ await this.finish(guard, p)
+ throw error
+ }
+ await this.finish(guard, p)
+ return true
+ }
+
+ async remove(id: string) {
+ const p = this.paths(id)
+ let mutation = await readDocument(p.state, null)
+ if (mutation?.request.action === 'replace')
+ throw new AtcError('ATC_USAGE', 'Finish the Strata replacement before deleting this model.')
+ if (!mutation) {
+ await this.assertOwned(p.target, id)
+ mutation = {
+ request: { request_id: 'atc-strata-remove-' + crypto.randomUUID(), action: 'remove', model_id: id },
+ }
+ await writeDocument(p.state, mutation)
+ }
+ const guard = await this.begin(mutation)
+ if (guard.state !== 'completed' && (await exists(p.target))) {
+ if (await exists(p.backup)) throw new Error('Both Strata install and backup need recovery.')
+ await mkdir(dirname(p.backup), { recursive: true })
+ await replaceFile(p.target, p.backup)
+ }
+ await this.finish(guard, p)
+ return { removed: true, model_id: id }
+ }
+}
diff --git a/src/workspace-service/strata/operations.ts b/src/workspace-service/strata/operations.ts
new file mode 100644
index 00000000..2e59c0db
--- /dev/null
+++ b/src/workspace-service/strata/operations.ts
@@ -0,0 +1,23 @@
+import type { WorkspaceInput } from '../../contract/index.js'
+import { NOT_CORE } from '../not-core.js'
+import type { StrataSetups } from './setups.js'
+
+export function strataOperation(setups: StrataSetups, operation: string, input: WorkspaceInput) {
+ switch (operation) {
+ case 'strata.plan':
+ return setups.plan(
+ String(input['model']),
+ input['refresh'] === true,
+ typeof input['import_directory'] === 'string' ? input['import_directory'] : undefined
+ )
+ case 'strata.install':
+ return setups.journal.install(input)
+ case 'strata.cancel':
+ return setups.cancel(String(input['id']))
+ case 'strata.status':
+ return setups.list()
+ case 'models.remove':
+ if (input['store'] === 'strata') return setups.remove(String(input['model_id']))
+ }
+ return NOT_CORE
+}
diff --git a/src/workspace-service/strata/plan.ts b/src/workspace-service/strata/plan.ts
new file mode 100644
index 00000000..b14913d4
--- /dev/null
+++ b/src/workspace-service/strata/plan.ts
@@ -0,0 +1,64 @@
+import { createHash } from 'node:crypto'
+import { isAbsolute } from 'node:path'
+import { strataSourceDigest } from '@atomic-chat/core/client'
+import type { StrataModelDescriptor } from '@atomic-chat/core/contracts'
+import { AtcError } from '../../errors/index.js'
+import type { WorkspaceServiceOptions } from '../service-options.js'
+import { checkStrataVariant, strataCatalogSource } from './catalog.js'
+
+export async function strataPlan(
+ options: WorkspaceServiceOptions,
+ model: string,
+ refresh = false,
+ importDirectory?: string
+) {
+ if (importDirectory && !isAbsolute(importDirectory))
+ throw new AtcError('ATC_USAGE', 'Use an absolute Strata import directory on the server.')
+ const normalized = model.replace(/^strata\//, '')
+ const { descriptors } = await strataCatalogSource(options, refresh)
+ const descriptor = descriptors.find(({ variant_id }) => variant_id === normalized)
+ if (!descriptor)
+ throw new AtcError('ATC_USAGE', 'Choose a variant from atc models catalog --engine strata.')
+ const {
+ source: { check },
+ } = await checkStrataVariant(options, descriptor)
+ const source_digest = await strataSourceDigest(descriptor)
+ const blockers: string[] = []
+ if (check.verdict !== 'ok' && check.verdict !== 'engine-not-installed')
+ blockers.push(check.reason ?? check.verdict)
+ if (!importDirectory && descriptor.gated && !options.env?.['HF_TOKEN'])
+ blockers.push('Accept the model license and set HF_TOKEN on the server.')
+ return {
+ digest: strataPlanDigest(source_digest, importDirectory),
+ source_digest,
+ model_id: descriptor.variant_id,
+ variant_id: descriptor.variant_id,
+ name: descriptor.name,
+ descriptor,
+ check,
+ capabilities: check.capabilities ?? descriptor.capabilities,
+ context_length: descriptor.context_length,
+ license: descriptor.license,
+ variant: { backend: check.compatible_devices?.[0]?.backend ?? '', verdict: check },
+ download_bytes: importDirectory ? 0 : descriptor.requirements.download_bytes,
+ blockers,
+ ...(importDirectory ? { import_directory: importDirectory } : {}),
+ }
+}
+
+export const strataPlanDigest = (sourceDigest: string, importDirectory?: string) =>
+ createHash('sha256')
+ .update(JSON.stringify([sourceDigest, importDirectory ?? null]))
+ .digest('hex')
+
+export type StrataPlan = Awaited>
+
+export function verifyStrataPlan(plan: StrataPlan, descriptor: StrataModelDescriptor, digest: string) {
+ if (
+ descriptor.variant_id !== plan.model_id ||
+ digest !== plan.source_digest ||
+ plan.digest !== strataPlanDigest(digest, plan.import_directory) ||
+ (plan.import_directory && !isAbsolute(plan.import_directory))
+ )
+ throw new Error('The saved Strata model plan no longer matches its pinned inputs.')
+}
diff --git a/src/workspace-service/strata/preparation.ts b/src/workspace-service/strata/preparation.ts
new file mode 100644
index 00000000..4837b234
--- /dev/null
+++ b/src/workspace-service/strata/preparation.ts
@@ -0,0 +1,45 @@
+import { setTimeout } from 'node:timers/promises'
+import type { StrataPreparationOperation, StrataPreparationRequest } from '@atomic-chat/core/contracts'
+import type { CoreLink } from '../../core-link/index.js'
+
+const route = '/strata/preparations'
+export const strataServerStopped = new Error('Strata setup interrupted by server shutdown.')
+export class StrataPreparationFailed extends Error {}
+const idle = new Set(['failed', 'interrupted', 'cancelled'])
+
+export async function prepareStrata(
+ link: CoreLink,
+ input: StrataPreparationRequest,
+ signal: AbortSignal
+): Promise {
+ if (signal.aborted) {
+ if (signal.reason === strataServerStopped) throw signal.reason
+ throw new StrataPreparationFailed('Strata preparation cancelled before it started.')
+ }
+ let operation = await link.request('POST', route, input)
+ const path = route + '/' + encodeURIComponent(operation.operation_id)
+ try {
+ if (operation.state === 'ready') return
+ signal.throwIfAborted()
+ if (idle.has(operation.state))
+ operation = await link.request('POST', path + '/resume', {})
+ for (;;) {
+ if (operation.state === 'ready') return
+ signal.throwIfAborted()
+ if (idle.has(operation.state))
+ throw new StrataPreparationFailed(
+ operation.error?.message ?? `Strata preparation is ${operation.state}.`
+ )
+ await setTimeout(300, undefined, { signal })
+ operation = await link.request('GET', path)
+ }
+ } catch (error) {
+ if (signal.reason === strataServerStopped) throw signal.reason
+ if (signal.aborted && operation.state !== 'ready') {
+ const stopped = await link.request('POST', path + '/cancel', {})
+ if (idle.has(stopped.state)) throw new StrataPreparationFailed('Strata preparation cancelled.')
+ if (stopped.state === 'ready') return
+ }
+ throw error
+ }
+}
diff --git a/src/workspace-service/strata/setups.ts b/src/workspace-service/strata/setups.ts
new file mode 100644
index 00000000..b90e5c4c
--- /dev/null
+++ b/src/workspace-service/strata/setups.ts
@@ -0,0 +1,268 @@
+import { AtomicCoreError } from '@atomic-chat/core'
+import { randomUUID } from 'node:crypto'
+import { lstat, mkdir, rm, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { parseStrataDescriptor, strataSourceDigest } from '@atomic-chat/core/client'
+import type { StrataCheckResult, StrataPreparationOperation } from '@atomic-chat/core/contracts'
+import { ModelRegistry, serializeModelYml } from '@atomic-chat/core/models'
+import { stagedDownloadBytes } from '../../downloads/index.js'
+import type { Downloader } from '../../downloads/index.js'
+import { AtcError } from '../../errors/index.js'
+import { replaceFile, writeDocument } from '../../terminal-data/index.js'
+import { downloadProxy } from '../models/download-proxy.js'
+import type { WorkspaceServiceOptions } from '../service-options.js'
+import { SerialWork } from '../serial.js'
+import { SetupJournal } from '../setup-journal.js'
+import type { SetupJob } from '../setup-journal.js'
+import { strataPlan, verifyStrataPlan } from './plan.js'
+import type { StrataPlan } from './plan.js'
+import {
+ downloadStrataSources,
+ importStrataSources,
+ stagedStrataImportBytes,
+ strataDownloadItems,
+} from './sources.js'
+import { prepareStrata, StrataPreparationFailed, strataServerStopped } from './preparation.js'
+import { STRATA_OWNED_FILE, StrataMaintenance } from './maintenance.js'
+
+type StrataJob = SetupJob & { kind: 'strata-model' }
+type StrataJobView = StrataJob & { task_ids: { download: string }; preparation?: StrataPreparationOperation }
+const taskId = (id: string) => 'atc-strata-download-' + id
+const cancellation = new Error('Strata setup cancelled.')
+
+export class StrataSetups {
+ readonly journal: SetupJournal
+ private readonly lanes = new SerialWork()
+ private stopped = false
+ private readonly controllers = new Map()
+ private readonly maintenance: StrataMaintenance
+
+ constructor(
+ private readonly options: WorkspaceServiceOptions,
+ private readonly downloader: Pick,
+ private readonly ensureEngine?: (id: string) => Promise
+ ) {
+ this.maintenance = new StrataMaintenance(options)
+ this.journal = new SetupJournal({
+ directory: join(options.paths.atcDir, 'strata-model-setups'),
+ kind: 'strata-model',
+ policy: { awaitWorkerOnCancel: true, recordTransferred: true, awaitCancelledBeforeInstall: true },
+ reviewFirst: 'Review a Strata model plan first.',
+ noSuch: 'No such Strata model setup.',
+ hasPlan: (plan) => Boolean(plan.descriptor),
+ isInstalled: (plan) => this.ready(plan.model_id, plan.source_digest),
+ downloader: {
+ cancel: (id) => downloader.cancel(taskId(id)),
+ snapshot: () =>
+ downloader
+ .snapshot()
+ .filter((transfer) => transfer.taskId.startsWith(taskId('')))
+ .map((transfer) => ({ ...transfer, taskId: transfer.taskId.slice(taskId('').length) })),
+ },
+ run: (job, worker) => this.lanes.run(job.plan.model_id, () => this.run(job, worker)),
+ })
+ }
+
+ plan(model: string, refresh: boolean, importDirectory?: string) {
+ return strataPlan(this.options, model, refresh, importDirectory).then((plan) => this.journal.record(plan))
+ }
+
+ async list(): Promise {
+ const jobs = await this.journal.list()
+ if (!jobs.length) return []
+ const operations = await this.options.link.request(
+ 'GET',
+ '/strata/preparations'
+ )
+ return jobs.map((job) => {
+ const prefix = 'atc-strata-prepare-' + job.id
+ const preparation = operations.findLast(
+ (op) =>
+ op.source_digest === job.plan.source_digest &&
+ (op.request_id === prefix || op.request_id.startsWith(prefix + ':'))
+ )
+ return { ...job, task_ids: { download: taskId(job.id) }, ...(preparation ? { preparation } : {}) }
+ })
+ }
+
+ stop() {
+ this.stopped = true
+ for (const [id, controller] of this.controllers) {
+ controller.abort(strataServerStopped)
+ this.downloader.cancel(taskId(id))
+ }
+ }
+
+ async cancel(id: string) {
+ this.controllers.get(id)?.abort(cancellation)
+ const job = await this.journal.cancel(id)
+ const active = (await this.list()).find((item) => item.id === id)?.preparation
+ if (active && ['queued', 'preparing', 'verifying', 'interrupted'].includes(active.state)) {
+ const path = '/strata/preparations/' + encodeURIComponent(active.operation_id) + '/cancel'
+ await this.options.link.request('POST', path, {})
+ }
+ return job
+ }
+
+ async discard(id: string) {
+ await this.cancel(id)
+ return this.journal.remove(id, (job) =>
+ this.lanes.run(job.plan.model_id, async () => {
+ if (await this.maintenance.pending(job.plan.model_id))
+ throw new AtcError('ATC_USAGE', 'Complete Strata maintenance before discarding this setup.')
+ const installed = await new ModelRegistry(this.options.paths.layout, 'strata').find(job.plan.model_id)
+ if (installed?.yml.strata?.source_digest === job.plan.source_digest)
+ throw new AtcError(
+ 'ATC_USAGE',
+ 'The Strata sources are installed. Remove them from Installed models.'
+ )
+ const stage = join(this.options.paths.layout.provider('strata').root, 'transfers', id)
+ await rm(stage, { recursive: true, force: true })
+ })
+ )
+ }
+
+ remove(modelId: string) {
+ return this.lanes.run(modelId, () => this.maintenance.remove(modelId))
+ }
+
+ private async ready(modelId: string, digest: string) {
+ const { link, paths } = this.options
+ const record = await new ModelRegistry(paths.layout, 'strata').find(modelId)
+ if (record?.yml.strata?.source_digest !== digest) return false
+ const check = await link.request('POST', '/models/strata/check', { model_id: modelId })
+ return check.verdict === 'ok' && check.preparation_status === 'ready'
+ }
+
+ private async run(job: StrataJob, worker: { cancelled: boolean }) {
+ if (worker.cancelled || this.stopped) return
+ const controller = new AbortController()
+ this.controllers.set(job.id, controller)
+ const signal = controller.signal
+ const { link, paths, env, config } = this.options
+ const { plan } = job
+ try {
+ const descriptor = parseStrataDescriptor(plan.descriptor)
+ const digest = await strataSourceDigest(descriptor)
+ verifyStrataPlan(plan, descriptor, digest)
+ const stage = join(paths.layout.provider('strata').root, 'transfers', job.id)
+ const modelId = descriptor.variant_id
+ const registry = new ModelRegistry(paths.layout, 'strata')
+ const target = join(paths.layout.provider('strata').modelsDir, modelId)
+ const existing = await registry.find(modelId)
+ if (existing?.yml.strata?.source_digest !== digest) {
+ const check = async () => {
+ const route = '/models/strata/check'
+ const initial = await link.request('POST', route, { descriptor })
+ if (initial.verdict !== 'insufficient-disk') return initial
+ const staged_bytes = plan.import_directory
+ ? await stagedStrataImportBytes(stage, descriptor.files, signal)
+ : await stagedDownloadBytes(strataDownloadItems(stage, descriptor), paths.dataFolder, signal)
+ if (!staged_bytes) return initial
+ try {
+ return await link.request('POST', route, { descriptor, staged_bytes })
+ } catch (error) {
+ // Published core 0.24.2 has the one-field descriptor check.
+ if (
+ error instanceof AtomicCoreError &&
+ error.code === 'INVALID_ARGUMENT' &&
+ error.message === 'Send a Strata descriptor or model_id.'
+ )
+ return initial
+ throw error
+ }
+ }
+ let verdict = await check()
+ if (verdict.verdict === 'engine-not-installed' && this.ensureEngine) {
+ await this.ensureEngine(job.id)
+ verdict = await check()
+ }
+ if (verdict.verdict !== 'ok') throw new Error(verdict.reason ?? verdict.verdict)
+ if (!plan.import_directory && descriptor.gated && !env?.['HF_TOKEN'])
+ throw new Error('Accept the model license and set HF_TOKEN on the server.')
+ await this.journal.step(job, worker, 'downloading')
+ signal.throwIfAborted()
+ await mkdir(stage, { recursive: true, mode: 0o700 })
+ if (plan.import_directory)
+ await importStrataSources(plan.import_directory, stage, descriptor.files, signal)
+ else
+ await downloadStrataSources(
+ this.downloader.download.bind(this.downloader),
+ taskId(job.id),
+ stage,
+ descriptor,
+ downloadProxy(config),
+ env?.['HF_TOKEN']
+ )
+ signal.throwIfAborted()
+ // core-boundary: model.yml — acquisition metadata, written only once each staged input is verified
+ const marker = join(stage, 'model.yml')
+ const temporary = marker + '.' + randomUUID() + '.tmp'
+ try {
+ await writeFile(
+ temporary,
+ serializeModelYml({
+ name: descriptor.name,
+ model_path: `strata/models/${modelId}/${descriptor.inputs.weights[0]!}`,
+ size_bytes: descriptor.requirements.download_bytes,
+ strata: { schema_version: 1, source_digest: digest, descriptor },
+ }),
+ { mode: 0o600 }
+ )
+ await writeDocument(join(stage, STRATA_OWNED_FILE), { model_id: modelId })
+ await replaceFile(temporary, marker)
+ } finally {
+ await rm(temporary, { force: true })
+ }
+ }
+ signal.throwIfAborted()
+ await this.journal.step(job, worker, 'preparing')
+ const prepare = (guard?: string) =>
+ prepareStrata(
+ link,
+ {
+ request_id: 'atc-strata-prepare-' + job.id + (guard ? ':' + guard : ''),
+ model_id: modelId,
+ source_digest: digest,
+ ...(guard ? { maintenance_id: guard } : {}),
+ },
+ signal
+ )
+ const replaced = await this.maintenance.replaceIfNeeded(
+ modelId,
+ job.id,
+ digest,
+ stage,
+ !!existing && existing.yml.strata?.source_digest !== digest,
+ prepare
+ )
+ if (!replaced) {
+ if (!existing) {
+ const occupied = await lstat(target).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return false
+ throw error
+ }
+ )
+ if (occupied) throw new AtcError('ATC_USAGE', 'The Strata model directory is occupied.')
+ await mkdir(dirname(target), { recursive: true })
+ await replaceFile(stage, target)
+ }
+ await prepare()
+ }
+ if (!(await this.ready(modelId, digest)))
+ throw new StrataPreparationFailed('Strata readiness could not be verified.')
+ await this.journal.write(job, 'ready')
+ } catch (error) {
+ await this.journal.step(
+ job,
+ worker,
+ signal.reason === strataServerStopped ? 'interrupted' : 'failed',
+ error
+ )
+ } finally {
+ this.controllers.delete(job.id)
+ }
+ }
+}
diff --git a/src/workspace-service/strata/sources.ts b/src/workspace-service/strata/sources.ts
new file mode 100644
index 00000000..22d27bc9
--- /dev/null
+++ b/src/workspace-service/strata/sources.ts
@@ -0,0 +1,107 @@
+import { randomUUID } from 'node:crypto'
+import { constants, createWriteStream } from 'node:fs'
+import { mkdir, open, realpath, rm } from 'node:fs/promises'
+import { dirname, isAbsolute, join, relative, sep } from 'node:path'
+import { pipeline } from 'node:stream/promises'
+import type { StrataFile, StrataModelDescriptor } from '@atomic-chat/core/contracts'
+import { verifyDownloadedFile } from '../../downloads/index.js'
+import type { Downloader, ProxyConfig } from '../../downloads/index.js'
+import { replaceFile } from '../../terminal-data/index.js'
+import { hubAuthorized } from '../models/hub-fetch.js'
+
+const HUB = 'https://huggingface.co'
+
+export function strataDownloadItems(
+ destination: string,
+ descriptor: StrataModelDescriptor,
+ proxy?: ProxyConfig | null
+) {
+ return descriptor.files.map((file) => {
+ const source = descriptor.sources.find((candidate) => candidate.id === file.source)!
+ const path = file.source_path.split('/').map(encodeURIComponent).join('/')
+ const url =
+ source.host === 'huggingface'
+ ? `${HUB}/${source.repo}/resolve/${source.revision}/${path}`
+ : `https://raw.githubusercontent.com/${source.repo}/${source.revision}/${path}`
+ return {
+ url,
+ size: file.size,
+ sha256: file.sha256,
+ save_path: join(destination, file.path),
+ ...(proxy ? { proxy } : {}),
+ }
+ })
+}
+
+/** The descriptor has been validated by the core. Only the server's downloader receives the token. */
+export function downloadStrataSources(
+ download: Downloader['download'],
+ id: string,
+ destination: string,
+ descriptor: StrataModelDescriptor,
+ proxy: ProxyConfig | null,
+ token?: string
+) {
+ return download(id, strataDownloadItems(destination, descriptor, proxy), {
+ resume: true,
+ wrapFetch: (fetch) => hubAuthorized(fetch, HUB, token),
+ })
+}
+
+async function verifiedImport(file: StrataFile, target: string, signal: AbortSignal) {
+ signal.throwIfAborted()
+ const verified = await verifyDownloadedFile(file, target, undefined, signal).then(
+ () => true,
+ () => false
+ )
+ signal.throwIfAborted()
+ return verified
+}
+
+export async function stagedStrataImportBytes(
+ destination: string,
+ files: readonly StrataFile[],
+ signal: AbortSignal
+) {
+ let bytes = 0
+ for (const file of files)
+ if (await verifiedImport(file, join(destination, file.path), signal)) bytes += file.size
+ return bytes
+}
+
+/** Stage an independent, verified copy. An imported directory remains owned by its original user. */
+export async function importStrataSources(
+ directory: string,
+ destination: string,
+ files: readonly StrataFile[],
+ signal: AbortSignal
+): Promise {
+ const root = await realpath(directory)
+ for (const file of files) {
+ const target = join(destination, file.path)
+ if (await verifiedImport(file, target, signal)) continue
+ const source = await realpath(join(root, file.path))
+ const inside = relative(root, source)
+ if (isAbsolute(inside) || inside === '..' || inside.startsWith('..' + sep))
+ throw new Error(`Strata import file escapes the selected directory: ${file.path}`)
+ const handle = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | constants.O_NONBLOCK)
+ const temporary = target + '.' + randomUUID() + '.tmp'
+ try {
+ const stat = await handle.stat()
+ if (!stat.isFile() || stat.size !== file.size)
+ throw new Error(`Strata import file has the wrong size or type: ${file.path}`)
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 })
+ await pipeline(
+ handle.createReadStream({ autoClose: false, end: file.size - 1 }),
+ createWriteStream(temporary, { flags: 'wx', mode: 0o600 }),
+ { signal }
+ )
+ await verifyDownloadedFile(file, temporary, undefined, signal)
+ signal.throwIfAborted()
+ await replaceFile(temporary, target)
+ } finally {
+ await handle.close()
+ await rm(temporary, { force: true })
+ }
+ }
+}
diff --git a/src/workspace-service/strata/strata-downloads.test.ts b/src/workspace-service/strata/strata-downloads.test.ts
new file mode 100644
index 00000000..8393cfca
--- /dev/null
+++ b/src/workspace-service/strata/strata-downloads.test.ts
@@ -0,0 +1,106 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { pathToFileURL } from 'node:url'
+import { dirname, join } from 'node:path'
+import { expect, it, vi } from 'vitest'
+import { parseStrataDescriptor } from '@atomic-chat/core/client'
+import type { Downloader } from '../../downloads/index.js'
+import catalog from '../../../test/fixtures/strata/catalog.json' with { type: 'json' }
+import { defaultConfig } from '../../config/index.js'
+import { catalogFixture } from '../../../test/helpers/model-catalog-fixture.js'
+import { fakeCoreLink } from '../../../test/helpers/fake-core-link.js'
+import { tmpDataFolder } from '../../../test/helpers/tmp-data-folder.js'
+import { StrataSetups } from './setups.js'
+import { downloadStrataSources } from './sources.js'
+
+const descriptor = parseStrataDescriptor(catalog.models['strata-qwen38-iq3-xxs'].definition)
+
+it('passes every pinned Strata input to the resumable server downloader', async () => {
+ const download = vi.fn()
+ await downloadStrataSources(download, 'install-1', '/staging', descriptor, null, 'fixture-token')
+ const [id, files, options] = download.mock.calls[0]!
+ expect(id).toBe('install-1')
+ expect(options?.resume).toBe(true)
+ expect(files).toHaveLength(descriptor.files.length)
+ for (const [index, file] of descriptor.files.entries()) {
+ const source = descriptor.sources.find((item) => item.id === file.source)!
+ expect(files[index]).toMatchObject({
+ sha256: file.sha256,
+ size: file.size,
+ save_path: join('/staging', file.path),
+ })
+ expect(files[index]!.url).toContain(source.revision)
+ }
+ const server = vi.fn(async (url) =>
+ String(url).startsWith('https://huggingface.co')
+ ? new Response(null, { status: 302, headers: { location: 'https://cdn.example/payload' } })
+ : new Response(null)
+ )
+ await options!.wrapFetch!(server)(new URL('https://huggingface.co/source'), { method: 'GET' })
+ expect(new Headers(server.mock.calls[0]![1]?.headers).get('authorization')).toBe('Bearer fixture-token')
+ expect(new Headers(server.mock.calls[1]![1]?.headers).get('authorization')).toBeNull()
+ expect(JSON.stringify(files)).not.toContain('fixture-token')
+})
+
+it('continues a cancelled network transfer with the saved revisions after the catalog changes', async () => {
+ const { paths, cleanup } = tmpDataFolder()
+ const link = fakeCoreLink()
+ link.responses['GET /strata/preparations'] = []
+ let tightDisk = false
+ link.responses['POST /models/strata/check'] = (request: unknown) =>
+ tightDisk && (request as { staged_bytes?: number }).staged_bytes !== 5
+ ? { verdict: 'insufficient-disk', reason: 'Room for the remaining sources only.' }
+ : { verdict: 'ok' }
+ const path = join(paths.dataFolder, 'catalog.json')
+ const options = {
+ paths,
+ link,
+ config: defaultConfig(),
+ env: { ATC_MODEL_CATALOG_URL: pathToFileURL(path).href },
+ }
+ let stop: (() => void) | undefined
+ const download = vi.fn(
+ () =>
+ new Promise((_resolve, reject) => {
+ stop = () => reject(new Error('Download cancelled'))
+ })
+ )
+ const cancel = vi.fn(() => {
+ stop?.()
+ return true
+ })
+ const setups = new StrataSetups(options, { download, cancel, snapshot: () => [] })
+ try {
+ const catalogDoc = catalogFixture()
+ Object.assign(catalogDoc.models, catalog.models)
+ Object.assign(catalogDoc.collections, catalog.collections)
+ await mkdir(paths.dataFolder, { recursive: true })
+ await writeFile(path, JSON.stringify(catalogDoc))
+ const plan = await setups.plan(descriptor.variant_id, false)
+ const input = { request_id: 'same-job', plan_digest: plan.digest }
+ await setups.journal.install(input)
+ await vi.waitFor(() => expect(download).toHaveBeenCalledOnce())
+ expect(await setups.cancel(input.request_id)).toMatchObject({ stage: 'cancelled' })
+ const files = download.mock.calls[0]![1]
+ const draft = files.find(({ save_path }) => save_path.endsWith(join('draft', 'config.json')))!
+ await mkdir(dirname(draft.save_path), { recursive: true })
+ await writeFile(draft.save_path + '.tmp', 'abcde')
+ await writeFile(draft.save_path + '.url', draft.url)
+ const bad = files.find(({ save_path }) => save_path.endsWith('profile.bin'))!
+ await writeFile(bad.save_path + '.tmp', 'bad')
+ await writeFile(bad.save_path + '.url', bad.url + '?wrong-revision')
+ tightDisk = true
+ await writeFile(path, JSON.stringify(catalogFixture()))
+ await setups.journal.install(input)
+ await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(2))
+ expect(link.calls.at(-1)).toMatchObject({
+ path: '/models/strata/check',
+ body: { descriptor, staged_bytes: 5 },
+ })
+ expect(download.mock.calls[0]?.slice(0, 2)).toEqual(download.mock.calls[1]?.slice(0, 2))
+ expect(cancel).toHaveBeenCalledWith('atc-strata-download-same-job')
+ await setups.cancel(input.request_id)
+ } finally {
+ setups.stop()
+ cleanup()
+ }
+})
diff --git a/src/workspace-service/strata/strata-import.test.ts b/src/workspace-service/strata/strata-import.test.ts
new file mode 100644
index 00000000..f82eb9ce
--- /dev/null
+++ b/src/workspace-service/strata/strata-import.test.ts
@@ -0,0 +1,37 @@
+import { createHash } from 'node:crypto'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { expect, it } from 'vitest'
+import type { StrataFile } from '@atomic-chat/core/contracts'
+import { importStrataSources, stagedStrataImportBytes } from './sources.js'
+
+const file: StrataFile = {
+ path: 'model.gguf',
+ source_path: 'model.gguf',
+ source: 'fixture',
+ role: 'weights',
+ size: 4,
+ sha256: createHash('sha256').update('good').digest('hex'),
+}
+
+it('refuses a corrupt shard and installs only a verified copy, leaving the import intact', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'atc-strata-import-'))
+ try {
+ const from = join(root, file.path)
+ const target = join(root, 'staging')
+ const signal = new AbortController().signal
+ await writeFile(from, 'badd')
+ await expect(importStrataSources(root, target, [file], signal)).rejects.toThrow(/hash verification/i)
+ await expect(readFile(join(target, file.path))).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(await readFile(from, 'utf8')).toBe('badd')
+ await writeFile(from, 'good')
+ await importStrataSources(root, target, [file], signal)
+ expect(await stagedStrataImportBytes(target, [file], signal)).toBe(file.size)
+ await writeFile(join(target, file.path), 'badd')
+ expect(await stagedStrataImportBytes(target, [file], signal)).toBe(0)
+ expect(await readFile(from, 'utf8')).toBe('good')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
diff --git a/src/workspace-service/strata/strata-maintenance.test.ts b/src/workspace-service/strata/strata-maintenance.test.ts
new file mode 100644
index 00000000..c709b679
--- /dev/null
+++ b/src/workspace-service/strata/strata-maintenance.test.ts
@@ -0,0 +1,78 @@
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { ModelRegistry, serializeModelYml } from '@atomic-chat/core/models'
+import { parseStrataDescriptor, strataSourceDigest } from '@atomic-chat/core/client'
+import { expect, it, vi } from 'vitest'
+import excerpt from '../../../test/fixtures/strata/catalog.json' with { type: 'json' }
+import { defaultConfig } from '../../config/index.js'
+import { writeDocument } from '../../terminal-data/index.js'
+import { fakeCoreLink } from '../../../test/helpers/fake-core-link.js'
+import { tmpDataFolder } from '../../../test/helpers/tmp-data-folder.js'
+import { STRATA_OWNED_FILE, StrataMaintenance } from './maintenance.js'
+import { StrataPreparationFailed } from './preparation.js'
+
+it('keeps the guard and backup on an uncertain core response, then restores the previous installation on a confirmed failure', async () => {
+ const { paths, cleanup } = tmpDataFolder()
+ try {
+ const link = fakeCoreLink()
+ const old = parseStrataDescriptor(excerpt.models['strata-qwen38-iq3-xxs'].definition)
+ const next = { ...old, name: old.name + ' updated' }
+ const model = old.variant_id
+ const original = await strataSourceDigest(old)
+ const digest = await strataSourceDigest(next)
+ const modelPath = `strata/models/${model}/${old.inputs.weights[0]!}`
+ const root = paths.layout.provider('strata')
+ const target = join(root.modelsDir, model)
+ const stage = join(root.root, 'fixture-stage')
+ const backup = join(root.root, 'recovery', model)
+ const registry = new ModelRegistry(paths.layout, 'strata')
+ await registry.write(model, {
+ model_path: modelPath,
+ strata: { schema_version: 1, descriptor: old, source_digest: original },
+ })
+ await writeDocument(join(target, STRATA_OWNED_FILE), { model_id: model })
+ await writeFile(join(target, 'previous'), 'old')
+ await mkdir(stage, { recursive: true })
+ await writeDocument(join(stage, STRATA_OWNED_FILE), { model_id: model })
+ // core-boundary: model.yml — the staged registration for the replacement fixture
+ await writeFile(
+ join(stage, 'model.yml'),
+ serializeModelYml({
+ model_path: modelPath,
+ strata: { schema_version: 1, descriptor: next, source_digest: digest },
+ })
+ )
+ link.responses['POST /models/strata/maintenance'] = {
+ operation_id: 'guard-1',
+ state: 'held',
+ ready_to_mutate: true,
+ }
+ const complete = vi.fn(async () => {
+ expect(await readFile(join(target, 'previous'), 'utf8')).toBe('old')
+ return { state: 'completed' }
+ })
+ link.responses['POST /models/strata/maintenance/guard-1/complete'] = complete
+ const options = { link, paths, config: defaultConfig() }
+ const attempt = new StrataMaintenance(options)
+ await expect(
+ attempt.replaceIfNeeded(model, 'job', digest, stage, true, async (id) => {
+ expect(id).toBe('guard-1')
+ throw new Error('Control connection lost')
+ })
+ ).rejects.toThrow('Control connection lost')
+ await expect(readFile(join(backup, 'previous'), 'utf8')).resolves.toBe('old')
+ expect(complete).not.toHaveBeenCalled()
+ await expect(
+ new StrataMaintenance(options).replaceIfNeeded(model, 'job', digest, stage, false, async () => {
+ throw new StrataPreparationFailed('Preparation failed')
+ })
+ ).rejects.toThrow('Preparation failed')
+ expect(complete).toHaveBeenCalledOnce()
+ expect(await attempt.pending(model)).toBe(false)
+ const requests = link.calls.filter(({ path }) => path === '/models/strata/maintenance')
+ expect(requests).toHaveLength(2)
+ expect(requests[0]?.body).toEqual(requests[1]?.body)
+ } finally {
+ cleanup()
+ }
+})
diff --git a/src/workspace-service/strata/strata-preparation.test.ts b/src/workspace-service/strata/strata-preparation.test.ts
new file mode 100644
index 00000000..03d7ae26
--- /dev/null
+++ b/src/workspace-service/strata/strata-preparation.test.ts
@@ -0,0 +1,33 @@
+import { expect, it, vi } from 'vitest'
+import { fakeCoreLink } from '../../../test/helpers/fake-core-link.js'
+import { prepareStrata, StrataPreparationFailed, strataServerStopped } from './preparation.js'
+
+const request = { request_id: 'prep', model_id: 'model', source_digest: 'a'.repeat(64) }
+const opened = { ...request, operation_id: 'job', state: 'preparing', revision: 1, error: null }
+
+it('confirms the preparation stopped when cancellation crosses the core begin response', async () => {
+ const link = fakeCoreLink()
+ const controller = new AbortController()
+ link.responses['POST /strata/preparations'] = () => {
+ controller.abort()
+ return opened
+ }
+ link.responses['POST /strata/preparations/job/cancel'] = { ...opened, state: 'cancelled', revision: 2 }
+ await expect(prepareStrata(link, request, controller.signal)).rejects.toBeInstanceOf(
+ StrataPreparationFailed
+ )
+ expect(link.calls.at(-1)).toMatchObject({ method: 'POST', path: '/strata/preparations/job/cancel' })
+})
+
+it('leaves the core operation intact when the atc process stops following it', async () => {
+ const link = fakeCoreLink()
+ const controller = new AbortController()
+ const cancelled = vi.fn()
+ link.responses['POST /strata/preparations/job/cancel'] = cancelled
+ link.responses['POST /strata/preparations'] = () => {
+ controller.abort(strataServerStopped)
+ return opened
+ }
+ await expect(prepareStrata(link, request, controller.signal)).rejects.toBe(strataServerStopped)
+ expect(cancelled).not.toHaveBeenCalled()
+})
diff --git a/src/workspace-service/strata/strata-recovery.test.ts b/src/workspace-service/strata/strata-recovery.test.ts
new file mode 100644
index 00000000..d7453c5f
--- /dev/null
+++ b/src/workspace-service/strata/strata-recovery.test.ts
@@ -0,0 +1,99 @@
+import { createHash } from 'node:crypto'
+import { mkdir, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { expect, it, vi } from 'vitest'
+import catalogExcerpt from '../../../test/fixtures/strata/catalog.json' with { type: 'json' }
+import { defaultConfig } from '../../config/index.js'
+import { WorkspaceService } from '../index.js'
+import { catalogFixture } from '../../../test/helpers/model-catalog-fixture.js'
+import { fakeCoreLink } from '../../../test/helpers/fake-core-link.js'
+import { tmpDataFolder } from '../../../test/helpers/tmp-data-folder.js'
+
+it('resumes the pinned plan after restart and reports the same preparation without transferring again', async () => {
+ const { paths, cleanup } = tmpDataFolder('strata-recovery-')
+ const link = fakeCoreLink()
+ const catalogPath = join(paths.dataFolder, 'catalog.json')
+ const directory = join(paths.dataFolder, 'import')
+ const descriptor = structuredClone(catalogExcerpt.models['strata-qwen38-iq3-xxs'].definition)
+ const bytes = Buffer.from('fixture')
+ const fileHash = createHash('sha256').update(bytes).digest('hex')
+ for (const file of descriptor.files) Object.assign(file, { size: bytes.length, sha256: fileHash })
+ descriptor.requirements.download_bytes = bytes.length * descriptor.files.length
+ const offline = vi.fn(async () => {
+ throw new Error('Unexpected model download')
+ })
+ const options = {
+ link,
+ paths,
+ config: defaultConfig(),
+ env: { ATOMIC_MODEL_CATALOG_URL: pathToFileURL(catalogPath).href },
+ fetch: offline,
+ }
+ let operation: Record | undefined
+ link.responses['POST /models/strata/check'] = () => ({
+ verdict: 'ok',
+ preparation_status: operation?.['state'] === 'ready' ? 'ready' : 'files-ready',
+ })
+ link.responses['POST /strata/preparations'] = (request: unknown) => {
+ operation ??= { ...(request as object), operation_id: 'prep-1', state: 'preparing', revision: 1 }
+ return operation
+ }
+ link.responses['GET /strata/preparations'] = () => (operation ? [operation] : [])
+ link.responses['GET /strata/preparations/prep-1'] = () => operation
+ link.responses['POST /strata/preparations/prep-1/resume'] = () =>
+ (operation = { ...operation, state: 'ready', revision: 3 })
+ link.responses['GET /models/strata/maintenance'] = []
+ let first: WorkspaceService | undefined
+ let second: WorkspaceService | undefined
+ try {
+ const catalog = catalogFixture()
+ Object.assign(catalog.models, catalogExcerpt.models)
+ Object.assign(catalog.collections, catalogExcerpt.collections)
+ const entry = catalog.models['strata-qwen38-iq3-xxs']!
+ entry.definition = descriptor
+ await mkdir(paths.dataFolder, { recursive: true })
+ await writeFile(catalogPath, JSON.stringify(catalog))
+ for (const file of descriptor.files) {
+ const path = join(directory, file.path)
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, bytes)
+ }
+ first = new WorkspaceService(options)
+ const model = descriptor.variant_id
+ const plan = (await first.execute('strata.plan', { model, import_directory: directory })) as {
+ digest: string
+ }
+ const input = { request_id: 'fixture-install', plan_digest: plan.digest }
+ await first.execute('strata.install', input)
+ await vi.waitFor(() => expect(operation).toMatchObject({ state: 'preparing' }))
+ await expect(first.execute('models.installed')).resolves.toMatchObject([
+ { id: model, store: 'strata', disabled_reason: 'Preparing model' },
+ ])
+ first.stop()
+ await vi.waitFor(async () =>
+ expect(await first!.execute('strata.status')).toMatchObject([{ stage: 'interrupted' }])
+ )
+ operation = { ...operation, state: 'interrupted', revision: 2 }
+ await writeFile(catalogPath, JSON.stringify(catalogFixture()))
+ second = new WorkspaceService(options)
+ expect(await second.execute('strata.status')).toMatchObject([
+ { id: input.request_id, stage: 'interrupted' },
+ ])
+ await second.execute('strata.install', input)
+ await vi.waitFor(async () =>
+ expect(await second!.execute('strata.status')).toMatchObject([
+ { id: input.request_id, stage: 'ready', preparation: { operation_id: 'prep-1', revision: 3 } },
+ ])
+ )
+ await expect(second.execute('models.installed')).resolves.toMatchObject([
+ { id: model, store: 'strata', disabled_reason: null },
+ ])
+ expect(offline).not.toHaveBeenCalled()
+ expect(link.calls.filter(({ path }) => path === '/strata/preparations/prep-1/resume')).toHaveLength(1)
+ } finally {
+ first?.stop()
+ second?.stop()
+ cleanup()
+ }
+})
diff --git a/src/workspace-view/catalog/catalog-formats.test.ts b/src/workspace-view/catalog/catalog-formats.test.ts
index ff9dc9f4..f2bd5a0c 100644
--- a/src/workspace-view/catalog/catalog-formats.test.ts
+++ b/src/workspace-view/catalog/catalog-formats.test.ts
@@ -16,6 +16,7 @@ describe('catalog formats', () => {
['litert-lm', 'litert'],
['geniex', 'geniex'],
['fastflowlm', 'fastflowlm'],
+ ['strata', 'strata'],
['an-engine-of-tomorrow', 'gguf'],
])('%s runs the %s format', (engine, format) => {
expect(engineCatalogFormat(engine)).toBe(format)
@@ -49,12 +50,14 @@ describe('catalog formats', () => {
litert: 'LiteRT-LM',
geniex: 'GenieX',
fastflowlm: 'FastFlowLM',
+ strata: 'Strata',
})
expect(FORMAT_ENGINE).toEqual({
foundry: 'foundry-local',
litert: 'litert-lm',
geniex: 'geniex',
fastflowlm: 'fastflowlm',
+ strata: 'strata',
})
})
})
diff --git a/src/workspace-view/catalog/catalog-formats.ts b/src/workspace-view/catalog/catalog-formats.ts
index cd021eda..db996b0f 100644
--- a/src/workspace-view/catalog/catalog-formats.ts
+++ b/src/workspace-view/catalog/catalog-formats.ts
@@ -7,7 +7,8 @@
import { ENGINE_KINDS } from '@atomic-chat/core/contracts'
import type { EngineId } from '@atomic-chat/core/contracts'
-export type CatalogFormat = 'gguf' | 'mlx' | 'safetensors' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm'
+export type CatalogFormat =
+ 'gguf' | 'mlx' | 'safetensors' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm' | 'strata'
export const CATALOG_FORMAT_LABELS: Record = {
gguf: 'GGUF',
@@ -17,6 +18,7 @@ export const CATALOG_FORMAT_LABELS: Record = {
litert: 'LiteRT-LM',
geniex: 'GenieX',
fastflowlm: 'FastFlowLM',
+ strata: 'Strata',
}
/** The engine whose own catalog (`models.search --engine`) a variant format reads. */
@@ -25,6 +27,7 @@ export const FORMAT_ENGINE: Partial> = {
litert: 'litert-lm',
geniex: 'geniex',
fastflowlm: 'fastflowlm',
+ strata: 'strata',
}
/**
diff --git a/src/workspace-view/downloads/download-controls.ts b/src/workspace-view/downloads/download-controls.ts
index af27bea5..8ebdbbcb 100644
--- a/src/workspace-view/downloads/download-controls.ts
+++ b/src/workspace-view/downloads/download-controls.ts
@@ -1,11 +1,13 @@
import type { DownloadRow } from './downloads.js'
-export type DownloadOwner = 'setup' | 'artifacts' | 'managed' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm'
+export type DownloadOwner =
+ 'setup' | 'artifacts' | 'managed' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm' | 'strata'
/** The services whose jobs resume by installing their plan again, by job kind. */
const PLAN_OWNERS: Record = {
'managed-model': 'managed',
'foundry-model': 'foundry',
'geniex-model': 'geniex',
'fastflowlm-model': 'fastflowlm',
+ 'strata-model': 'strata',
'litert-model': 'litert',
}
export function downloadOwner(job: Record): DownloadOwner | null {
@@ -20,8 +22,13 @@ export const downloadHeld = (state: string) => /paused|cancelled/.test(state)
/** What every client calls a download's state: one held by a person is Paused, never "cancelled". */
export function downloadStateLabel(state: string, completed = false): string {
if (completed) return 'Downloaded'
+ if (state === 'preparing') return 'Preparing model'
return downloadHeld(state) ? 'Paused' : state.replaceAll('_', ' ')
}
+export function strataPreparationNotice(job: Record, state: string): string | undefined {
+ if (job['kind'] === 'strata-model' && state === 'preparing')
+ return 'Preparing Strata model. This can take a few minutes.'
+}
export function downloadControl(job: DownloadRow, action: 'pause' | 'resume') {
const owner = downloadOwner(job)
if (!owner) return null
diff --git a/src/workspace-view/downloads/downloads.ts b/src/workspace-view/downloads/downloads.ts
index 7cac5239..c3510188 100644
--- a/src/workspace-view/downloads/downloads.ts
+++ b/src/workspace-view/downloads/downloads.ts
@@ -76,13 +76,15 @@ export function downloadRows(
done +=
Number(record(plan['engine'])['download_size'] ?? 0) + Number(record(plan['model'])['size'] ?? 0)
if (['verifying', 'registering'].includes(progressPhase) || completed.has(phase)) done = size
+ const preparing = phase === 'preparing' && job['kind'] === 'strata-model'
+ const preparation = record(job['preparation'])
result.push({
...job,
id,
// What both lists name the row by: a store job's repository, a Foundry Local job's variant.
model_id: job['model_id'] ?? plan['variant_id'] ?? plan['repository'] ?? plan['model_id'],
- total: size,
- transferred: done,
+ total: preparing ? Number(preparation['total_bytes'] ?? 0) : size,
+ transferred: preparing ? Number(preparation['completed_bytes'] ?? 0) : done,
state: phase || 'queued',
completed: completed.has(phase),
owner: plan['category'] ? 'artifacts' : 'setup',
diff --git a/src/workspace-view/engines/engine-order.ts b/src/workspace-view/engines/engine-order.ts
index cb430372..1c35b9c7 100644
--- a/src/workspace-view/engines/engine-order.ts
+++ b/src/workspace-view/engines/engine-order.ts
@@ -19,6 +19,7 @@ const ORDER = [
'litert-lm',
'geniex',
'fastflowlm',
+ 'strata',
] as const
const NAMES: Readonly> = {
@@ -33,6 +34,7 @@ const NAMES: Readonly> = {
'litert-lm': 'LiteRT-LM',
'geniex': 'GenieX',
'fastflowlm': 'FastFlowLM',
+ 'strata': 'Strata',
'sd-cpp': 'stable-diffusion.cpp',
'audio-cpp': 'audio.cpp',
}
@@ -65,8 +67,9 @@ export function orderEngines(ids: readonly T[]): T[] {
*/
export function engineFamily(
id: string
-): 'llamacpp' | 'managed' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm' | 'build' {
+): 'llamacpp' | 'managed' | 'foundry' | 'litert' | 'geniex' | 'fastflowlm' | 'strata' | 'build' {
if (id === 'foundry-local') return 'foundry'
+ if (id === 'strata') return 'strata'
if (id === 'fastflowlm') return 'fastflowlm'
if (id === 'geniex') return 'geniex'
if (id === 'litert-lm') return 'litert'
diff --git a/src/workspace-view/index.ts b/src/workspace-view/index.ts
index c5f02d02..e5a50ac0 100644
--- a/src/workspace-view/index.ts
+++ b/src/workspace-view/index.ts
@@ -111,6 +111,7 @@ export {
downloadStopped,
downloadHeld,
downloadStateLabel,
+ strataPreparationNotice,
downloadControl,
} from './downloads/download-controls.js'
export type { DownloadOwner } from './downloads/download-controls.js'
diff --git a/src/workspace-view/setup/connection-model.ts b/src/workspace-view/setup/connection-model.ts
index 16137cc6..4058f2a5 100644
--- a/src/workspace-view/setup/connection-model.ts
+++ b/src/workspace-view/setup/connection-model.ts
@@ -36,6 +36,7 @@ const VARIANT_JOBS: Record = {
'litert-model': 'litert-lm',
'geniex-model': 'geniex',
'fastflowlm-model': 'fastflowlm',
+ 'strata-model': 'strata',
}
export function connectionDownloadTarget(job: unknown) {
diff --git a/test/contract/strata-commands.test.ts b/test/contract/strata-commands.test.ts
new file mode 100644
index 00000000..7de0fe85
--- /dev/null
+++ b/test/contract/strata-commands.test.ts
@@ -0,0 +1,76 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { expect, it } from 'vitest'
+import { atcPathsFor } from '../../src/config/index.js'
+import catalogExcerpt from '../fixtures/strata/catalog.json' with { type: 'json' }
+import { catalogFixture } from '../helpers/model-catalog-fixture.js'
+import { testRun } from '../helpers/test-context.js'
+import { workspaceServer } from '../helpers/workspace-server.js'
+
+it('uses the server’s Strata catalog, host verdicts and revisioned engine settings', async () => {
+ const t = testRun()
+ const paths = atcPathsFor(t.io.env['ATC_DATA_FOLDER']!)
+ const { link } = t
+ link.responses['POST /engines/versions'] = { engines: [{ engine: 'strata', kind: 'engine-build' }] }
+ link.responses['POST /engine-builds/strata/catalog'] = { host_backend_id: 'macos-arm64-metal' }
+ link.responses['POST /models/strata/check'] = {
+ verdict: 'platform-unsupported',
+ reason: 'No compatible GPU on this server.',
+ }
+ link.responses['GET /settings/strata'] = { revision: 3, values: { memory_mode: 'auto' } }
+ let close: (() => Promise) | undefined
+ try {
+ const catalog = catalogFixture()
+ Object.assign(catalog.models, catalogExcerpt.models)
+ Object.assign(catalog.collections, catalogExcerpt.collections)
+ await mkdir(paths.cacheDir, { recursive: true })
+ const path = join(paths.cacheDir, 'strata catalog.json')
+ await writeFile(path, JSON.stringify(catalog))
+ const workspace = await workspaceServer(link, paths, {
+ ATOMIC_MODEL_CATALOG_URL: pathToFileURL(path).href,
+ })
+ close = workspace.close
+ const command = async (...args: string[]) => {
+ t.io.out.length = 0
+ expect(await t.run([...args, '--json']), t.io.err.join('')).toBe(0)
+ return JSON.parse(t.io.out.join(''))
+ }
+ const expected = {
+ rows: [
+ {
+ id: 'iq3-xxs-dflash2',
+ source: {
+ provider: 'strata',
+ check: { verdict: 'platform-unsupported', reason: 'No compatible GPU on this server.' },
+ },
+ },
+ ],
+ }
+ expect((await command('models', 'catalog', '--engine', 'strata')).result).toMatchObject(expected)
+ expect((await command('models', 'search', 'dflash2', '--engine', 'strata')).result).toMatchObject(
+ expected
+ )
+ expect((await command('models', 'search', 'unlisted', '--engine', 'strata')).result.rows).toEqual([])
+ expect(link.calls).toContainEqual({
+ method: 'POST',
+ path: '/models/strata/check',
+ body: { descriptor: expect.objectContaining({ variant_id: 'iq3-xxs-dflash2' }) },
+ })
+ const dryRun = await command('models', 'pull', 'iq3-xxs-dflash2', '--engine', 'strata', '--dry-run')
+ expect(dryRun).toMatchObject({
+ model_id: 'iq3-xxs-dflash2',
+ blockers: ['No compatible GPU on this server.'],
+ })
+ expect(dryRun.descriptor.files.length).toBeGreaterThan(2)
+ expect(await command('config', 'set', 'engine.strata.vision', 'off')).toMatchObject({ value: 'off' })
+ expect(link.calls).toContainEqual({
+ method: 'PATCH',
+ path: '/settings/strata',
+ body: { values: { vision: 'off' }, expected_revision: 3 },
+ })
+ } finally {
+ await close?.()
+ t.cleanup()
+ }
+})
diff --git a/test/contract/strata-server.test.ts b/test/contract/strata-server.test.ts
new file mode 100644
index 00000000..f187491b
--- /dev/null
+++ b/test/contract/strata-server.test.ts
@@ -0,0 +1,65 @@
+import { request } from 'node:http'
+import { AtomicCore } from '@atomic-chat/core'
+import { expect, it } from 'vitest'
+import { resolveConfig } from '../../src/config/index.js'
+import { startDaemon } from '../../src/daemon/index.js'
+import type { RunningDaemon } from '../../src/daemon/index.js'
+import { recordingIo } from '../../src/io.js'
+import { createLogger } from '../../src/output/index.js'
+import { fakeHost } from '../helpers/test-context.js'
+import { tmpDataFolder } from '../helpers/tmp-data-folder.js'
+
+it('keeps headless Strata preparation on the control listener and protects the public API', async () => {
+ const { paths, cleanup } = tmpDataFolder('atc-strata-headless-')
+ const env = {
+ ATC_API_KEY: 'strata-contract-key',
+ ATC_API_AUTO_START: 'false',
+ ATC_UPDATE_CHECK_ON_START: 'false',
+ }
+ let daemon: RunningDaemon | undefined
+ try {
+ daemon = await startDaemon({
+ paths,
+ io: recordingIo({ env }),
+ config: resolveConfig({ env }),
+ host: fakeHost(),
+ log: createLogger(() => {}, { level: 'silent' }),
+ controlPort: 0,
+ admin: { enabled: false },
+ telemetry: false,
+ createCore: (options) =>
+ AtomicCore.create({
+ ...options,
+ fetch: async () => new Response('Offline contract fixture', { status: 503 }),
+ }),
+ })
+ const state = await daemon.link.server.start({
+ host: '127.0.0.1',
+ port: 0,
+ prefix: '/v1',
+ fallback_port: false,
+ })
+ const base = `http://127.0.0.1:${state.port}`
+ const headers = { authorization: 'Bearer ' + env.ATC_API_KEY }
+ expect((await fetch(base + '/v1/models')).status).toBe(401)
+ const listed = await fetch(base + '/v1/models', { headers })
+ expect(listed.status).toBe(200)
+ expect(await listed.json()).toMatchObject({ data: [] })
+ const untrusted = await new Promise((resolve, reject) => {
+ request(base + '/v1/models', { headers: { ...headers, host: 'untrusted.example' } }, (response) => {
+ response.resume()
+ resolve(response.statusCode)
+ })
+ .on('error', reject)
+ .end()
+ })
+ expect(untrusted).toBe(403)
+ expect((await fetch(base + '/atomic/v1/strata/preparations', { headers })).status).toBe(404)
+ const metrics = await fetch(base + '/v1/metrics', { headers })
+ expect(metrics.status).toBeGreaterThanOrEqual(400)
+ await expect(daemon.link.request('GET', '/strata/preparations')).resolves.toEqual([])
+ } finally {
+ await daemon?.shutdown()
+ cleanup()
+ }
+}, 30_000)
diff --git a/test/contract/strata-sources.test.ts b/test/contract/strata-sources.test.ts
new file mode 100644
index 00000000..c81fcd49
--- /dev/null
+++ b/test/contract/strata-sources.test.ts
@@ -0,0 +1,79 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { AtomicCore, CORE_VERSION } from '@atomic-chat/core'
+import { CoreClient } from '@atomic-chat/core/client'
+import { expect, it, vi } from 'vitest'
+import { readAdminToken } from '../../src/admin/index.js'
+import { resolveConfig } from '../../src/config/index.js'
+import { startDaemon } from '../../src/daemon/index.js'
+import type { RunningDaemon } from '../../src/daemon/index.js'
+import { recordingIo } from '../../src/io.js'
+import { createLogger } from '../../src/output/index.js'
+import manifestFixture from '../fixtures/strata/manifest.json' with { type: 'json' }
+import { catalogFixture } from '../helpers/model-catalog-fixture.js'
+import { fakeHost } from '../helpers/test-context.js'
+import { tmpDataFolder } from '../helpers/tmp-data-folder.js'
+
+it('uses the server’s local Strata manifest and model catalog without fetching conf', async () => {
+ const { paths, cleanup } = tmpDataFolder('atc-strata-sources-')
+ const offline = vi.fn(async () => new Response('Offline contract fixture', { status: 503 }))
+ let daemon: RunningDaemon | undefined
+ try {
+ await mkdir(paths.dataFolder)
+ const manifest = join(paths.dataFolder, 'local strata.json')
+ const catalog = join(paths.dataFolder, 'local catalog.json')
+ await writeFile(manifest, JSON.stringify(manifestFixture))
+ await writeFile(
+ catalog,
+ JSON.stringify(
+ catalogFixture({
+ 'staff-picks': { picks: [{ model_name: 'fixture/local-model', title: 'Local model' }] },
+ })
+ )
+ )
+ const env = {
+ ATOMIC_STRATA_MANIFEST_URL: pathToFileURL(manifest).href,
+ ATOMIC_MODEL_CATALOG_URL: pathToFileURL(catalog).href,
+ ATC_API_AUTO_START: 'false',
+ ATC_UPDATE_CHECK_ON_START: 'false',
+ }
+ daemon = await startDaemon({
+ paths,
+ io: recordingIo({ env, fetch: offline }),
+ config: resolveConfig({ env }),
+ host: fakeHost(),
+ log: createLogger(() => {}, { level: 'silent' }),
+ controlPort: 0,
+ admin: { enabled: true, port: 0 },
+ telemetry: false,
+ createCore: (options) => AtomicCore.create({ ...options, fetch: offline }),
+ })
+
+ expect(daemon.core.version).toBe(CORE_VERSION)
+ const client = new CoreClient({ baseUrl: daemon.link.endpoint.baseUrl, token: daemon.core.controlToken })
+ await expect(client.strataPreparations()).resolves.toEqual([])
+ await expect(daemon.link.request('POST', '/engine-builds/strata/catalog', {})).resolves.toMatchObject({
+ engine: 'strata',
+ manifest: { tag: 'strata-0.1.59-r7', source: 'remote' },
+ manifest_error: null,
+ })
+
+ const token = await readAdminToken(paths.adminToken)
+ const response = await fetch(new URL('/api/workspace/execute', daemon.admin!.url), {
+ method: 'POST',
+ headers: { 'authorization': 'Bearer ' + token, 'content-type': 'application/json', 'x-atc-admin': '1' },
+ body: JSON.stringify({ operation: 'models.catalog', input: { category: 'text' } }),
+ })
+ expect(response.status).toBe(200)
+ expect(await response.json()).toMatchObject({ rows: [{ id: 'fixture/local-model' }], cached: false })
+ expect(offline.mock.calls.map(([url]) => String(url))).not.toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(/atomic-chat-conf.*(?:strata-manifest|models\/catalog)\.json/),
+ ])
+ )
+ } finally {
+ await daemon?.shutdown()
+ cleanup()
+ }
+}, 30_000)
diff --git a/test/fixtures/strata/README.md b/test/fixtures/strata/README.md
new file mode 100644
index 00000000..e18f80e7
--- /dev/null
+++ b/test/fixtures/strata/README.md
@@ -0,0 +1,4 @@
+The fixtures are the Metal r7 release and the first Strata catalog entry from
+AtomicBot-ai/atomic-chat-conf at `38241e4f5bb6de3c9e49ea5641d1fd02b50d3448`.
+They contain metadata only. Contract tests block remote source requests and
+combine the Strata catalog excerpt with the bundled catalog.
diff --git a/test/fixtures/strata/catalog.json b/test/fixtures/strata/catalog.json
new file mode 100644
index 00000000..ea0c88b2
--- /dev/null
+++ b/test/fixtures/strata/catalog.json
@@ -0,0 +1,197 @@
+{
+ "schema_version": 1,
+ "updated_at": "2026-11-06T09:05:18Z",
+ "models": {
+ "strata-qwen38-iq3-xxs": {
+ "kind": "strata",
+ "format": "strata",
+ "definition": {
+ "family": "qwen38",
+ "variant_id": "iq3-xxs-dflash2",
+ "name": "Qwen3.8-Flash-Next IQ3_XXS",
+ "license": "Apache-2.0",
+ "gated": false,
+ "context_length": 8192,
+ "engine_release": "strata-0.1.59-r5",
+ "preparation_abi": "strata-v1",
+ "preparation_recipe_id": "strata-qwen38-v1",
+ "sources": [
+ {
+ "id": "weights",
+ "host": "huggingface",
+ "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF",
+ "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09"
+ },
+ {
+ "id": "drafter",
+ "host": "huggingface",
+ "repo": "incoai/Qwen3.8-Flash-Next-DFlash2",
+ "revision": "a22a1744e85c17364dcc54a6a420af7135d4c7f6"
+ },
+ {
+ "id": "strata-data",
+ "host": "github",
+ "repo": "Niko1221/Strata",
+ "revision": "d2f096475817d4666c364c820b0ca830f751cfc5"
+ }
+ ],
+ "files": [
+ {
+ "source": "weights",
+ "source_path": "IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
+ "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
+ "size": 47039860096,
+ "sha256": "219ea929900dfa9ef091f3aa473fdba6874b65fcb36526d7d851ac9e95856d15",
+ "role": "weights"
+ },
+ {
+ "source": "weights",
+ "source_path": "IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf",
+ "path": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf",
+ "size": 28800138432,
+ "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113",
+ "role": "weights"
+ },
+ {
+ "source": "weights",
+ "source_path": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
+ "path": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
+ "size": 907543008,
+ "sha256": "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0",
+ "role": "vision"
+ },
+ {
+ "source": "drafter",
+ "source_path": "config.json",
+ "path": "draft/config.json",
+ "size": 1236,
+ "sha256": "2409575986f9ea24d455343eb469c0e6940def5edab1d1be503bb8eb4cc3b1b9",
+ "role": "drafter-config"
+ },
+ {
+ "source": "drafter",
+ "source_path": "model.safetensors",
+ "path": "draft/model.safetensors",
+ "size": 1206140008,
+ "sha256": "d6723f2a359eaf33ec0c95f22ae8edda896774020c552296a85e1913b4d3186f",
+ "role": "drafter"
+ },
+ {
+ "source": "strata-data",
+ "source_path": "data/draft_vocab.bin",
+ "path": "draft/vocab.bin",
+ "size": 425196,
+ "sha256": "b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91",
+ "role": "draft-vocab"
+ },
+ {
+ "source": "strata-data",
+ "source_path": "data/expert-profile.bin",
+ "path": "profile.bin",
+ "size": 196632,
+ "sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf",
+ "role": "expert-profile"
+ }
+ ],
+ "inputs": {
+ "weights": [
+ "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
+ "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"
+ ],
+ "vision": "mmproj-Qwen3.8-Flash-Next-BF16.gguf",
+ "drafter": "draft/model.safetensors",
+ "drafter_config": "draft/config.json",
+ "draft_vocab": "draft/vocab.bin",
+ "expert_profile": "profile.bin",
+ "tokenizer_from": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
+ "chat_template_from": "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
+ "drafting": "dflash2"
+ },
+ "compatible_variants": [
+ "linux-arm64-spark-cuda13",
+ "linux-x64-cuda12",
+ "linux-x64-cuda13",
+ "linux-x64-halo",
+ "linux-x64-rx6000",
+ "linux-x64-rx7900",
+ "linux-x64-rx9070",
+ "linux-x64-rx9070-deepseek",
+ "linux-x64-sycl",
+ "macos-arm64-metal",
+ "windows-x64-cuda12",
+ "windows-x64-cuda13",
+ "windows-x64-rdna2",
+ "windows-x64-rdna3",
+ "windows-x64-rdna3-deepseek",
+ "windows-x64-rx9070"
+ ],
+ "capabilities": {
+ "chat": true,
+ "tools": true,
+ "reasoning": true,
+ "vision": true,
+ "structured_output": true
+ },
+ "capability_requirements": {
+ "vision": [
+ "compatible-picture-reader"
+ ],
+ "structured_output": [
+ "full-json-schema-validator"
+ ],
+ "drafting": [
+ "verified-family-profile"
+ ]
+ },
+ "requirements": {
+ "download_bytes": 77954304608,
+ "memory_accounting": "separate-ram-vram-or-unified",
+ "resource_estimator": "strata-qwen38-v1",
+ "disk_components": [
+ "sources",
+ "derivatives",
+ "temporary",
+ "previous-installation"
+ ],
+ "memory_components": [
+ "ram",
+ "vram",
+ "unified-memory"
+ ],
+ "memory_modes": [
+ "auto",
+ "ram",
+ "ssd"
+ ],
+ "requires_core_check": true
+ },
+ "qualification": {
+ "status": "upstream-supported",
+ "evidence": [
+ "https://github.com/Niko1221/Strata/blob/13eedf552417a6a791a7d13c6597e24300ee3a09/docs/CAPABILITIES.md",
+ "https://github.com/Niko1221/Strata/blob/13eedf552417a6a791a7d13c6597e24300ee3a09/docs/MODELS.md",
+ "https://github.com/Niko1221/Strata/blob/d2f096475817d4666c364c820b0ca830f751cfc5/setup.py"
+ ]
+ }
+ },
+ "variants": {
+ "iq3-xxs-dflash2": {
+ "family": "qwen38"
+ }
+ }
+ }
+ },
+ "collections": {
+ "strata-models": {
+ "header": {
+ "schema_version": 1
+ },
+ "entries": [
+ {
+ "model": "strata-qwen38-iq3-xxs",
+ "variant": "iq3-xxs-dflash2"
+ }
+ ]
+ }
+ }
+}
diff --git a/test/fixtures/strata/manifest.json b/test/fixtures/strata/manifest.json
new file mode 100644
index 00000000..26c38112
--- /dev/null
+++ b/test/fixtures/strata/manifest.json
@@ -0,0 +1,146 @@
+{
+ "$schema": "./strata-schema.json",
+ "schema_version": 1,
+ "releases": [
+ {
+ "release_id": "strata-0.1.59-r7",
+ "engine_version": "0.1.59",
+ "minimum_core_version": "0.24.0",
+ "adapter_contract_version": 1,
+ "preparation_abi": "strata-v1",
+ "control_versions": [
+ "0.1.59"
+ ],
+ "components": [
+ {
+ "id": "control",
+ "kind": "control",
+ "version": "0.1.59",
+ "platform": "macos-arm64",
+ "url": "https://github.com/Niko1221/Strata/releases/download/v0.2.13/strata-control-0.1.59-macos-arm64.tar.gz",
+ "sha256": "62e571b58d60d6507e5d24975f380ae0f2c302210e895ad31fc166b59c18d024",
+ "size": 51226275,
+ "unpacked_bytes": 151069985,
+ "archive": "tar.gz",
+ "source_revision": "d2f096475817d4666c364c820b0ca830f751cfc5",
+ "executable_paths": [
+ "python/bin/python3"
+ ],
+ "notices": [
+ {
+ "name": "Strata",
+ "license": "MIT",
+ "url": "https://raw.githubusercontent.com/Niko1221/Strata/d2f096475817d4666c364c820b0ca830f751cfc5/LICENSE",
+ "sha256": "949b9b0aada7476006469e58ee4ffb0e0f68c2d9137e90a356757b61a09d37f0"
+ }
+ ],
+ "python_version": "3.12.15",
+ "python_modules": [
+ "gguf",
+ "jsonschema",
+ "referencing",
+ "rpds",
+ "attrs",
+ "jsonschema_specifications"
+ ],
+ "structured_output": true
+ },
+ {
+ "id": "qwen",
+ "kind": "qwen",
+ "version": "0.1.59",
+ "platform": "macos-arm64",
+ "url": "https://github.com/Niko1221/Strata/releases/download/v0.2.13/strata-engine-0.1.59-macos-arm64-metal.tar.gz",
+ "sha256": "9d326745eaebf24248968c145908aca5616ad8562dbca9c3aa327164724a517d",
+ "size": 5535163,
+ "unpacked_bytes": 15362828,
+ "archive": "tar.gz",
+ "source_revision": "712fec6b4297c9cfd32ab43daaa2979a9aa01edf",
+ "executable_paths": [
+ "strata",
+ "strata-vision"
+ ],
+ "notices": [
+ {
+ "name": "Strata",
+ "license": "MIT",
+ "url": "https://raw.githubusercontent.com/Niko1221/Strata/d2f096475817d4666c364c820b0ca830f751cfc5/LICENSE",
+ "sha256": "949b9b0aada7476006469e58ee4ffb0e0f68c2d9137e90a356757b61a09d37f0"
+ }
+ ],
+ "backend": "metal"
+ },
+ {
+ "id": "deepseek",
+ "kind": "deepseek",
+ "version": "0.1.59",
+ "platform": "macos-arm64",
+ "url": "https://github.com/Niko1221/Strata/releases/download/v0.2.13/strata-dsv41-0.1.59-macos-arm64-metal.tar.gz",
+ "sha256": "2fcbd44259db297782b0bdf54065b65a3882a0f52723b12940fdff40b928013d",
+ "size": 1809511,
+ "unpacked_bytes": 4833527,
+ "archive": "tar.gz",
+ "source_revision": "712fec6b4297c9cfd32ab43daaa2979a9aa01edf",
+ "executable_paths": [
+ "strata-dsv41"
+ ],
+ "notices": [
+ {
+ "name": "Strata",
+ "license": "MIT",
+ "url": "https://raw.githubusercontent.com/Niko1221/Strata/d2f096475817d4666c364c820b0ca830f751cfc5/LICENSE",
+ "sha256": "949b9b0aada7476006469e58ee4ffb0e0f68c2d9137e90a356757b61a09d37f0"
+ }
+ ],
+ "backend": "metal"
+ }
+ ],
+ "variants": [
+ {
+ "id": "macos-arm64-metal",
+ "platform": "macos-arm64",
+ "backend": "metal",
+ "host": {
+ "os": "macos",
+ "arch": "arm64",
+ "cpu_features": [],
+ "gpu_vendor": "apple",
+ "gpu_architectures": [
+ "apple-gpu"
+ ],
+ "minimum_os_version": "15.0"
+ },
+ "components": [
+ "control",
+ "qwen",
+ "deepseek"
+ ],
+ "families": [
+ "qwen38",
+ "deepseek41"
+ ],
+ "qualification": {
+ "status": "upstream-supported",
+ "urls": [
+ "https://github.com/Niko1221/Strata/blob/13eedf552417a6a791a7d13c6597e24300ee3a09/docs/CAPABILITIES.md"
+ ]
+ },
+ "bundle": {
+ "url": "https://github.com/AtomicBot-ai/atomic-chat-conf/releases/download/strata-0.1.59-runtime-preview/strata-0.1.59-r7-macos-arm64-metal.tar.gz",
+ "size": 59282875,
+ "unpacked_bytes": 174457631,
+ "sha256": "6fcf8909989333b866e3e5e61956ca0809676ae5419e438eb08463b2c81162fa",
+ "archive": "tar.gz",
+ "bundle_manifest_sha256": "9f5c6803546077f208ddaf4138e0c414cab69ce85b351038d2e08cefd6a492db",
+ "python": "control/python/bin/python3",
+ "component_roots": {
+ "control": "control",
+ "qwen": "components/qwen",
+ "deepseek": "components/deepseek"
+ }
+ }
+ }
+ ]
+ }
+ ]
+}