The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(device): expose Store discovery and durable agent preparation (#245)
Leoe2ba60d913a2
diff --git a/cli/scripts/device-store-contract.ts b/cli/scripts/device-store-contract.tsnew file mode 100644index 000000000..80778aff5--- /dev/null+++ b/cli/scripts/device-store-contract.ts@@ -0,0 +1,12 @@+/** Generate/check the OS handoff schemas from the validators used by the device facade. */+import { readFileSync, writeFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { z } from 'zod'+import { DeviceStoreRequestSchema, DeviceStoreResultSchema } from '../src/lib/autonomous-device/storeContract.js'+for (const [name, schema] of [['request', DeviceStoreRequestSchema], ['response', DeviceStoreResultSchema]] as const) {+ const file = fileURLToPath(new URL(`../../docs/contracts/autonomous-device-store-v1/${name}.schema.json`, import.meta.url))+ const text = JSON.stringify(z.toJSONSchema(schema, { io: name === 'request' ? 'input' : 'output' }), null, 2) + '\n'+ if (process.argv.includes('--check')) {+ if (readFileSync(file, 'utf8') !== text) throw new Error(`Contract drift: regenerate ${file} and coordinate the change with Autonomous OS.`)+ } else writeFileSync(file, text)+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 2ef1d3ba9..5ec43f7f6 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,4 +1,5 @@#!/usr/bin/env node+import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'import { mutateDsh } from './dsh/service.js'import { HarnessShareOwner } from './sharing/owner.js'import { HarnessGrantStore } from './sharing/grants.js'@@ -5442,7 +5443,9 @@ async function runForeground(session: AuthSession): Promise<void> {const cable = new CableSession(cableHost, new DialLog(env.HARNESS_LOGS_DIR))cableRef = cable+ const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId, create: input => backend.onCreateAgent!(input) })autonomousDeviceService = new AutonomousDeviceService({+ store: deviceStore,machineId: backend.machineId,requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },@@ -5452,8 +5455,13 @@ async function runForeground(session: AuthSession): Promise<void> {stepFocus: (direction, currentAgentId) => backend.hasLocalClient() ? cableHost.stepFocus(direction, currentAgentId) : Promise.resolve('no_app'),// The dial's touchpad stroke, borrowed the same way: `dial_scroll` to the window's focused terminal.scroll: (phase, dy, velocity) => { if (!backend.hasLocalClient()) return false; cableHost.scrolled(phase, dy, velocity); return true },- agents: () => registry.advertised().map(s => ({ agentId: s.agentId, name: projectDisplayName(s), engine: s.engine,- state: turnStartedAt.has(s.sessionId) ? 'running' : 'idle' })),+ agents: () => {+ const evidence = new Map(deviceStoreAgents(backend.machineId).map(a => [a.agentId, a]))+ return registry.advertised().map(s => ({ agentId: s.agentId, name: projectDisplayName(s), engine: s.engine,+ packageId: evidence.get(s.agentId)?.packageId ?? null, workspace: evidence.get(s.agentId)?.workspace ?? s.cwd,+ runtime: evidence.get(s.agentId)?.runtime ?? 'unavailable',+ state: turnStartedAt.has(s.sessionId) ? 'running' : 'idle' }))+ },submit: submitAgent,cancelDelivery: id => input.cancelDelivery(id),stop: id => cancelAgent(id, true),diff --git a/cli/src/lib/autonomous-device/relay.spec.ts b/cli/src/lib/autonomous-device/relay.spec.tsindex b9a35e01c..c6c531dd0 100644--- a/cli/src/lib/autonomous-device/relay.spec.ts+++ b/cli/src/lib/autonomous-device/relay.spec.ts@@ -2,13 +2,13 @@ import { describe, expect, it, vi } from 'vitest'import { AutonomousDeviceRelay } from './relay.js'import { AutonomousDeviceService } from './service.js'import { randomUUID } from 'node:crypto'-function fixture() {+function fixture(store?: import('./store.js').AutonomousDeviceStore) {let role = 'device', identity: string | null = 'trusted-device'const submit = vi.fn(), cancel = vi.fn(() => true), send = vi.fn()const crypto = { sessionRole: () => role as 'device' | 'web', sessionIdentity: () => identity,unwrapDown: (_c: string, frame: Record<string, unknown>) => ({ ...frame, payload: (frame.payload as { __e2e: unknown }).__e2e }),wrapTarget: (_c: string, type: string, payload: Record<string, unknown>) => ({ type, payload: { __e2e: payload } }) }- const service = new AutonomousDeviceService({ machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Agent', engine: 'codex', state: 'idle' }], submit, cancelDelivery: cancel, stop: async () => true, answer: async () => true, recent: () => [] })+ const service = new AutonomousDeviceService({ store, machineId: 'machine', agents: () => [{ agentId: 'agent', name: 'Agent', engine: 'codex', state: 'idle' }], submit, cancelDelivery: cancel, stop: async () => true, answer: async () => true, recent: () => [] })const remoteRevoke = vi.fn()const relay = new AutonomousDeviceRelay(crypto, send, service, 'machine', undefined, remoteRevoke)const request = (payload: Record<string, unknown>) => relay.handle('conn', { type: 'autonomous_device_request', payload: { __e2e: payload } })@@ -60,3 +60,27 @@ describe('Autonomous device existing E2EE relay seam', () => {expect(f.remoteRevoke).not.toHaveBeenCalled()})})++it('Store uses the same device-only encrypted hello gate and never exposes generic app operations', async () => {+ const call = vi.fn(async (_identity: string, _req: Record<string, unknown>) => ({ packages: [], nextOffset: null, machineId: 'machine' }))+ const store = { request: call } as unknown as import('./store.js').AutonomousDeviceStore+ const f = fixture(store)+ await f.request({ type: 'store.list', requestId: randomUUID() })+ expect(f.send.mock.calls.at(-1)?.[1]).toMatchObject({ payload: { __e2e: { error: { code: 'HELLO_REQUIRED' } } } })+ expect(call).not.toHaveBeenCalled()+ f.setRole('web')+ await f.request({ type: 'hello', proto: 1, requestId: randomUUID() })+ await f.request({ type: 'store.list', requestId: randomUUID() })+ expect(call).not.toHaveBeenCalled()+ f.setRole('device')+ await f.relay.handle('conn', { type: 'autonomous_device_request', payload: { type: 'store.list' } })+ expect(call).not.toHaveBeenCalled()+ await f.request({ type: 'hello', proto: 1, requestId: randomUUID() })+ expect(f.send.mock.calls.some(([, frame]) => frame.payload.__e2e.capabilities?.includes('agent.prepare'))).toBe(true)+ await f.request({ type: 'store.list', requestId: randomUUID() })+ expect(call).toHaveBeenCalledOnce()+ expect(call.mock.calls[0]?.[0]).toBe('trusted-device')+ await f.request({ type: 'agent_create', requestId: randomUUID(), cwd: '/tmp', engine: 'claude' })+ expect(f.send.mock.calls.at(-1)?.[1]).toMatchObject({ payload: { __e2e: { error: { code: 'UNSUPPORTED_CAPABILITY' } } } })+ expect(call).toHaveBeenCalledOnce()+})diff --git a/cli/src/lib/autonomous-device/relay.ts b/cli/src/lib/autonomous-device/relay.tsindex 9e4045bbf..554195280 100644--- a/cli/src/lib/autonomous-device/relay.ts+++ b/cli/src/lib/autonomous-device/relay.ts@@ -1,6 +1,6 @@import { isWrapped } from '../e2ee/core.js'import type { E2eeManager } from '../e2ee/manager.js'-import { AUTONOMOUS_DEVICE_CAPABILITIES, type AutonomousDeviceService, type AutonomousDeviceFrame } from './service.js'+import { type AutonomousDeviceService, type AutonomousDeviceFrame } from './service.js'type Frame = Record<string, unknown>/** Application RPC over the existing relay E2EE session. No socket, identity, PAKE or trust of its own. */@@ -30,7 +30,7 @@ export class AutonomousDeviceRelay {const current = this.clients.get(connId)this.clients.set(connId, current?.identity === identity ? current : { identity, tokens: 20, at: Date.now(), active: 0 })const resume = req.resume as { serverInstanceId?: unknown; cursor?: unknown } | undefined- reply({ type: 'hello_result', requestId: req.requestId, proto: 1, machineId: this.machineId, serverInstanceId: this.service.serverInstanceId, capabilities: AUTONOMOUS_DEVICE_CAPABILITIES, ...this.service.resume(resume) })+ reply({ type: 'hello_result', requestId: req.requestId, proto: 1, machineId: this.machineId, serverInstanceId: this.service.serverInstanceId, capabilities: this.service.capabilities, ...this.service.resume(resume) })this.service.replay(resume, event => this.sendEvent(connId, identity, event))this.onReady?.()returndiff --git a/cli/src/lib/autonomous-device/service.ts b/cli/src/lib/autonomous-device/service.tsindex 1d1f35ebe..6ac85294f 100644--- a/cli/src/lib/autonomous-device/service.ts+++ b/cli/src/lib/autonomous-device/service.ts@@ -1,3 +1,5 @@+import type { AutonomousDeviceStore } from './store.js'+import { DEVICE_STORE_CAPABILITIES, DeviceStoreError } from './storeContract.js'import { createHash, randomUUID } from 'node:crypto'export type AutonomousDeviceFrame = Record<string, unknown> & { type: string }@@ -7,11 +9,12 @@ export interface AutonomousDeviceReceipt {agentId: string; machineId: string; serverInstanceId: string; turnId: string | nullerror: { code: string; message: string } | null; at: number}-export interface AutonomousDeviceAgent { agentId: string; name: string; engine: string; state: string }+export interface AutonomousDeviceAgent { agentId: string; name: string; engine: string; state: string; packageId?: string | null; workspace?: string | null; runtime?: string }const AGENT_RECAP_MAX_CHARS = 200export interface AutonomousDeviceDelivery { deliveryId: string; sessionId: string; state: ReceiptState; reason?: string }export interface AutonomousDeviceServiceOptions {+ store?: AutonomousDeviceStoremachineId: string; serverInstanceId?: string; now?: () => numberagents: () => AutonomousDeviceAgent[]requestAppFocus?: (agentId: string, expiresAt: number, focusRevision: string) => boolean@@ -226,6 +229,7 @@ export class AutonomousDeviceService {this.update(entry, event.state, event.reason)}revoke(deviceId: string): void {+ this.options.store?.revoke(deviceId)for (const [key, entry] of this.entries) if (entry.deviceId === deviceId) {this.options.cancelDelivery(entry.receipt.deliveryId)this.deliveries.delete(entry.receipt.deliveryId)@@ -282,13 +286,15 @@ export class AutonomousDeviceService {this.event(p.kind === 'summary' ? 'turn.summary' : p.kind === 'tool' ? 'turn.tool' : 'agent.error', agentId, full ? { ...p, fullText: full } : p)}}+ get capabilities(): string[] { return [...AUTONOMOUS_DEVICE_CAPABILITIES, ...(this.options.store ? DEVICE_STORE_CAPABILITIES : [])] }async request(deviceId: string, req: Record<string, unknown>): Promise<AutonomousDeviceFrame> {const type = typeof req.type === 'string' ? req.type : 'invalid'const response = (data: Record<string, unknown>): AutonomousDeviceFrame => ({ type: `${type}_result`, requestId: req.requestId, ...data })let reserved: Entry | undefinedtry {if (!UUID.test(String(req.requestId))) fail('INVALID_REQUEST', 'requestId must be a UUIDv4')- if (!AUTONOMOUS_DEVICE_CAPABILITIES.includes(type)) fail('UNSUPPORTED_CAPABILITY', 'Operation is not supported')+ if (!this.capabilities.includes(type)) fail('UNSUPPORTED_CAPABILITY', 'Operation is not supported')+ if ((DEVICE_STORE_CAPABILITIES as readonly string[]).includes(type)) return response(await this.options.store!.request(deviceId, req))const allowed = ['type', 'requestId', ...(['agents.list', 'focus.get', 'focus.ensure'].includes(type) ? [] : type === 'receipt.get' ? ['idempotencyKey'] : type === 'focus.step' ? ['direction', 'idempotencyKey', 'focusRevision'] : type === 'scroll' ? ['phase', 'dy', 'velocity'] : ['machineId', 'agentId']),...(MUTATIONS.has(type) ? ['idempotencyKey'] : []), ...(type === 'turn.send' ? ['text', 'focusRevision'] : type === 'question.answer' ? ['questionRequestId', 'answers', 'focusRevision'] : type === 'recap' ? ['n'] : [])]if (Object.keys(req).some(k => !allowed.includes(k))) fail('INVALID_REQUEST', 'Unknown request field')@@ -364,7 +370,7 @@ export class AutonomousDeviceService {reserved.receipt.error = { code: 'INTERNAL', message: 'Reserved operation could not be confirmed' }return response({ status: 'accepted', receipt: structuredClone(reserved.receipt) })}- return response({ error: { code: e instanceof RequestError ? e.code : 'INTERNAL', message: e instanceof RequestError ? e.message : 'Request failed' } })+ return response({ error: { code: e instanceof RequestError || e instanceof DeviceStoreError ? e.code : 'INTERNAL', message: e instanceof RequestError || e instanceof DeviceStoreError ? e.message : 'Request failed' } })}}}diff --git a/cli/src/lib/autonomous-device/store.spec.ts b/cli/src/lib/autonomous-device/store.spec.tsnew file mode 100644index 000000000..ffe9e1d4c--- /dev/null+++ b/cli/src/lib/autonomous-device/store.spec.ts@@ -0,0 +1,245 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { randomUUID } from 'node:crypto'+import { AutonomousDeviceStore, type StoreAgent, type StorePackage } from './store.js'+import { DeviceOperationSchema } from './storeContract.js'+import { AutonomousDeviceService } from './service.js'+import { AgentCreationReceipts } from '../agentCreationReceipt.js'++const roots: string[] = []+afterEach(() => { for (const p of roots.splice(0)) rmSync(p, { recursive: true, force: true }) })+const request = (type: string, extra: Record<string, unknown> = {}) => ({ type, requestId: randomUUID(), ...extra })+function fixture(installed = true) {+ const directory = mkdtempSync(join(tmpdir(), 'device-store-')); roots.push(directory)+ const pkg: StorePackage = { packageId: 'autonomous/blender', name: 'Blender', description: 'Create editable 3D geometry', category: '3D', engine: 'claude',+ installed, catalog: true, verified: true, viewerPackageId: 'autonomous/model-viewer', installAllowed: true, version: 'one', broken: null }+ const agents: StoreAgent[] = []+ const deps = { directory, machineId: 'mac', packages: vi.fn(async () => [pkg]),+ install: vi.fn(async () => { pkg.installed = true; return { ok: true } }),+ doctor: vi.fn(async () => ({ ok: true, checked: true, lines: ['ok bpy', 'ok viewer'] })),+ workspace: vi.fn(async () => '/projects/airplane'),+ create: vi.fn(async () => {+ agents.push({ agentId: 'agent1', machineId: 'mac', packageId: pkg.packageId, workspace: '/projects/airplane', engine: 'claude', state: 'idle', runtime: 'ready' })+ return { state: 'created' as const, agentId: 'agent1' }+ }), agents: () => agents,+ }+ const store = new AutonomousDeviceStore(deps)+ const prepare = (key = 'airplane', extra: Record<string, unknown> = {}) => store.request('lamp', request('agent.prepare', {+ machineId: 'mac', packageId: pkg.packageId, idempotencyKey: key, workspace: { kind: 'new', name: 'airplane' }, ...extra,+ }))+ const settled = async (id: string) => {+ await vi.waitFor(() => expect(store.get('lamp', id).state).not.toMatch(/^(accepted|running)$/))+ return store.get('lamp', id)+ }+ const id = (r: Record<string, unknown>) => (r.operation as { operationId: string }).operationId+ return { deps, pkg, agents, store, prepare, settled, id, directory }+}+describe('device Store durable preparation', () => {+ it('discovers metadata without claiming readiness or executing doctors/setup', async () => {+ const f = fixture(false)+ const result = await f.store.request('lamp', request('store.list', { query: 'blender' }))+ expect(result.packages).toMatchObject([{ installed: false, catalog: true, readiness: { state: 'not_installed' }, capabilities: { source: 'package_metadata' } }])+ expect(f.deps.doctor).not.toHaveBeenCalled()+ expect(f.deps.install).not.toHaveBeenCalled()+ f.pkg.installed = true+ const inspected = await f.store.request('lamp', request('store.inspect', { packageId: f.pkg.packageId }))+ expect(inspected.package).toMatchObject({ readiness: { state: 'unknown', engineAuthentication: 'unknown' } })+ })+ it.each([true, false])('prepares Blender (installed=%s), separately from task delivery', async installed => {+ const f = fixture(installed)+ const result = await f.prepare()+ expect(result).toMatchObject({ status: 'accepted', operation: { state: 'accepted', taskDispatched: false } })+ const op = await f.settled(f.id(result))+ expect(DeviceOperationSchema.parse(op)).toMatchObject({ state: 'ready', agentId: 'agent1', workspace: '/projects/airplane', doctor: ['ok bpy', 'ok viewer'] })+ expect(f.deps.install).toHaveBeenCalledTimes(installed ? 0 : 1)+ expect(f.deps.create).toHaveBeenCalledWith('autonomous/blender', '/projects/airplane')+ const result2 = await f.store.request('lamp', request('store.inspect', { packageId: f.pkg.packageId }))+ expect(result2).toMatchObject({ package: { readiness: { state: 'passed' } }, candidates: [{ agentId: 'agent1', packageId: 'autonomous/blender' }] })+ f.pkg.version = 'two'+ expect((await f.store.request('lamp', request('store.inspect', { packageId: f.pkg.packageId }))).package).toMatchObject({ readiness: { state: 'unknown' } })+ })+ it('deduplicates concurrent retries and reconnects with different requestIds', async () => {+ const f = fixture(false)+ const results = await Promise.all([f.prepare(), f.prepare(), f.prepare()])+ expect(new Set(results.map(f.id)).size).toBe(1)+ await f.settled(f.id(results[0]))+ expect(f.deps.install).toHaveBeenCalledOnce(); expect(f.deps.create).toHaveBeenCalledOnce()+ expect(await f.prepare()).toMatchObject({ status: 'duplicate', operation: { state: 'ready' } })+ await expect(f.prepare('airplane', { workspace: { kind: 'new', name: 'other' } })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' })+ })+ it('shares a package installation between distinct operations, but not their agents', async () => {+ const f = fixture(false)+ let done!: () => void+ f.deps.install.mockImplementationOnce(() => new Promise(resolve => { done = () => { f.pkg.installed = true; resolve({ ok: true }) } }))+ f.deps.workspace.mockImplementation(async () => `/projects/${randomUUID()}`)+ f.deps.create.mockImplementation(async () => ({ state: 'created', agentId: randomUUID() }))+ const a = await f.prepare('a'), b = await f.prepare('b')+ await vi.waitFor(() => expect(f.deps.install).toHaveBeenCalledOnce())+ expect(f.store.get('lamp', f.id(a)).state).toBe('running')+ done()+ await f.settled(f.id(a)); await f.settled(f.id(b))+ expect(f.deps.install).toHaveBeenCalledOnce(); expect(f.deps.create).toHaveBeenCalledTimes(2)+ })+ it('does not repeat work when caller times out during install', async () => {+ const f = fixture(false)+ let done!: () => void+ f.deps.install.mockImplementationOnce(() => new Promise(resolve => { done = () => { f.pkg.installed = true; resolve({ ok: true }) } }))+ const result = await f.prepare()+ await vi.waitFor(() => expect(f.deps.install).toHaveBeenCalledOnce())+ expect(await f.prepare()).toMatchObject({ status: 'duplicate', operation: { state: 'running' } })+ done(); expect((await f.settled(f.id(result))).state).toBe('ready')+ expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('returns doctor evidence and concrete action without creating an agent', async () => {+ const f = fixture()+ f.deps.doctor.mockResolvedValue({ ok: false, checked: true, lines: ['miss bpy: run setup in Harness Store'] })+ const op = await f.settled(f.id(await f.prepare()))+ expect(op).toMatchObject({ state: 'needs_user_action', error: { code: 'DEPENDENCY_NOT_READY' }, doctor: ['miss bpy: run setup in Harness Store'] })+ expect(f.deps.create).not.toHaveBeenCalled()+ })+ it('requires review of uninstalled community packages/dependencies', async () => {+ const f = fixture(false); f.pkg.installAllowed = false+ expect(await f.settled(f.id(await f.prepare()))).toMatchObject({ state: 'needs_user_action', error: { code: 'PACKAGE_REVIEW_REQUIRED' } })+ expect(f.deps.install).not.toHaveBeenCalled()+ })+ it('reports install errors without turning them into an agent launch', async () => {+ const f = fixture(false)+ f.deps.install.mockResolvedValue({ ok: false, error: 'SETUP_FAILED', detail: 'Permission denied installing bpy' } as never)+ expect(await f.settled(f.id(await f.prepare()))).toMatchObject({ state: 'needs_user_action', error: { code: 'SETUP_FAILED' } })+ expect(f.deps.create).not.toHaveBeenCalled()+ })+ it('preserves candidates and refuses to reuse or change a live agent workspace', async () => {+ const f = fixture()+ f.agents.push({ agentId: 'existing', machineId: 'mac', packageId: f.pkg.packageId, engine: 'claude', workspace: '/projects/airplane', state: 'running', runtime: 'ready' })+ expect(await f.settled(f.id(await f.prepare()))).toMatchObject({ error: { code: 'WORKSPACE_IN_USE' } })+ expect(f.deps.create).not.toHaveBeenCalled()+ expect(f.agents[0].agentId).toBe('existing')+ })+ it('serializes competing creation attempts for the same canonical workspace', async () => {+ const f = fixture()+ let complete!: () => void+ f.deps.create.mockImplementationOnce(() => new Promise(resolve => { complete = () => resolve({ state: 'created', agentId: 'one' }) }))+ const a = await f.prepare('a')+ await vi.waitFor(() => expect(f.deps.create).toHaveBeenCalledOnce())+ expect(await f.settled(f.id(await f.prepare('b')))).toMatchObject({ error: { code: 'WORKSPACE_IN_USE' } })+ complete(); await f.settled(f.id(a)); expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('recovers completed preparation after daemon restart using disk state', async () => {+ const f = fixture(); const id = f.id(await f.prepare()); await f.settled(id)+ const restarted = new AutonomousDeviceStore(f.deps)+ expect(restarted.get('lamp', id)).toMatchObject({ state: 'ready', agentId: 'agent1' })+ expect(await restarted.request('lamp', request('agent.prepare', { machineId: 'mac', packageId: f.pkg.packageId, idempotencyKey: 'airplane', workspace: { kind: 'new', name: 'airplane' } }))).toMatchObject({ status: 'duplicate' })+ expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('never replays install/create when a restart finds an uncertain reservation', async () => {+ const f = fixture(false)+ f.deps.install.mockImplementationOnce(() => new Promise(() => {}))+ const id = f.id(await f.prepare())+ await vi.waitFor(() => expect(f.deps.install).toHaveBeenCalledOnce())+ const restarted = new AutonomousDeviceStore(f.deps)+ expect(restarted.get('lamp', id)).toMatchObject({ state: 'needs_user_action', error: { code: 'RECOVERY_REQUIRED' } })+ expect(f.deps.install).toHaveBeenCalledOnce(); expect(f.deps.create).not.toHaveBeenCalled()+ })+ it('recovers the spawn/journal crash gap from the existing creation receipt', async () => {+ const f = fixture(); const id = f.id(await f.prepare()); await f.settled(id)+ const file = join(f.directory, `${id}.json`), row = JSON.parse(readFileSync(file, 'utf8'))+ row.operation.state = 'running'; row.operation.phase = 'create'; row.operation.agentId = null+ writeFileSync(file, JSON.stringify(row), { mode: 0o600 })+ expect(new AgentCreationReceipts(join(f.directory, 'creations')).status(id)).toMatchObject({ state: 'created' })+ expect(new AutonomousDeviceStore(f.deps).get('lamp', id)).toMatchObject({ state: 'ready', agentId: 'agent1' })+ expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('isolates operation visibility by paired identity', async () => {+ const f = fixture(), id = f.id(await f.prepare()); await f.settled(id)+ expect(() => f.store.get('other-device', id)).toThrow('No preparation')+ })+ it('halts after in-flight install on revoke, without dispatch or agent creation', async () => {+ const f = fixture(false)+ let done!: () => void+ f.deps.install.mockImplementationOnce(() => new Promise(resolve => { done = () => { f.pkg.installed = true; resolve({ ok: true }) } }))+ const id = f.id(await f.prepare()); await vi.waitFor(() => expect(f.deps.install).toHaveBeenCalledOnce())+ f.store.revoke('lamp'); done()+ expect(await f.settled(id)).toMatchObject({ error: { code: 'REVOKED' } })+ expect(f.deps.create).not.toHaveBeenCalled()+ })+ it('does not report a starting engine as ready; allows user to fix its launch', async () => {+ const f = fixture()+ const create = f.deps.create.getMockImplementation()!+ f.deps.create.mockImplementation(async () => { const result = await create(); f.agents[0].runtime = 'starting'; return result })+ const id = f.id(await f.prepare()); await vi.waitFor(() => expect(f.deps.create).toHaveBeenCalledOnce())+ await vi.waitFor(() => expect(f.store.get('lamp', id).phase).toBe('launch'))+ expect(f.store.get('lamp', id).state).toBe('running')+ f.agents[0].runtime = 'unavailable'; f.agents[0].error = 'Complete login in the agent terminal'+ expect(f.store.get('lamp', id)).toMatchObject({ state: 'needs_user_action', error: { code: 'ENGINE_ACTION_REQUIRED' } })+ f.agents[0].runtime = 'ready'+ expect(f.store.get('lamp', id).state).toBe('ready')+ expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('refuses corrupt journals instead of creating again', async () => {+ const f = fixture(), id = f.id(await f.prepare()); await f.settled(id)+ writeFileSync(join(f.directory, `${id}.json`), '{broken', { mode: 0o600 })+ expect(() => new AutonomousDeviceStore(f.deps).get('lamp', id)).toThrow('cannot be read safely')+ })+ it.each([{ prompt: 'draw plane' }, { url: 'https://evil.test' }, { engine: 'codex' }, { bypassPermission: true }, { workspace: { kind: 'existing', path: '../elsewhere' } }])('rejects extra powers/malformed workspace: %j', async extra => {+ const f = fixture()+ await expect(f.prepare('x', extra)).rejects.toMatchObject({ code: 'INVALID_REQUEST' })+ expect(f.deps.create).not.toHaveBeenCalled()+ })+ it('rejects a remote-machine target', async () => {+ const f = fixture()+ await expect(f.prepare('x', { machineId: 'other' })).rejects.toMatchObject({ code: 'MACHINE_MISMATCH' })+ })+ it('advertises Store only when wired; old clients and turn.send remain separate', async () => {+ const f = fixture()+ const submit = vi.fn()+ const options = { machineId: 'mac', agents: () => [{ agentId: 'agent1', name: 'Blender', engine: 'claude', state: 'idle' }], submit,+ cancelDelivery: () => true, stop: async () => true, answer: async () => true, recent: () => [] }+ const old = new AutonomousDeviceService(options), service = new AutonomousDeviceService({ ...options, store: f.store })+ expect(old.capabilities).not.toContain('agent.prepare'); expect(service.capabilities).toContain('agent.prepare')+ expect(await old.request('lamp', request('store.list'))).toMatchObject({ error: { code: 'UNSUPPORTED_CAPABILITY' } })+ const r = await service.request('lamp', request('agent.prepare', { machineId: 'mac', packageId: f.pkg.packageId, idempotencyKey: 'a', workspace: { kind: 'new' } }))+ await f.settled(f.id(r)); expect(submit).not.toHaveBeenCalled()+ const turn = request('turn.send', { machineId: 'mac', agentId: 'agent1', idempotencyKey: 'task-airplane', text: 'Draw an airplane' })+ await service.request('lamp', turn); await service.request('lamp', { ...turn, requestId: randomUUID() })+ expect(submit).toHaveBeenCalledOnce()+ })+})++describe('device preparation failure boundaries', () => {+ it.each(['failed', 'unconfirmed', 'throw'] as const)('retains a %s create outcome without repeating it', async state => {+ const f = fixture()+ f.deps.create.mockImplementationOnce(async () => {+ if (state === 'throw') throw new Error('response lost after spawn')+ return state === 'failed' ? { state: 'failed', error: 'TMUX_UNAVAILABLE' } as never : { state: 'unconfirmed' } as never+ })+ const id = f.id(await f.prepare())+ expect((await f.settled(id)).state).toBe('needs_user_action')+ await f.prepare(); expect(f.deps.create).toHaveBeenCalledOnce()+ })+ it('bounds accepted background work rather than exhausting processes', async () => {+ const f = fixture(false); f.deps.install.mockImplementation(() => new Promise(() => {}))+ for (let i = 0; i < 4; i++) await f.prepare(String(i))+ await expect(f.prepare('fifth')).rejects.toMatchObject({ code: 'BACKPRESSURE' })+ })+ it('does not claim doctor readiness when no checks exist', async () => {+ const f = fixture(); f.deps.doctor.mockResolvedValue({ ok: true, checked: false, lines: [] })+ await f.settled(f.id(await f.prepare()))+ expect((await f.store.request('lamp', request('store.inspect', { packageId: f.pkg.packageId }))).package).toMatchObject({ readiness: { state: 'unknown' } })+ })+ it('does not prepare an unknown package', async () => {+ const f = fixture(); f.deps.packages.mockResolvedValue([])+ expect(await f.settled(f.id(await f.prepare()))).toMatchObject({ state: 'failed', error: { code: 'PACKAGE_NOT_FOUND' } })+ expect(f.deps.install).not.toHaveBeenCalled(); expect(f.deps.create).not.toHaveBeenCalled()+ })+})++it('withdraws a ready result if the same agent is restarting', async () => {+ const f = fixture(); const id = f.id(await f.prepare()); await f.settled(id)+ f.agents[0].runtime = 'starting'+ expect(f.store.get('lamp', id)).toMatchObject({ state: 'running', phase: 'launch' })+ f.agents[0].runtime = 'ready'+ expect(f.store.get('lamp', id).state).toBe('ready')+ expect(f.deps.create).toHaveBeenCalledOnce()+})diff --git a/cli/src/lib/autonomous-device/store.ts b/cli/src/lib/autonomous-device/store.tsnew file mode 100644index 000000000..1e3586830--- /dev/null+++ b/cli/src/lib/autonomous-device/store.ts@@ -0,0 +1,251 @@+import { createHash, randomUUID } from 'node:crypto'+import { closeSync, constants, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { z } from 'zod'+import { AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from '../agentCreationReceipt.js'+import { readPrivateStateFile, secureStateDirectory } from '../secureState.js'+import { DeviceOperationSchema, DeviceStoreError, DeviceStoreRequestSchema, type DeviceOperation, type PrepareRequest } from './storeContract.js'++export interface StoreAgent {+ agentId: string; machineId: string; packageId: string | null; engine: string; workspace: string | null+ state: string; runtime: 'starting' | 'ready' | 'unavailable'; error?: string+}+export interface StorePackage {+ packageId: string; name: string; description: string; category: string | null; engine: string | null+ installed: boolean; catalog: boolean; verified: boolean; viewerPackageId: string | null+ installAllowed: boolean; version: string | null; broken: string | null+}+export interface DeviceStoreDependencies {+ directory: string; machineId: string+ packages(): Promise<StorePackage[]>+ install(id: string, progress: (phase: string) => void): Promise<{ ok: boolean; error?: string; detail?: string }>+ doctor(id: string): Promise<{ ok: boolean; checked: boolean; lines: string[] }>+ workspace(request: PrepareRequest['workspace'], label: string): Promise<string>+ create(packageId: string, cwd: string): Promise<AgentCreationOutcome>+ agents(): StoreAgent[]+ now?: () => number+}+const JournalSchema = z.strictObject({+ version: z.literal(1), owner: z.string(), fingerprint: z.string(), operation: DeviceOperationSchema,+})+type Journal = z.infer<typeof JournalSchema>+const hash = (s: string) => createHash('sha256').update(s).digest('hex')+const active = (op: DeviceOperation) => op.state === 'accepted' || op.state === 'running'+const bounded = (s: string) => s.slice(0, 1000)++/** A durable prepare intent is never re-executed on timeout, reconnect, or restart.+ * The existing creation receipt resolves the crash gap between spawning and journaling agentId.+ * Progress is polled through operation.get; no new transport/event delivery semantics are needed.+ */+export class AutonomousDeviceStore {+ private readonly receipts: AgentCreationReceipts+ private readonly live = new Map<string, Journal>()+ private readonly installs = new Map<string, Promise<{ ok: boolean; error?: string; detail?: string }>>()+ private readonly checks = new Map<string, { state: 'passed' | 'failed' | 'unknown'; checkedAt: number; version: string | null; lines: string[] }>()+ private readonly revoked = new Set<string>()+ private readonly workspaces = new Map<string, string>()+ private readonly now: () => number+ constructor(private readonly deps: DeviceStoreDependencies) {+ this.receipts = new AgentCreationReceipts(join(deps.directory, 'creations'))+ this.now = deps.now ?? Date.now+ }+ private file(id: string) { return join(this.deps.directory, `${id}.json`) }+ private save(row: Journal, exclusive = false): void {+ secureStateDirectory(this.deps.directory)+ const file = this.file(row.operation.operationId)+ const target = exclusive ? file : `${file}.${randomUUID()}.tmp`+ let opened = false+ try {+ const fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)+ opened = true+ try { writeFileSync(fd, JSON.stringify(row)); fsyncSync(fd) } finally { closeSync(fd) }+ if (!exclusive) renameSync(target, file)+ const dir = openSync(this.deps.directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)+ try { fsyncSync(dir) } finally { closeSync(dir) }+ } finally { if (!exclusive && opened) rmSync(target, { force: true }) }+ }+ private read(id: string): Journal | null {+ if (this.live.has(id)) return this.live.get(id)!+ try {+ const row = JournalSchema.parse(JSON.parse(readPrivateStateFile(this.file(id), 32_768)))+ if (row.operation.operationId !== id || row.operation.machineId !== this.deps.machineId) throw new Error('Journal identity mismatch')+ return row+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw new DeviceStoreError('STORAGE_FAILED', 'Preparation state cannot be read safely. Inspect this machine; do not retry with a new key.')+ }+ }+ private change(row: Journal, patch: Partial<DeviceOperation>): void {+ const next = { ...row, operation: { ...row.operation, ...patch, updatedAt: this.now() } }+ this.save(next) // persist before exposing progress or advancing to another side effect+ row.operation = next.operation+ }+ private action(row: Journal, code: string, message: string, guidance: string): void {+ this.change(row, { state: 'needs_user_action', error: { code, message: bounded(message) }, guidance })+ }+ private authorized(row: Journal): void {+ if (this.revoked.has(row.operation.operationId)) throw new DeviceStoreError('REVOKED', 'Pairing was revoked. No further preparation steps will run.')+ }+ revoke(deviceId: string): void {+ for (const row of this.live.values()) if (row.owner === hash(deviceId)) this.revoked.add(row.operation.operationId)+ }++ private lastPreparation(packageId: string) {+ const op = [...this.live.values()].map(r => r.operation).filter(o => o.packageId === packageId).sort((a, b) => b.updatedAt - a.updatedAt)[0]+ return op ? { state: op.state, phase: op.phase, error: op.error, updatedAt: op.updatedAt } : null+ }+ private async listing() {+ return (await this.deps.packages()).map(p => ({ ...p,+ // Descriptive evidence, not a claim that the engine/app is logged in or usable.+ capabilities: { source: 'package_metadata' as const, description: p.description, category: p.category },+ requirements: { engine: p.engine, viewerPackageId: p.viewerPackageId, applications: null,+ note: 'Application requirements are not structured in the manifest. Preparation runs package and viewer doctors.' },+ lastPreparation: this.lastPreparation(p.packageId),+ installation: this.installs.has(p.packageId) ? 'installing' : p.broken ? 'broken' : p.installed ? 'installed' : 'not_installed',+ readiness: { ...(p.installed && this.checks.get(p.packageId)?.version === p.version ? this.checks.get(p.packageId) : undefined),+ state: !p.installed ? 'not_installed' : p.broken ? 'failed' : this.checks.get(p.packageId)?.version === p.version ? this.checks.get(p.packageId)!.state : 'unknown',+ scope: 'package_doctor', engineAuthentication: 'unknown', taskSuccess: 'unknown' },+ }))+ }+ async request(deviceId: string, raw: Record<string, unknown>): Promise<Record<string, unknown>> {+ const parsed = DeviceStoreRequestSchema.safeParse(raw)+ if (!parsed.success) throw new DeviceStoreError('INVALID_REQUEST', parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ').slice(0, 1000))+ const req = parsed.data+ if (req.type === 'operation.get') return { operation: this.get(deviceId, req.operationId) }+ if (req.type === 'agent.prepare') {+ if (req.machineId !== this.deps.machineId) throw new DeviceStoreError('MACHINE_MISMATCH', 'Only the paired machine is available')+ return this.prepare(deviceId, req)+ }+ const packages = await this.listing()+ if (req.type === 'store.inspect') {+ const item = packages.find(p => p.packageId === req.packageId)+ if (!item) throw new DeviceStoreError('PACKAGE_NOT_FOUND', 'Package is not in the catalog or installed on this machine')+ const candidates = this.deps.agents().filter(a => a.packageId === req.packageId)+ return { machineId: this.deps.machineId, package: item, candidates: candidates.slice(0, 5), candidatesTruncated: candidates.length > 5 }+ }+ const terms = (req.query ?? '').toLowerCase().split(/\s+/).filter(Boolean)+ const matches = packages.filter(p => terms.every(t => `${p.packageId} ${p.name} ${p.description} ${p.category ?? ''}`.toLowerCase().includes(t)))+ return { machineId: this.deps.machineId, packages: matches.slice(req.offset, req.offset + req.limit),+ nextOffset: req.offset + req.limit < matches.length ? req.offset + req.limit : null }+ }+ private prepare(deviceId: string, req: PrepareRequest): Record<string, unknown> {+ const owner = hash(deviceId)+ const operationId = hash(`${deviceId}\0${req.idempotencyKey}`)+ const fingerprint = creationFingerprint({ ...req, requestId: null })+ const prior = this.read(operationId)+ if (prior) {+ if (prior.fingerprint !== fingerprint) throw new DeviceStoreError('IDEMPOTENCY_CONFLICT', 'Key already belongs to different preparation parameters')+ return { status: 'duplicate', operation: this.get(deviceId, operationId) }+ }+ if ([...this.live.values()].filter(r => active(r.operation)).length >= 4) throw new DeviceStoreError('BACKPRESSURE', 'Four preparations are already running; poll their operations')+ const at = this.now()+ const row: Journal = { version: 1, owner, fingerprint, operation: { operationId, machineId: this.deps.machineId,+ packageId: req.packageId, state: 'accepted', phase: 'accepted', createdAt: at, updatedAt: at,+ agentId: null, workspace: null, error: null, guidance: null, doctor: [], taskDispatched: false, engineAuthentication: 'unknown' } }+ try { this.save(row, true) } catch { throw new DeviceStoreError('STORAGE_FAILED', 'Could not reserve preparation. Retry only with the same key.') }+ this.live.set(operationId, row)+ // Detach before any network, doctor or process work. A transport timeout cannot cancel this job.+ void Promise.resolve().then(() => this.run(row, req)).catch(error => {+ try {+ this.action(row, error instanceof DeviceStoreError ? error.code : 'PREPARATION_UNCONFIRMED',+ error instanceof Error ? error.message : 'Preparation could not be confirmed',+ 'Inspect the operation and Harness on this machine before starting a new preparation. Do not automatically retry with a new key.')+ } catch {+ row.operation = { ...row.operation, state: 'needs_user_action', error: { code: 'STORAGE_FAILED', message: 'Progress could not be persisted; inspect this machine before retrying.' } }+ }+ }).finally(() => {+ for (const [cwd, owner] of this.workspaces) if (owner === operationId) this.workspaces.delete(cwd)+ })+ return { status: 'accepted', operation: structuredClone(row.operation) }+ }+ private async run(row: Journal, req: PrepareRequest): Promise<void> {+ this.authorized(row)+ this.change(row, { state: 'running', phase: 'install' })+ let pkg = (await this.deps.packages()).find(p => p.packageId === req.packageId)+ this.authorized(row)+ if (!pkg) { this.change(row, { state: 'failed', error: { code: 'PACKAGE_NOT_FOUND', message: 'Package is not available on this machine' } }); return }+ if (!pkg.installed) {+ if (!pkg.installAllowed) {+ this.action(row, 'PACKAGE_REVIEW_REQUIRED', 'This package or a dependency requires local review before executing its setup.', 'Review and install it in Harness Store on this machine, then deliberately submit a new preparation key.'); return+ }+ let installing = this.installs.get(pkg.packageId)+ if (!installing) {+ // Store's own lock also covers installs/updates originating outside this facade.+ installing = this.deps.install(pkg.packageId, phase => {+ if (phase === 'clone' || phase === 'setup' || phase === 'doctor') {+ if (row.operation.phase !== phase) this.change(row, { phase })+ }+ }).finally(() => this.installs.delete(req.packageId))+ this.installs.set(pkg.packageId, installing)+ }+ const result = await installing+ this.authorized(row)+ if (!result.ok) {+ this.action(row, result.error ?? 'INSTALL_FAILED', result.detail ?? 'Installation failed', 'Open this package in Harness Store on this machine and resolve the reported install/setup/doctor error. A new key is a deliberate new attempt.'); return+ }+ pkg = (await this.deps.packages()).find(p => p.packageId === req.packageId)+ if (!pkg?.installed) throw new DeviceStoreError('INSTALL_UNCONFIRMED', 'Installation returned without a usable installed package')+ }+ if (pkg.broken) { this.action(row, 'PACKAGE_BROKEN', pkg.broken, 'Repair this installation in Harness Store.'); return }+ this.authorized(row)+ this.change(row, { phase: 'doctor' })+ const doctor = await this.deps.doctor(req.packageId)+ this.authorized(row)+ const lines = doctor.lines.slice(-10).map(l => l.slice(0, 400))+ this.checks.set(req.packageId, { state: !doctor.ok ? 'failed' : doctor.checked ? 'passed' : 'unknown', checkedAt: this.now(), version: pkg.version, lines })+ this.change(row, { doctor: lines })+ if (!doctor.ok) { this.action(row, 'DEPENDENCY_NOT_READY', lines.join('\n') || 'A package or viewer doctor failed', 'Resolve the doctor findings on this machine, then submit a new preparation key.'); return }+ this.change(row, { phase: 'workspace' })+ const cwd = await this.deps.workspace(req.workspace, pkg.name)+ this.authorized(row)+ // Never repurpose or materialize over another live session's project.+ if (this.workspaces.has(cwd) || this.deps.agents().some(a => a.workspace === cwd)) {+ this.action(row, 'WORKSPACE_IN_USE', 'A live agent already uses this workspace', 'Inspect Store candidates and explicitly use that agent with turn.send, or prepare a new workspace.'); return+ }+ this.workspaces.set(cwd, row.operation.operationId)+ this.change(row, { phase: 'create', workspace: cwd })+ const result = await this.receipts.run(row.operation.operationId, row.fingerprint, async () => {+ this.authorized(row)+ return this.deps.create(req.packageId, cwd)+ })+ if (result.state === 'created') {+ this.change(row, { phase: 'launch', agentId: result.agentId, guidance: 'Waiting for the native engine conversation. Open this agent in Harness if login or trust prompts need attention.' })+ } else if (result.state === 'failed') {+ this.action(row, result.error, result.detail ?? result.error, 'Open Harness on this machine to resolve the engine/workspace error.'); return+ } else {+ this.action(row, 'CREATION_UNCONFIRMED', 'Agent creation may have executed; it will not be repeated', 'Inspect existing agents on this machine before starting anything else.'); return+ }+ this.authorized(row)+ this.refreshRuntime(row)+ }+ private refreshRuntime(row: Journal): void {+ if (!row.operation.agentId || (row.operation.state !== 'running' && row.operation.state !== 'ready'+ && !['ENGINE_ACTION_REQUIRED', 'AGENT_UNAVAILABLE'].includes(row.operation.error?.code ?? ''))) return+ const agent = this.deps.agents().find(a => a.agentId === row.operation.agentId)+ if (agent?.packageId !== row.operation.packageId || agent?.workspace !== row.operation.workspace) {+ this.action(row, 'AGENT_UNAVAILABLE', 'The prepared agent is missing or its package/workspace changed', 'Inspect this agent in Harness; preparation never changes an existing session.'); return+ }+ if (agent.runtime === 'ready') {+ if (row.operation.state !== 'ready') this.change(row, { state: 'ready', phase: 'complete', error: null, guidance: null })+ } else if (agent.runtime === 'starting' && row.operation.state === 'ready') {+ this.change(row, { state: 'running', phase: 'launch', guidance: 'The engine is starting again; wait for its native conversation before sending a task.' })+ } else if (agent.runtime === 'unavailable' || this.now() - row.operation.updatedAt > 10 * 60_000) {+ this.action(row, 'ENGINE_ACTION_REQUIRED', agent.error ?? 'Engine launch is not ready; login, trust or installation may require interaction.', 'Open the returned agent in Harness and complete its engine prompts. Do not create another agent automatically.')+ }+ }+ get(deviceId: string, operationId: string): DeviceOperation {+ const row = this.read(operationId)+ if (!row || row.owner !== hash(deviceId)) throw new DeviceStoreError('OPERATION_NOT_FOUND', 'No preparation for this device has that ID')+ if (active(row.operation) && !this.live.has(operationId)) {+ const receipt = this.receipts.status(operationId)+ if (receipt.state === 'created' && row.operation.workspace) {+ this.change(row, { agentId: receipt.agentId, phase: 'launch', state: 'running' })+ this.live.set(operationId, row)+ } else {+ this.action(row, 'RECOVERY_REQUIRED', 'Daemon restarted during preparation; no install or creation will be replayed.', 'Inspect Harness and the workspace on this machine. Retry this same key to read its status; only deliberately use a new key after reconciling any side effects.')+ }+ }+ this.refreshRuntime(row)+ return structuredClone(row.operation)+ }+}diff --git a/cli/src/lib/autonomous-device/storeContract.spec.ts b/cli/src/lib/autonomous-device/storeContract.spec.tsnew file mode 100644index 000000000..56e0dbce8--- /dev/null+++ b/cli/src/lib/autonomous-device/storeContract.spec.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest'+import { readFileSync, mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { z } from 'zod'+import { DeviceStoreRequestSchema, DeviceStoreResultSchema } from './storeContract.js'+import { AutonomousDeviceStore } from './store.js'+import { AutonomousDeviceService } from './service.js'+const directory = new URL('../../../../docs/contracts/autonomous-device-store-v1/', import.meta.url)+describe('OS handoff contract', () => {+ it('keeps published JSON schemas identical to runtime validators', () => {+ for (const [name, schema] of [['request', DeviceStoreRequestSchema], ['response', DeviceStoreResultSchema]] as const) {+ if (name === 'request') {+ const json = z.toJSONSchema(schema, { io: 'input' }) as { oneOf: Array<{ required: string[] }> }+ expect(json.oneOf[0].required).toEqual(['type', 'requestId'])+ }+ expect(JSON.parse(readFileSync(new URL(`${name}.schema.json`, directory), 'utf8'))).toEqual(z.toJSONSchema(schema, { io: name === 'request' ? 'input' : 'output' }))+ }+ })+ it('validates fixtures and replays the Blender request sequence through the actual service', async () => {+ const fixture = JSON.parse(readFileSync(new URL('blender.fixture.json', directory), 'utf8'))+ const path = mkdtempSync(join(tmpdir(), 'device-contract-'))+ let installed = false, created = false+ const store = new AutonomousDeviceStore({ directory: path, machineId: 'mac-example',+ packages: async () => [{ packageId: 'autonomous/blender', name: 'Blender', description: '3D', category: '3D', engine: 'claude', installed,+ catalog: true, verified: true, viewerPackageId: null, installAllowed: true, version: null, broken: null }],+ install: async () => { installed = true; return { ok: true } }, doctor: async () => ({ ok: true, checked: true, lines: [] }),+ workspace: async () => '/Users/example/harnesses/airplane', create: async () => { created = true; return { state: 'created', agentId: 'agent-example' } },+ agents: () => created ? [{ agentId: 'agent-example', machineId: 'mac-example', packageId: 'autonomous/blender', workspace: '/Users/example/harnesses/airplane', engine: 'claude', state: 'idle', runtime: 'ready' }] : [],+ })+ let sent = 0+ const service = new AutonomousDeviceService({ machineId: 'mac-example', store,+ agents: () => created ? [{ agentId: 'agent-example', name: 'Airplane', engine: 'claude', state: 'idle' }] : [],+ submit: () => { sent++ }, cancelDelivery: () => true, stop: async () => true, answer: async () => true, recent: () => [] })+ try {+ for (const step of fixture.steps) {+ DeviceStoreRequestSchema.parse(step.request)+ if (step.response) DeviceStoreResultSchema.parse(step.response)+ if (step.request.type === 'operation.get') {+ await expect.poll(() => store.get(fixture.deviceIdentity, step.request.operationId).state).toBe('ready')+ }+ const actual = await service.request(fixture.deviceIdentity, step.request)+ DeviceStoreResultSchema.parse(actual)+ if (step.response?.operation) expect(actual).toMatchObject({ operation: { operationId: step.response.operation.operationId, state: step.response.operation.state, taskDispatched: false } })+ }+ // Invalid correlation fields are echoed when present, absent when missing.+ DeviceStoreResultSchema.parse(await service.request(fixture.deviceIdentity, { type: 'store.list' }))+ DeviceStoreResultSchema.parse(await service.request(fixture.deviceIdentity, { type: 'store.list', requestId: 'invalid' }))+ expect(sent).toBe(0)+ await service.request(fixture.deviceIdentity, fixture.taskRequest)+ await service.request(fixture.deviceIdentity, fixture.taskRequest)+ expect(sent).toBe(1)+ } finally { rmSync(path, { recursive: true, force: true }) }+ })+})diff --git a/cli/src/lib/autonomous-device/storeContract.ts b/cli/src/lib/autonomous-device/storeContract.tsnew file mode 100644index 000000000..8b8e2c914--- /dev/null+++ b/cli/src/lib/autonomous-device/storeContract.ts@@ -0,0 +1,60 @@+import { z } from 'zod'+import { DSH_ID_RE } from '../../dsh/manifest.js'++/** Device Store v1. Strict, deliberately smaller than the desktop/admin API. */+export const DEVICE_STORE_CAPABILITIES = ['store.list', 'store.inspect', 'agent.prepare', 'operation.get'] as const+const requestId = z.string().regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/)+const packageId = z.string().max(129).regex(DSH_ID_RE)+const safeText = z.string().min(1).max(4096).regex(/^[^\x00-\x1f\x7f]+$/)+export const WorkspaceSchema = z.discriminatedUnion('kind', [+ z.strictObject({ kind: z.literal('new'), name: z.string().min(1).max(100).regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).optional() }),+ z.strictObject({ kind: z.literal('existing'), path: safeText.regex(/^\//, 'Absolute path required') }),+])+export const DeviceStoreRequestSchema = z.discriminatedUnion('type', [+ z.strictObject({ type: z.literal('store.list'), requestId, query: z.string().max(200).optional(), offset: z.number().int().min(0).max(25000).default(0), limit: z.number().int().min(1).max(10).default(10) }),+ z.strictObject({ type: z.literal('store.inspect'), requestId, packageId }),+ z.strictObject({ type: z.literal('agent.prepare'), requestId, machineId: z.string().min(1).max(200), packageId,+ idempotencyKey: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), workspace: WorkspaceSchema }),+ z.strictObject({ type: z.literal('operation.get'), requestId, operationId: z.string().regex(/^[a-f0-9]{64}$/) }),+])+export type PrepareRequest = Extract<z.infer<typeof DeviceStoreRequestSchema>, { type: 'agent.prepare' }>+export const DeviceOperationSchema = z.strictObject({+ operationId: z.string().regex(/^[a-f0-9]{64}$/), machineId: z.string(), packageId: z.string(),+ state: z.enum(['accepted', 'running', 'ready', 'failed', 'needs_user_action']),+ phase: z.enum(['accepted', 'install', 'clone', 'setup', 'doctor', 'workspace', 'create', 'launch', 'complete']),+ createdAt: z.number(), updatedAt: z.number(), agentId: z.string().nullable(), workspace: z.string().nullable(),+ error: z.strictObject({ code: z.string(), message: z.string() }).nullable(),+ guidance: z.string().nullable(), doctor: z.array(z.string()).max(10),+ taskDispatched: z.literal(false),+ engineAuthentication: z.literal('unknown'),+})+export type DeviceOperation = z.infer<typeof DeviceOperationSchema>+export class DeviceStoreError extends Error {+ constructor(readonly code: string, message: string) { super(message) }+}++export const StoreAgentSchema = z.strictObject({+ agentId: z.string(), machineId: z.string(), packageId: z.string().nullable(), engine: z.string(),+ workspace: z.string().nullable(), state: z.string(), runtime: z.enum(['starting', 'ready', 'unavailable']), error: z.string().optional(),+})+export const StorePackageSchema = z.strictObject({+ packageId: z.string(), name: z.string(), description: z.string(), category: z.string().nullable(), engine: z.string().nullable(),+ installed: z.boolean(), catalog: z.boolean(), verified: z.boolean(), viewerPackageId: z.string().nullable(),+ installAllowed: z.boolean(), version: z.string().nullable(), broken: z.string().nullable(),+ capabilities: z.strictObject({ source: z.literal('package_metadata'), description: z.string(), category: z.string().nullable() }),+ requirements: z.strictObject({ engine: z.string().nullable(), viewerPackageId: z.string().nullable(), applications: z.null(), note: z.string() }),+ installation: z.enum(['installing', 'installed', 'not_installed', 'broken']),+ lastPreparation: z.strictObject({ state: DeviceOperationSchema.shape.state, phase: DeviceOperationSchema.shape.phase,+ error: DeviceOperationSchema.shape.error, updatedAt: z.number() }).nullable(),+ readiness: z.strictObject({ state: z.enum(['unknown', 'not_installed', 'passed', 'failed']), scope: z.literal('package_doctor'),+ engineAuthentication: z.literal('unknown'), taskSuccess: z.literal('unknown'), checkedAt: z.number().optional(),+ version: z.string().nullable().optional(), lines: z.array(z.string()).max(10).optional() }),+})+export const DeviceStoreResultSchema = z.union([+ z.strictObject({ type: z.literal('store.list_result'), requestId, machineId: z.string(), packages: z.array(StorePackageSchema).max(10), nextOffset: z.number().int().nullable() }),+ z.strictObject({ type: z.literal('store.inspect_result'), requestId, machineId: z.string(), package: StorePackageSchema, candidates: z.array(StoreAgentSchema).max(5), candidatesTruncated: z.boolean() }),+ z.strictObject({ type: z.literal('agent.prepare_result'), requestId, status: z.enum(['accepted', 'duplicate']), operation: DeviceOperationSchema }),+ z.strictObject({ type: z.literal('operation.get_result'), requestId, operation: DeviceOperationSchema }),+ z.strictObject({ type: z.enum(['store.list_result', 'store.inspect_result', 'agent.prepare_result', 'operation.get_result']), requestId: z.unknown().optional(),+ error: z.strictObject({ code: z.string(), message: z.string() }) }),+])diff --git a/cli/src/lib/autonomous-device/storeRuntime.spec.ts b/cli/src/lib/autonomous-device/storeRuntime.spec.tsnew file mode 100644index 000000000..645df8df3--- /dev/null+++ b/cli/src/lib/autonomous-device/storeRuntime.spec.ts@@ -0,0 +1,86 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { randomUUID } from 'node:crypto'+import type { RegisteredSession } from '../registry.js'+import type { DshRegistryEntry } from '../../dsh/registry.js'+const state = vi.hoisted(() => ({ agents: [] as RegisteredSession[], catalog: [] as DshRegistryEntry[] }))+vi.mock('../registry.js', () => ({ registry: { list: () => state.agents, terminalAvailable: () => true } }))+vi.mock('../../dsh/catalog.js', () => ({ refreshDshRegistry: async () => state.catalog, catalogEntry: (id: string) => state.catalog.find(e => e.id === id) }))+import { env } from '../../config/env.js'+import * as engineLaunch from '../engineLaunch.js'+import { installDsh } from '../../dsh/install.js'+import { installedDsh, invalidateInstalledDsh } from '../../dsh/installed.js'+import { materializeWorkspace } from '../../dsh/materialize.js'+import { createDeviceStore, deviceStorePackages } from './storeRuntime.js'+import { DeviceStoreResultSchema } from './storeContract.js'+import { HARNESS_MONOREPO } from '../../dsh/registry.js'++let root: string, original: string+beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'device-store-runtime-')))+ original = env.DSH_DIR; env.DSH_DIR = join(root, 'installed'); invalidateInstalledDsh()+ state.agents = []; state.catalog = []+ // Run real fixture shell scripts, without sourcing the operator's login profile.+ vi.spyOn(engineLaunch, 'interactiveEngineShell').mockReturnValue(null)+})+afterEach(() => { vi.restoreAllMocks(); env.DSH_DIR = original; invalidateInstalledDsh(); rmSync(root, { recursive: true, force: true }) })+async function setup() {+ const source = join(root, 'package'); mkdirSync(join(source, 'template'), { recursive: true })+ writeFileSync(join(source, 'harness.json'), JSON.stringify({ spec: 1, id: 'test/robot-fixture', name: 'Robot fixture', engine: 'claude',+ toolchain: { setup: 'setup.sh', doctor: 'doctor.sh' }, workspace: { template: 'template', marker: 'scene.txt' }, agent: { instructions: 'AGENTS.md' } }))+ writeFileSync(join(source, 'setup.sh'), '#!/bin/sh\nprintf installed > dependency\n', { mode: 0o755 })+ writeFileSync(join(source, 'doctor.sh'), '#!/bin/sh\nif [ -f dependency ]; then echo "ok dependency"; else echo "miss dependency"; exit 1; fi\n', { mode: 0o755 })+ writeFileSync(join(source, 'AGENTS.md'), 'Fixture instructions, no model calls.\n')+ writeFileSync(join(source, 'template', 'scene.txt'), 'fixture scene\n')+ const installed = await installDsh({ source, link: true })+ expect(installed.ok).toBe(true)+ const cwd = join(root, 'workspace'); mkdirSync(cwd)+ const create = vi.fn(async (input: Parameters<NonNullable<import('../../backendSocket.js').BackendSocket['onCreateAgent']>>[0]) => {+ await materializeWorkspace(installedDsh(input.dsh!)!, input.cwd)+ const session = { agentId: 'fixture-agent', sessionId: 'native-conversation', active: true, cwd: input.cwd, dsh: input.dsh, engine: input.engine, launch: { state: 'ready' } } as RegisteredSession+ state.agents.push(session)+ return { ok: true as const, session }+ })+ const store = createDeviceStore({ dataDir: join(root, 'state'), machineId: 'mac', create })+ const request = { type: 'agent.prepare', requestId: randomUUID(), machineId: 'mac', packageId: 'test/robot-fixture', workspace: { kind: 'existing', path: cwd }, idempotencyKey: 'prepare' }+ return { source, cwd, create, store, request }+}+describe('device Store production adapter with real local package scripts', () => {+ it('uses actual installed inventory, doctor and materialization with safe creation arguments', async () => {+ const f = await setup()+ const reply = await f.store.request('lamp', f.request)+ const id = (reply.operation as { operationId: string }).operationId+ await vi.waitFor(() => expect(f.store.get('lamp', id).state).toBe('ready'))+ expect(f.store.get('lamp', id).doctor).toEqual(['test/robot-fixture: ok dependency'])+ expect(f.create).toHaveBeenCalledWith(expect.objectContaining({ cwd: f.cwd, dsh: 'test/robot-fixture', prompt: null, bypassPermission: false, permissionMode: null, grid: null, codexHome: null }))+ const req = { type: 'store.inspect', requestId: randomUUID(), packageId: 'test/robot-fixture' }+ const response = { type: 'store.inspect_result', requestId: req.requestId, ...await f.store.request('lamp', req) }+ expect(DeviceStoreResultSchema.parse(response)).toMatchObject({ package: { installed: true, catalog: false, readiness: { state: 'passed' } }, candidates: [{ agentId: 'fixture-agent', runtime: 'ready' }] })+ })+ it('reports a real doctor failure without spawning', async () => {+ const f = await setup(); rmSync(join(f.source, 'dependency'))+ const reply = await f.store.request('lamp', f.request), id = (reply.operation as { operationId: string }).operationId+ await vi.waitFor(() => expect(f.store.get('lamp', id)).toMatchObject({ state: 'needs_user_action', error: { code: 'DEPENDENCY_NOT_READY' } }))+ expect(f.create).not.toHaveBeenCalled()+ })+ it('canonicalizes symlinks and refuses a workspace held by another session', async () => {+ const f = await setup(), link = join(root, 'alias'); symlinkSync(f.cwd, link)+ state.agents.push({ agentId: 'other', cwd: f.cwd, dsh: null, engine: 'codex', active: true } as RegisteredSession)+ const reply = await f.store.request('lamp', { ...f.request, workspace: { kind: 'existing', path: link } })+ const id = (reply.operation as { operationId: string }).operationId+ await vi.waitFor(() => expect(f.store.get('lamp', id)).toMatchObject({ error: { code: 'WORKSPACE_IN_USE' } }))+ expect(f.create).not.toHaveBeenCalled()+ })+ it('checks official source identity and all uninstalled viewer dependencies', async () => {+ const entry: DshRegistryEntry = { id: 'autonomous/blender', name: 'Blender', engine: 'claude', verified: true, repo: HARNESS_MONOREPO,+ path: 'store/agents/blender', viewerUse: 'autonomous/model-viewer' }+ state.catalog = [entry]+ expect(await deviceStorePackages()).toMatchObject([{ installAllowed: false }])+ state.catalog.push({ id: 'autonomous/model-viewer', name: '3D viewer', kind: 'viewer', verified: true, repo: HARNESS_MONOREPO, path: 'store/viewers/model-viewer' })+ expect(await deviceStorePackages()).toMatchObject([{ installAllowed: true }])+ state.catalog[1].repo = 'https://github.com/someone/else'+ expect(await deviceStorePackages()).toMatchObject([{ installAllowed: false }])+ })+})diff --git a/cli/src/lib/autonomous-device/storeRuntime.ts b/cli/src/lib/autonomous-device/storeRuntime.tsnew file mode 100644index 000000000..cf8856cf2--- /dev/null+++ b/cli/src/lib/autonomous-device/storeRuntime.ts@@ -0,0 +1,108 @@+/** Narrow adapter onto the SAME Store, project preparation and engine creator used by Desktop.+ * Never passes device frames to BackendSocket's generic dispatcher.+ */+import { realpathSync, statSync } from 'node:fs'+import { join } from 'node:path'+import type { BackendSocket } from '../../backendSocket.js'+import { refreshDshRegistry } from '../../dsh/catalog.js'+import { installedDsh, listDshState } from '../../dsh/installed.js'+import { runDshDoctor } from '../../dsh/install.js'+import { viewerUse } from '../../dsh/manifest.js'+import { HARNESS_MONOREPO, type DshRegistryEntry } from '../../dsh/registry.js'+import { mutateDsh } from '../../dsh/service.js'+import { prepareProjectFolder, ProjectFolderError } from '../projectFolder.js'+import { registry } from '../registry.js'+import { AutonomousDeviceStore, type StoreAgent, type StorePackage } from './store.js'+import { DeviceStoreError } from './storeContract.js'++const canonicalPath = (path: string | null): string | null => {+ if (!path) return null+ try { return realpathSync(path) } catch { return path }+}+export function deviceStoreAgents(machineId: string): StoreAgent[] {+ return registry.list().map(s => ({ agentId: s.agentId, machineId, packageId: s.dsh ? installedDsh(s.dsh)?.id ?? s.dsh : null,+ engine: s.engine, workspace: canonicalPath(s.cwd), state: s.active ? 'active' : 'inactive',+ runtime: !registry.terminalAvailable(s.agentId) || s.launch?.state === 'failed' ? 'unavailable'+ : s.launch?.state === 'starting' ? 'starting' : s.active ? (s.sessionId || s.engine === 'terminal' ? 'ready' : 'starting') : 'unavailable',+ ...(s.launch?.state === 'failed' ? { error: s.launch.detail ?? s.launch.error } : {}) }))+}+function trusted(entry: DshRegistryEntry | undefined): boolean {+ return !!entry && entry.verified === true && entry.repo.replace(/\.git$/, '') === HARNESS_MONOREPO+ && entry.id.startsWith('autonomous/') && entry.path === `store/${entry.kind === 'viewer' ? 'viewers' : 'agents'}/${entry.id.slice(11)}`+}+export async function deviceStorePackages(): Promise<StorePackage[]> {+ const catalog = await refreshDshRegistry()+ const { installed, broken } = listDshState()+ const ids = new Set([...catalog.filter(e => e.kind !== 'viewer').map(e => e.id), ...installed.filter(e => e.manifest.kind !== 'viewer').map(e => e.id), ...broken.map(e => e.id)])+ const byId = new Map(catalog.map(e => [e.id, e]))+ const allowed = (id: string, seen = new Set<string>()): boolean => {+ if (installedDsh(id)) return true // already installed by the owner+ if (seen.has(id)) return false+ seen.add(id)+ const e = byId.get(id)+ return trusted(e) && (!e?.viewerUse || allowed(e.viewerUse, seen))+ }+ return [...ids].sort().map(id => {+ const record = installed.find(e => e.id === id), entry = byId.get(id), bad = broken.find(e => e.id === id)+ const m = record?.manifest+ return { packageId: id, name: (m?.name ?? entry?.name ?? id).slice(0, 200), description: (m?.description ?? entry?.description ?? '').slice(0, 1000),+ category: m?.category ?? entry?.category ?? null, engine: m?.engine ?? entry?.engine ?? null,+ installed: !!record || !!bad, catalog: !!entry, verified: trusted(entry),+ viewerPackageId: m ? viewerUse(m) : entry?.viewerUse ?? null, installAllowed: allowed(id),+ version: record?.revision ?? record?.commit ?? null, broken: bad?.error.slice(0, 1000) ?? null }+ })+}++export function createDeviceStore(options: { dataDir: string; machineId: string; create: NonNullable<BackendSocket['onCreateAgent']> }): AutonomousDeviceStore {+ return new AutonomousDeviceStore({+ directory: join(options.dataDir, 'device-preparations'), machineId: options.machineId,+ packages: deviceStorePackages,+ agents: () => deviceStoreAgents(options.machineId),+ install: async (id, progress) => {+ const pkg = (await deviceStorePackages()).find(p => p.packageId === id)+ if (!pkg?.installAllowed) return { ok: false, error: 'PACKAGE_REVIEW_REQUIRED', detail: 'Review this package and its dependencies in Harness Store first.' }+ return mutateDsh({ id }, p => progress(p.phase))+ },+ doctor: async id => {+ const root = installedDsh(id)+ if (!root) return { ok: false, checked: false, lines: ['Package is not installed'] }+ const dependency = viewerUse(root.manifest)+ const viewer = dependency ? installedDsh(dependency) : undefined+ if (dependency && !viewer) return { ok: false, checked: false, lines: [`Missing viewer ${dependency}. Install it through Harness Store.`] }+ const lines: string[] = []+ let checked = true+ for (const pkg of [root, ...(viewer ? [viewer] : [])]) {+ checked &&= !!pkg.manifest.toolchain?.doctor+ const result = await runDshDoctor(pkg)+ lines.push(...result.lines.map(l => `${pkg.id}: ${l}`))+ if (!result.ok) return { ok: false, checked, lines }+ }+ return { ok: true, checked, lines }+ },+ workspace: async (request, label) => {+ if (request.kind === 'new') {+ try { return realpathSync(await prepareProjectFolder({ source: 'new', ...(request.name ? { name: request.name } : {}) }, { label })) }+ catch (error) {+ if (error instanceof ProjectFolderError) throw new DeviceStoreError(error.code, error.message)+ throw error+ }+ }+ try {+ const path = realpathSync(request.path)+ if (!statSync(path).isDirectory()) throw new Error('Not a directory')+ return path+ } catch { throw new DeviceStoreError('INVALID_WORKSPACE', 'Select an existing accessible directory, or request a new workspace.') }+ },+ create: async (id, cwd) => {+ const pkg = installedDsh(id)+ if (!pkg?.manifest.engine || pkg.manifest.kind === 'viewer') return { state: 'failed', error: 'INVALID_DSH' }+ // Check again immediately before materialization; never retarget another agent.+ if (deviceStoreAgents(options.machineId).some(a => a.workspace === cwd)) return { state: 'failed', error: 'WORKSPACE_IN_USE' }+ const result = await options.create({ engine: pkg.manifest.engine, cwd, dsh: id,+ bypassPermission: false, permissionMode: null, grid: null, codexHome: null, prompt: null, name: null, agent: null })+ if (result.ok) return { state: 'created', agentId: result.session.agentId }+ if (['SPAWN_FAILED', 'REGISTRATION_FAILED'].includes(result.error)) return { state: 'unconfirmed' }+ return { state: 'failed', error: result.error, detail: result.detail }+ },+ })+}diff --git a/docs/autonomous-device-integration.md b/docs/autonomous-device-integration.mdindex 3f0805af1..673388a24 100644--- a/docs/autonomous-device-integration.md+++ b/docs/autonomous-device-integration.md@@ -1,5 +1,10 @@# Autonomous device ↔ Mac: direct discovery and original Harness E2EE+## Store discovery and agent preparation (v1)++Paired robots can negotiate Store discovery and durable agent preparation separately from task delivery. See the [shared OS contract](autonomous-device-store.md), including JSON schemas, recovery rules and the Blender walkthrough. Older clients keep the operations below unchanged.++The Mac discovers Autonomous OS on the local network and connects **directly to the device**.No manual IP address, device backend credentials, cloud device registration, or backend relay isinvolved in this path. The existing Harness Mac login/start behavior is unchanged; an alreadydiff --git a/docs/autonomous-device-store.md b/docs/autonomous-device-store.mdnew file mode 100644index 000000000..f4db40171--- /dev/null+++ b/docs/autonomous-device-store.md@@ -0,0 +1,276 @@+# Autonomous robot → Harness Store contract, v1++This is the shared implementation contract for Autonomous OS (`harness-use` → OS loopback API →+existing direct encrypted device connection → Harness CLI). It adds Store discovery and **agent+preparation**, not task delivery. English and [Vietnamese](vi/autonomous-device-store_vi.md) describe+the same contract. The machine-readable authority is+[`contracts/autonomous-device-store-v1/`](contracts/autonomous-device-store-v1/).++**Status:** implemented in this checkout; not installed, released, or deployed by this change.+Do not assume a running CLI supports it until its hello advertises the capabilities below.+Once handed to OS, coordinate changes to operation names, meanings, required fields, errors and+schemas with the OS integrator. Regenerate the schemas and fixtures/tests together. Never silently+repurpose a v1 field.++## Transport and capability negotiation++Keep protocol `proto: 1`, pairing, identity pins, PAKE and E2EE envelopes from+[the existing integration](autonomous-device-integration.md). No new credentials, listener,+transport or pairing flow. These are **decrypted application payloads**, not plaintext LAN frames.+Each request uses a fresh UUIDv4 `requestId`; each response echoes it with `<type>_result`.++An authenticated role-device application `hello` advertises these additional capability strings:++```json+["store.list", "store.inspect", "agent.prepare", "operation.get"]+```++Require all four before offering automatic preparation. If missing, explain that the Harness CLI on+the paired computer needs updating. Existing operations and old OS clients remain compatible. An+unwired/older service returns `UNSUPPORTED_CAPABILITY`; do not try `dsh_install` or `agent_create`+over the device channel. Only the paired machine is addressable. Plaintext and non-device-role+requests never reach this facade; application hello and existing rate/concurrency limits still apply.++This permission permits installing official Store packages and their reviewed official dependencies+as the paired computer's user. Setup is real local execution, not a sandbox. Uninstalled community+packages or dependencies require the owner to review/install them in Desktop first. No URL/ref,+custom engine command, arbitrary shell, permission-bypass flag, update/remove, or generic admin+operation is accepted. Existing owner-installed packages can be used. Preparation always creates a+new agent with permission bypass off and no first prompt.++## Operations++### `store.list`++```json+{"type":"store.list","requestId":"11111111-1111-4111-8111-111111111111","query":"Blender","offset":0,"limit":5}+```++Result: `{type, requestId, machineId, packages:[Package], nextOffset:number|null}`.+`query` is optional (≤200 characters), matching all whitespace-separated terms in ID/name/description/+category. `offset` defaults to 0 (0–25000); `limit` defaults to 10 (1–10). Use `nextOffset` until null.+Pages are current snapshots, not a frozen catalog transaction. Viewer packages are dependencies,+not selectable agent entries. Installed unlisted packages remain discoverable.++### `store.inspect`++```json+{"type":"store.inspect","requestId":"22222222-2222-4222-8222-222222222222","packageId":"autonomous/blender"}+```++Result: `{type, requestId, machineId, package:Package, candidates:[Agent], candidatesTruncated:boolean}`.+At most five candidate agents are returned. Use existing `agents.list` for the remaining agents.+Candidates match **recorded package identity**, not an inferred name/recap; they are suggestions only.+Neither inspect nor prepare takes control of an existing session.++`Package` contains:++| Field | Meaning |+|---|---|+| `packageId`, `name`, `description`, `category`, `engine` | Catalog/installed manifest facts |+| `catalog`, `installed` | Independent booleans: being listed is not being installed |+| `verified`, `installAllowed` | Official source recognition and permission for automatic installation; not a security or usability guarantee |+| `viewerPackageId` | Known shared-viewer dependency, or null |+| `version`, `broken` | Installed tree/commit if known; broken installation reason or null |+| `capabilities` | `{source:"package_metadata",description,category}` — descriptive claims from metadata, not tested semantic capability tags |+| `requirements` | `{engine,viewerPackageId,applications:null,note}` — app/dependency names are not structured in current manifests; do not invent them |+| `installation` | `not_installed`, `installed`, `installing` (this service's active install), or `broken` |+| `readiness` | `{state,scope:"package_doctor",engineAuthentication:"unknown",taskSuccess:"unknown",checkedAt?,version?,lines?}` |+| `lastPreparation` | Latest in-memory preparation's `{state,phase,error,updatedAt}` for this package, or null; use operation.get for durable history |++Readiness is `not_installed`, `unknown`, `passed`, or `failed`. Merely listing/inspecting never runs+scripts. A prepare runs the package and shared viewer doctors and caches up to ten 400-character+output lines, time and version. A changed version or daemon restart invalidates that in-memory check.+A package without a doctor has unknown check coverage. A passed doctor is a dated observation, not+a promise that login, licensing, GPU capacity, all app features, or the user's task will work.+Installation done elsewhere may only be reflected when its installed index changes.++`Agent`: `{agentId,machineId,packageId,engine,workspace,state,runtime,error?}`.+`runtime` is `starting`, `ready`, or `unavailable`. `workspace` is a canonical absolute directory where+available. `agents.list` also gains optional `packageId`, `workspace`, and `runtime` fields. An absent/+null package identity is unknown, never inferred from recap. Runtime ready requires a live terminal,+engine process and bound native conversation (plain terminal tiles are a special case). Authentication+is not independently verified. Caller decides whether a candidate belongs to the user's intended+project; explicit use of that agent goes straight to existing `turn.send` without prepare.++### `agent.prepare`++```json+{+ "type":"agent.prepare",+ "requestId":"33333333-3333-4333-8333-333333333333",+ "machineId":"mac-example",+ "packageId":"autonomous/blender",+ "idempotencyKey":"prepare-airplane-001",+ "workspace":{"kind":"new","name":"airplane"}+}+```++Workspace is required, exactly one of:++- `{"kind":"new","name":"airplane"}`: same `~/harnesses/` convention as Desktop/`harness new`.+ Optional name is 1–100 ASCII letters/digits/`_`/`-`, beginning with a letter/digit. Without a name,+ Harness chooses its normal package/time folder name. An existing named folder is an error, not reused.+- `{"kind":"existing","path":"/Users/example/harnesses/airplane"}`: absolute existing directory,+ ≤4096 characters, no control characters. Symlinks are canonicalized. Owner explicitly selects it;+ materialization follows the package's normal instructions/template behavior. A workspace used by+ another registered agent is refused; prepare never changes that agent's project. Device requests+ competing for one canonical workspace are serialized/refused before creation.++No `text` or `prompt` is allowed. No implicit installation update. The implementation reuses catalog,+Store install/setup/doctor, `prepareProjectFolder`, `onCreateAgent` and `AgentCreationReceipts`.+Already-installed packages skip setup/install but run doctors again. Missing/unusable viewer or+application requirements produce action-needed with doctor evidence. A review-required dependency+is not silently installed. Broken installs are not overwritten.++The response is immediate after durable reservation:++```json+{+ "type":"agent.prepare_result",+ "requestId":"33333333-3333-4333-8333-333333333333",+ "status":"accepted",+ "operation":{+ "operationId":"c733824e9af646c6ff8d0e19f1e2e368d02608b0fe99b1f2936a4d740244829d",+ "machineId":"mac-example","packageId":"autonomous/blender",+ "state":"accepted","phase":"accepted",+ "createdAt":1790000000000,"updatedAt":1790000000000,+ "agentId":null,"workspace":null,"error":null,"guidance":null,"doctor":[],+ "taskDispatched":false,"engineAuthentication":"unknown"+ }+}+```++The ID above is illustrative; **store the returned ID**. Exact executable examples are in+[blender.fixture.json](contracts/autonomous-device-store-v1/blender.fixture.json).+Retry identical parameters and key with a new requestId → `status:"duplicate"`, same operation.+Changing any preparation parameter under the same key → `IDEMPOTENCY_CONFLICT`.++### `operation.get`++```json+{"type":"operation.get","requestId":"44444444-4444-4444-8444-444444444444","operationId":"c733824e9af646c6ff8d0e19f1e2e368d02608b0fe99b1f2936a4d740244829d"}+```++Result: `{type:"operation.get_result",requestId,operation:Operation}`. Query on the same paired+identity. An unknown ID or another device's ID returns `OPERATION_NOT_FOUND`.+Poll about every 2 seconds, back off on rate limiting. There is **no new progress event in v1**;+`operation.get` is the authoritative status/progress mechanism. Existing event replay/resync and+`serverInstanceId` still apply to turn delivery. After reconnect/resync, poll retained operation IDs.++| State | Meaning and caller action |+|---|---|+| `accepted` | Intent persisted; nothing should be inferred about install/create yet |+| `running` | Work or engine startup in progress; keep polling the same operation |+| `ready` | Package preparation completed and the returned agent's runtime/conversation is available; task has NOT been sent |+| `failed` | Definite failure such as package not found; inspect error before a deliberate new attempt |+| `needs_user_action` | Show `error.message` and `guidance`; may mean dependency/login/workspace repair or uncertain side effects; never blindly create again |++Phases: `accepted → install / clone / setup → doctor → workspace → create → launch → complete`.+Installed packages skip clone/setup. Shared dependencies may repeat installation phases.+`createdAt`/`updatedAt` are Unix milliseconds, doctor output is bounded. `agentId` may already be+present before ready or alongside an action-needed error: open that agent, do not create a duplicate.+No task is dispatched in any state; `taskDispatched` is always false.++Ready is a **preparation** result, not an airplane, tool output, login certification, or model success.+`engineAuthentication:"unknown"` is explicit. If launch/binding is absent for ten minutes, polling+reports `ENGINE_ACTION_REQUIRED`; a known launch failure reports it sooner. Complete engine prompts+in the returned agent and poll again: the same operation can become ready, without creating again.+If an agent disappears/changes workspace, a previously ready operation can require action again.++## Idempotency, timeout and recovery++- Preparation key scope is `(paired identity, idempotencyKey)` on this machine; keys use 1–64+ ASCII letters/digits/`_`/`-`. Parameters are fingerprinted; requestId is excluded.+- Reserve an operation privately on disk before install/workspace/create. Operation journals and+ creation receipts are **not expired automatically**. Preserve them under `ADAPTER_DATA_DIR`.+- Four active preparation jobs maximum; concurrent device requests for one package share its install.+ Existing Store package locks also cover Desktop/CLI mutations. `DSH_BUSY` can require waiting for+ an external installer; it does not authorize a parallel setup.+- RPC timeout/disconnect does not cancel accepted work. Retry the same prepare key/parameters to+ recover the operation ID, or poll it. Never infer “not executed” from a timeout.+- On daemon restart, a completed creation receipt can recover agentId even if the final operation+ update was lost. It is rechecked against registry package/workspace/runtime; it is never recreated.+- A persisted interrupted operation without confirmed creation becomes `needs_user_action` /+ `RECOVERY_REQUIRED`. No install, setup, folder creation or agent launch is replayed automatically.+ The owner inspects the machine first. A new key means a deliberate new operation and can create+ another session; OS must not manufacture new keys as a retry strategy.+- If pairing is revoked, already-running setup/doctor/spawn cannot necessarily be undone. Future+ preparation steps stop at the next boundary. Created files/agents may remain for inspection.+ No automatic delete or rollback of user work. Revoked transports cannot read/send more requests.+- Preparation receipts are separate from `receipt.get` (which remains for turn/stop/answer). The+ latter's existing in-memory delivery dedupe does **not** become durable with this change.+ After an ambiguous `turn.send` across a daemon restart, inspect/reconcile; do not resend just+ because the old receipt is absent. Consult `serverInstanceId` and existing recovery rules.++## Errors++Before reservation, errors have `{type,requestId,error:{code,message}}` and no operation. After+acceptance, inspect `operation.error` and `operation.guidance`, including on duplicate replies.++| Code | Handling |+|---|---|+| `UNSUPPORTED_CAPABILITY`, `PROTO_UNSUPPORTED` | Update CLI/use supported interface; no generic dispatcher fallback |+| `HELLO_REQUIRED`, `RATE_LIMITED`, `BACKPRESSURE` | Establish existing session / back off; preserve keys |+| `INVALID_REQUEST`, `MACHINE_MISMATCH` | Fix request schema/target; unknown fields rejected |+| `PACKAGE_NOT_FOUND` | Refresh catalog, choose an actual package |+| `PACKAGE_REVIEW_REQUIRED` | Owner reviews/installs package or dependency in Desktop |+| `PACKAGE_BROKEN`, `DEPENDENCY_NOT_READY` | Show bounded doctor/broken-install findings; repair locally |+| `INVALID_WORKSPACE`, `WORKSPACE_IN_USE` | Choose a suitable project or explicitly select an existing candidate |+| `IDEMPOTENCY_CONFLICT` | Same intent key was reused with different parameters; reconcile caller state |+| `OPERATION_NOT_FOUND` | Wrong/missing ID, identity or state storage; never assume work did not execute |+| `STORAGE_FAILED` | Cannot safely read/reserve/persist; inspect local state, retry same key only |+| `INSTALL_UNCONFIRMED`, `CREATION_UNCONFIRMED`, `PREPARATION_UNCONFIRMED`, `RECOVERY_REQUIRED` | Side effects may exist; inspect before any new attempt |+| `ENGINE_ACTION_REQUIRED`, `AGENT_UNAVAILABLE` | Open returned agent on machine, resolve launch/login/trust or stale target |+| `REVOKED` | Preparation authorization ended; inspect any already-created artifacts |+| `INTERNAL` | No confirmed result; retry same key or poll, not a new intent |++Existing Store/creator error codes can also be carried without rewriting their meaning, e.g.+`CLONE_FAILED`, `SETUP_FAILED`, `DOCTOR_FAILED`, `DSH_BUSY`, `TMUX_UNAVAILABLE`, `CWD_NOT_FOUND`,+`TMUX_TOO_OLD_FOR_DSH`, `PROJECT_EXISTS`, `PROJECT_PREPARATION_FAILED`. Consumers must display unknown+codes and guidance, not treat them as success. Setup error details can be tool/platform-specific.++## Full Blender flow and OS implementation checklist++1. Persist an OS user intent for “I want to use Blender to draw an airplane for me.” Negotiate all+ four capabilities. Never infer Blender readiness from an agent's name or recap.+2. `store.list(query:"Blender")` → select `autonomous/blender`; `store.inspect` → inspect metadata,+ installation, doctor evidence and candidates. If the user explicitly chooses a suitable existing+ candidate, use its exact machine/agent IDs instead of preparing another session.+3. Otherwise persist `prepare-airplane-001` and workspace choice before sending `agent.prepare`.+ Store returned operationId. Poll; narrate installation/checking/launching. Surface action-needed+ exactly, including authentication uncertainty. Let Harness own tool setup.+4. At `ready`, persist returned machineId/agentId and a **different** task key, `task-airplane-001`.+ Send the original user task once through existing `turn.send`:++ ```json+ {"type":"turn.send","requestId":"55555555-5555-4555-8555-555555555555","machineId":"mac-example","agentId":"agent-example","idempotencyKey":"task-airplane-001","text":"Use Blender to draw an airplane for me."}+ ```++ Do not bind this explicit returned target to unrelated app focus. Do not send the task in prepare,+ workspace name, an install script or an extra first-prompt call.+5. Persist delivery receipt/serverInstanceId and follow `receipt.get`, status, turn events, questions+ and recap. Existing `question.answer` cannot approve tool permissions; surface such prompts in+ Desktop. Announce actual completion from the agent's result, not from prepare being ready.+6. OS needs operation polling, durable intent/keys, capability fallback, candidate selection and+ action-needed presentation. It needs **no Blender-specific install commands or credentials**.++## Validation and limits++Automated coverage: catalog/installed/unknown readiness, package install coalescing, real local+fixture setup/doctor/materialization, permission-safe creator arguments, readiness transitions,+deduplication/reconnect, durable restart and spawn/journal recovery, workspace/symlink collisions,+revocation boundaries, errors, capability/role/encryption gates, strict schemas and replayed fixtures.+Creation/model boundary is mocked in these tests. Fixture doctor lines in the Blender JSON are+synthetic examples. This change has not installed Blender, driven a real robot, started a paid model+session, or rendered an airplane. Existing Store/creation regression suites provide additional+coverage but do not replace a future joint Lamp → real Blender acceptance test.++Regenerate/check schemas from runtime validators:++```sh+cd cli+npx tsx scripts/device-store-contract.ts+npx tsx scripts/device-store-contract.ts --check+npx vitest run src/lib/autonomous-device --maxWorkers=1+```diff --git a/docs/contracts/autonomous-device-store-v1/README.md b/docs/contracts/autonomous-device-store-v1/README.mdnew file mode 100644index 000000000..fda7080f9--- /dev/null+++ b/docs/contracts/autonomous-device-store-v1/README.md@@ -0,0 +1,28 @@+# Shared OS contract: Autonomous device Store v1++Start with [English](../../autonomous-device-store.md) or+[Tiếng Việt](../../vi/autonomous-device-store_vi.md).++- `request.schema.json`: decrypted request payloads, including optional input defaults.+- `response.schema.json`: successful responses and errors for the four new operations.+- `blender.fixture.json`: executable synthetic Blender walkthrough and a separate existing+ `turn.send` request. Agent IDs, timestamps and doctor output are examples, not a real render.++Schemas are generated from `cli/src/lib/autonomous-device/storeContract.ts`. Tests compare them to+the runtime validators and replay the fixture through the real service with mocked engine/install+boundaries. The separate runtime tests run real fixture setup/doctor/materialization scripts.++```sh+cd cli+npx tsx scripts/device-store-contract.ts --check+npx vitest run src/lib/autonomous-device --maxWorkers=1+```++The new capabilities are `store.list`, `store.inspect`, `agent.prepare`, `operation.get`.+Progress uses polling, not a new event type. `prepare` never sends a task. A timeout is not proof+that no work happened. Keep preparation keys and task keys separate, and read the recovery section+before implementing retries.++This is a source-level handoff, not a published release. Check the running CLI's hello capabilities.+If this contract changes after OS integration begins, coordinate both sides and update this bundle,+its generated schemas, both language guides and the matching fixtures/tests together.diff --git a/docs/contracts/autonomous-device-store-v1/VALIDATION.md b/docs/contracts/autonomous-device-store-v1/VALIDATION.mdnew file mode 100644index 000000000..d9f72bcc2--- /dev/null+++ b/docs/contracts/autonomous-device-store-v1/VALIDATION.md@@ -0,0 +1,46 @@+# Validation — 2026-09-23++Source changes only. No commit/push, daemon restart, live CLI installation, robot deployment,+Blender installation, paid model task or airplane render was performed.++Verified:++- TypeScript typecheck: passed.+- CLI build (`npm --prefix cli run build`): passed.+- Device suite: 117 tests passed in 8 files (includes the added restart/readiness regression).+- Broader Store/install/update/catalog/materialization, project folder, creation receipt,+ backend DSH and device regression run: 234 passed in 16 files, before the one additional+ device restart/readiness test. These counts overlap; do not add them.+- Final schema/fixture tests: 2 passed after checking malformed requestId error responses.+- Generated request/response JSON schemas match runtime Zod validators. Request defaults are+ optional inputs; invalid/missing requestId can be echoed/omitted in error responses.+- `git diff --check`: passed.++The first broader run used `/bin/sh` and one pre-existing materialization test saw an extra+`logout` line from that interactive shell. Re-running with `/bin/zsh` and an empty temporary+`ZDOTDIR` passed the full selected regression suite. Product shell behavior was not changed.+Runtime adapter tests use real temporary setup/doctor scripts and workspace materialization;+only their shell selection is isolated from the operator's profile. Engine creation is mocked.+Other device tests use isolated temporary durable journals/creation receipts and mock package+or engine boundaries. Transport tests verify role, encryption and hello gating at the existing+relay seam; this is not a physical Lamp acceptance run.++Reproduce the broader selection from `cli/` with an empty temporary ZDOTDIR:++```sh+SHELL=/bin/zsh ZDOTDIR=/path/to/empty-test-zdot npx vitest run \+ src/lib/autonomous-device \+ src/lib/agentCreationReceipt.spec.ts src/lib/projectFolder.spec.ts \+ src/dsh/catalog.spec.ts src/dsh/install.spec.ts src/dsh/materialize.spec.ts \+ src/dsh/service.spec.ts src/dsh/update.spec.ts src/backendSocket.dsh.spec.ts \+ --maxWorkers=1+npm run typecheck+npx tsx scripts/device-store-contract.ts --check+npm run build+```++Next joint acceptance: install the new CLI through the machine's authorized lifecycle helper,+verify existing LAN connectivity, confirm all four capabilities in a real Lamp hello, then run+discover → inspect → prepare/poll → separate turn.send against Blender. Record actual engine+login/permission prompts and generated artifacts. OS must not report a rendered airplane from+this validation or from preparation reaching ready.diff --git a/docs/contracts/autonomous-device-store-v1/blender.fixture.json b/docs/contracts/autonomous-device-store-v1/blender.fixture.jsonnew file mode 100644index 000000000..e02fb0e7d--- /dev/null+++ b/docs/contracts/autonomous-device-store-v1/blender.fixture.json@@ -0,0 +1,93 @@+{+ "fixtureOnly": true,+ "deviceIdentity": "lamp-fixture",+ "steps": [+ {+ "request": {+ "type": "store.list",+ "requestId": "11111111-1111-4111-8111-111111111111",+ "query": "Blender",+ "limit": 5+ }+ },+ {+ "request": {+ "type": "store.inspect",+ "requestId": "22222222-2222-4222-8222-222222222222",+ "packageId": "autonomous/blender"+ }+ },+ {+ "request": {+ "type": "agent.prepare",+ "requestId": "33333333-3333-4333-8333-333333333333",+ "machineId": "mac-example",+ "packageId": "autonomous/blender",+ "idempotencyKey": "prepare-airplane-001",+ "workspace": {+ "kind": "new",+ "name": "airplane"+ }+ },+ "response": {+ "type": "agent.prepare_result",+ "requestId": "33333333-3333-4333-8333-333333333333",+ "status": "accepted",+ "operation": {+ "operationId": "c733824e9af646c6ff8d0e19f1e2e368d02608b0fe99b1f2936a4d740244829d",+ "machineId": "mac-example",+ "packageId": "autonomous/blender",+ "state": "accepted",+ "phase": "accepted",+ "createdAt": 1790000000000,+ "updatedAt": 1790000000000,+ "agentId": null,+ "workspace": null,+ "error": null,+ "guidance": null,+ "doctor": [],+ "taskDispatched": false,+ "engineAuthentication": "unknown"+ }+ }+ },+ {+ "request": {+ "type": "operation.get",+ "requestId": "44444444-4444-4444-8444-444444444444",+ "operationId": "c733824e9af646c6ff8d0e19f1e2e368d02608b0fe99b1f2936a4d740244829d"+ },+ "response": {+ "type": "operation.get_result",+ "requestId": "44444444-4444-4444-8444-444444444444",+ "operation": {+ "operationId": "c733824e9af646c6ff8d0e19f1e2e368d02608b0fe99b1f2936a4d740244829d",+ "machineId": "mac-example",+ "packageId": "autonomous/blender",+ "state": "ready",+ "phase": "complete",+ "createdAt": 1790000000000,+ "updatedAt": 1790000010000,+ "agentId": "agent-example",+ "workspace": "/Users/example/harnesses/airplane",+ "error": null,+ "guidance": null,+ "doctor": [+ "autonomous/blender: ok blender 4.5",+ "autonomous/model-viewer: ok viewer"+ ],+ "taskDispatched": false,+ "engineAuthentication": "unknown"+ }+ }+ }+ ],+ "taskRequest": {+ "type": "turn.send",+ "requestId": "55555555-5555-4555-8555-555555555555",+ "machineId": "mac-example",+ "agentId": "agent-example",+ "idempotencyKey": "task-airplane-001",+ "text": "Use Blender to draw an airplane for me."+ }+}diff --git a/docs/contracts/autonomous-device-store-v1/request.schema.json b/docs/contracts/autonomous-device-store-v1/request.schema.jsonnew file mode 100644index 000000000..70eb4f9fe--- /dev/null+++ b/docs/contracts/autonomous-device-store-v1/request.schema.json@@ -0,0 +1,172 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "store.list"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "query": {+ "type": "string",+ "maxLength": 200+ },+ "offset": {+ "default": 0,+ "type": "integer",+ "minimum": 0,+ "maximum": 25000+ },+ "limit": {+ "default": 10,+ "type": "integer",+ "minimum": 1,+ "maximum": 10+ }+ },+ "required": [+ "type",+ "requestId"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "store.inspect"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "packageId": {+ "type": "string",+ "maxLength": 129,+ "pattern": "^[a-z0-9][a-z0-9-]{0,63}\\/[a-z0-9][a-z0-9-]{0,63}$"+ }+ },+ "required": [+ "type",+ "requestId",+ "packageId"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "agent.prepare"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "machineId": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "packageId": {+ "type": "string",+ "maxLength": 129,+ "pattern": "^[a-z0-9][a-z0-9-]{0,63}\\/[a-z0-9][a-z0-9-]{0,63}$"+ },+ "idempotencyKey": {+ "type": "string",+ "pattern": "^[A-Za-z0-9_-]{1,64}$"+ },+ "workspace": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "new"+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 100,+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9_-]*$"+ }+ },+ "required": [+ "kind"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "existing"+ },+ "path": {+ "type": "string",+ "minLength": 1,+ "maxLength": 4096,+ "allOf": [+ {+ "pattern": "^[^\\x00-\\x1f\\x7f]+$"+ },+ {+ "pattern": "^\\/"+ }+ ]+ }+ },+ "required": [+ "kind",+ "path"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "required": [+ "type",+ "requestId",+ "machineId",+ "packageId",+ "idempotencyKey",+ "workspace"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "operation.get"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "operationId": {+ "type": "string",+ "pattern": "^[a-f0-9]{64}$"+ }+ },+ "required": [+ "type",+ "requestId",+ "operationId"+ ],+ "additionalProperties": false+ }+ ]+}diff --git a/docs/contracts/autonomous-device-store-v1/response.schema.json b/docs/contracts/autonomous-device-store-v1/response.schema.jsonnew file mode 100644index 000000000..58f068023--- /dev/null+++ b/docs/contracts/autonomous-device-store-v1/response.schema.json@@ -0,0 +1,1063 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "store.list_result"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "machineId": {+ "type": "string"+ },+ "packages": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "packageId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "category": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "engine": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "installed": {+ "type": "boolean"+ },+ "catalog": {+ "type": "boolean"+ },+ "verified": {+ "type": "boolean"+ },+ "viewerPackageId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "installAllowed": {+ "type": "boolean"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "broken": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "capabilities": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "const": "package_metadata"+ },+ "description": {+ "type": "string"+ },+ "category": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "source",+ "description",+ "category"+ ],+ "additionalProperties": false+ },+ "requirements": {+ "type": "object",+ "properties": {+ "engine": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "viewerPackageId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "applications": {+ "type": "null"+ },+ "note": {+ "type": "string"+ }+ },+ "required": [+ "engine",+ "viewerPackageId",+ "applications",+ "note"+ ],+ "additionalProperties": false+ },+ "installation": {+ "type": "string",+ "enum": [+ "installing",+ "installed",+ "not_installed",+ "broken"+ ]+ },+ "lastPreparation": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "state": {+ "type": "string",+ "enum": [+ "accepted",+ "running",+ "ready",+ "failed",+ "needs_user_action"+ ]+ },+ "phase": {+ "type": "string",+ "enum": [+ "accepted",+ "install",+ "clone",+ "setup",+ "doctor",+ "workspace",+ "create",+ "launch",+ "complete"+ ]+ },+ "error": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "updatedAt": {+ "type": "number"+ }+ },+ "required": [+ "state",+ "phase",+ "error",+ "updatedAt"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "readiness": {+ "type": "object",+ "properties": {+ "state": {+ "type": "string",+ "enum": [+ "unknown",+ "not_installed",+ "passed",+ "failed"+ ]+ },+ "scope": {+ "type": "string",+ "const": "package_doctor"+ },+ "engineAuthentication": {+ "type": "string",+ "const": "unknown"+ },+ "taskSuccess": {+ "type": "string",+ "const": "unknown"+ },+ "checkedAt": {+ "type": "number"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "lines": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "state",+ "scope",+ "engineAuthentication",+ "taskSuccess"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "packageId",+ "name",+ "description",+ "category",+ "engine",+ "installed",+ "catalog",+ "verified",+ "viewerPackageId",+ "installAllowed",+ "version",+ "broken",+ "capabilities",+ "requirements",+ "installation",+ "lastPreparation",+ "readiness"+ ],+ "additionalProperties": false+ }+ },+ "nextOffset": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "type",+ "requestId",+ "machineId",+ "packages",+ "nextOffset"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "store.inspect_result"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "machineId": {+ "type": "string"+ },+ "package": {+ "type": "object",+ "properties": {+ "packageId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "category": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "engine": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "installed": {+ "type": "boolean"+ },+ "catalog": {+ "type": "boolean"+ },+ "verified": {+ "type": "boolean"+ },+ "viewerPackageId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "installAllowed": {+ "type": "boolean"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "broken": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "capabilities": {+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "const": "package_metadata"+ },+ "description": {+ "type": "string"+ },+ "category": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "source",+ "description",+ "category"+ ],+ "additionalProperties": false+ },+ "requirements": {+ "type": "object",+ "properties": {+ "engine": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "viewerPackageId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "applications": {+ "type": "null"+ },+ "note": {+ "type": "string"+ }+ },+ "required": [+ "engine",+ "viewerPackageId",+ "applications",+ "note"+ ],+ "additionalProperties": false+ },+ "installation": {+ "type": "string",+ "enum": [+ "installing",+ "installed",+ "not_installed",+ "broken"+ ]+ },+ "lastPreparation": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "state": {+ "type": "string",+ "enum": [+ "accepted",+ "running",+ "ready",+ "failed",+ "needs_user_action"+ ]+ },+ "phase": {+ "type": "string",+ "enum": [+ "accepted",+ "install",+ "clone",+ "setup",+ "doctor",+ "workspace",+ "create",+ "launch",+ "complete"+ ]+ },+ "error": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "updatedAt": {+ "type": "number"+ }+ },+ "required": [+ "state",+ "phase",+ "error",+ "updatedAt"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "readiness": {+ "type": "object",+ "properties": {+ "state": {+ "type": "string",+ "enum": [+ "unknown",+ "not_installed",+ "passed",+ "failed"+ ]+ },+ "scope": {+ "type": "string",+ "const": "package_doctor"+ },+ "engineAuthentication": {+ "type": "string",+ "const": "unknown"+ },+ "taskSuccess": {+ "type": "string",+ "const": "unknown"+ },+ "checkedAt": {+ "type": "number"+ },+ "version": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "lines": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "state",+ "scope",+ "engineAuthentication",+ "taskSuccess"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "packageId",+ "name",+ "description",+ "category",+ "engine",+ "installed",+ "catalog",+ "verified",+ "viewerPackageId",+ "installAllowed",+ "version",+ "broken",+ "capabilities",+ "requirements",+ "installation",+ "lastPreparation",+ "readiness"+ ],+ "additionalProperties": false+ },+ "candidates": {+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "agentId": {+ "type": "string"+ },+ "machineId": {+ "type": "string"+ },+ "packageId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "engine": {+ "type": "string"+ },+ "workspace": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "state": {+ "type": "string"+ },+ "runtime": {+ "type": "string",+ "enum": [+ "starting",+ "ready",+ "unavailable"+ ]+ },+ "error": {+ "type": "string"+ }+ },+ "required": [+ "agentId",+ "machineId",+ "packageId",+ "engine",+ "workspace",+ "state",+ "runtime"+ ],+ "additionalProperties": false+ }+ },+ "candidatesTruncated": {+ "type": "boolean"+ }+ },+ "required": [+ "type",+ "requestId",+ "machineId",+ "package",+ "candidates",+ "candidatesTruncated"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "agent.prepare_result"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "status": {+ "type": "string",+ "enum": [+ "accepted",+ "duplicate"+ ]+ },+ "operation": {+ "type": "object",+ "properties": {+ "operationId": {+ "type": "string",+ "pattern": "^[a-f0-9]{64}$"+ },+ "machineId": {+ "type": "string"+ },+ "packageId": {+ "type": "string"+ },+ "state": {+ "type": "string",+ "enum": [+ "accepted",+ "running",+ "ready",+ "failed",+ "needs_user_action"+ ]+ },+ "phase": {+ "type": "string",+ "enum": [+ "accepted",+ "install",+ "clone",+ "setup",+ "doctor",+ "workspace",+ "create",+ "launch",+ "complete"+ ]+ },+ "createdAt": {+ "type": "number"+ },+ "updatedAt": {+ "type": "number"+ },+ "agentId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "workspace": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "error": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "guidance": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "doctor": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "taskDispatched": {+ "type": "boolean",+ "const": false+ },+ "engineAuthentication": {+ "type": "string",+ "const": "unknown"+ }+ },+ "required": [+ "operationId",+ "machineId",+ "packageId",+ "state",+ "phase",+ "createdAt",+ "updatedAt",+ "agentId",+ "workspace",+ "error",+ "guidance",+ "doctor",+ "taskDispatched",+ "engineAuthentication"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "type",+ "requestId",+ "status",+ "operation"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "operation.get_result"+ },+ "requestId": {+ "type": "string",+ "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"+ },+ "operation": {+ "type": "object",+ "properties": {+ "operationId": {+ "type": "string",+ "pattern": "^[a-f0-9]{64}$"+ },+ "machineId": {+ "type": "string"+ },+ "packageId": {+ "type": "string"+ },+ "state": {+ "type": "string",+ "enum": [+ "accepted",+ "running",+ "ready",+ "failed",+ "needs_user_action"+ ]+ },+ "phase": {+ "type": "string",+ "enum": [+ "accepted",+ "install",+ "clone",+ "setup",+ "doctor",+ "workspace",+ "create",+ "launch",+ "complete"+ ]+ },+ "createdAt": {+ "type": "number"+ },+ "updatedAt": {+ "type": "number"+ },+ "agentId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "workspace": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "error": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "guidance": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "doctor": {+ "maxItems": 10,+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "taskDispatched": {+ "type": "boolean",+ "const": false+ },+ "engineAuthentication": {+ "type": "string",+ "const": "unknown"+ }+ },+ "required": [+ "operationId",+ "machineId",+ "packageId",+ "state",+ "phase",+ "createdAt",+ "updatedAt",+ "agentId",+ "workspace",+ "error",+ "guidance",+ "doctor",+ "taskDispatched",+ "engineAuthentication"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "type",+ "requestId",+ "operation"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": [+ "store.list_result",+ "store.inspect_result",+ "agent.prepare_result",+ "operation.get_result"+ ]+ },+ "requestId": {},+ "error": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "type",+ "error"+ ],+ "additionalProperties": false+ }+ ]+}diff --git a/docs/vi/autonomous-device-integration_vi.md b/docs/vi/autonomous-device-integration_vi.mdindex 4fa4adf35..9156704e2 100644--- a/docs/vi/autonomous-device-integration_vi.md+++ b/docs/vi/autonomous-device-integration_vi.md@@ -1,5 +1,10 @@# Autonomous device ↔ Mac trực tiếp+## Khám phá Store và chuẩn bị agent (v1)++Robot đã pair có thể negotiate capability Store và chuẩn bị agent, tách biệt với giao task. Xem [contract chung cho phía OS](autonomous-device-store_vi.md), gồm JSON schemas, recovery và ví dụ Blender. Các operation cũ giữ tương thích.++Mac tự tìm Autonomous OS qua service Avahi `_autonomous._tcp` đang có, dùng bonjour-servicebrowse ba giây. Không nhập IP, không backend relay hoặc credential cloud trên thiết bị. Giữlogin/start của Harness Mac như cũ; daemon đang chạy vẫn pair/điều khiển khi backend offline.diff --git a/docs/vi/autonomous-device-store_vi.md b/docs/vi/autonomous-device-store_vi.mdnew file mode 100644index 000000000..e44ae36f8--- /dev/null+++ b/docs/vi/autonomous-device-store_vi.md@@ -0,0 +1,230 @@+# Contract Autonomous robot → Harness Store, v1++Đây là tài liệu tích hợp chung cho phía Autonomous OS và OpenHarness. Luồng giữ nguyên:+`harness-use → OS loopback API → direct encrypted device connection → Harness CLI`.+[Bản English](../autonomous-device-store.md) mô tả cùng contract; nguồn máy đọc được là+[JSON schemas và fixture Blender](../contracts/autonomous-device-store-v1/).++**Trạng thái:** đã triển khai trong checkout này, chưa cài vào daemon đang chạy, chưa release hay+triển khai lên robot. OS phải kiểm tra capabilities khi hello, không suy đoán từ số phiên bản.+Sau bàn giao, mọi thay đổi contract phải được thông báo cho phía OS và cập nhật đồng bộ schemas,+fixtures, tests và hai bản tài liệu. Không âm thầm đổi nghĩa field/operation v1.++## Kết nối, capability và quyền++Giữ `proto:1`, pairing, PAKE, identity pin và E2EE của integration hiện có. JSON dưới đây là+**payload sau giải mã**, không gửi plaintext trên LAN. Mỗi RPC có `requestId` UUIDv4 mới; response+là `<type>_result`, echo đúng requestId.++OS chỉ bật tự động chuẩn bị khi `hello_result.capabilities` có đủ:++```json+["store.list", "store.inspect", "agent.prepare", "operation.get"]+```++CLI cũ/chưa nối service trả `UNSUPPORTED_CAPABILITY`; báo cần cập nhật CLI trên máy đã pair.+Không dùng `dsh_install`, `agent_create` hoặc generic dispatcher để lách capability. OS cũ vẫn hoạt+động như trước. Chỉ xử lý máy đã pair; vẫn cần role-device đã xác thực, ciphertext và application+hello. Rate limit/concurrency limit của interface cũ giữ nguyên.++Device có thể yêu cầu cài package chính thức và dependency chính thức đã được nhận diện trong Store.+Setup thực thi thật dưới quyền tài khoản trên máy, không phải sandbox. Package/dependency cộng đồng+chưa cài yêu cầu chủ máy review/cài qua Desktop. Package đã được chủ máy cài có thể dùng.+Không nhận URL/ref tùy ý, lệnh shell, engine override, bypass quyền, update/remove hay admin RPC.+Agent mới dùng permission bypass **tắt**, không có first prompt.++## 1. Khám phá và kiểm tra thông tin++```json+{"type":"store.list","requestId":"11111111-1111-4111-8111-111111111111","query":"Blender","offset":0,"limit":5}+```++Response: `{type,requestId,machineId,packages:[Package],nextOffset:number|null}`.+`query` tùy chọn, tối đa 200 ký tự; tìm tất cả từ trong ID/name/description/category. `offset` mặc định+0 (0–25000), `limit` mặc định 10 (1–10). Lặp với nextOffset đến null; catalog có thể đổi giữa các trang.+Viewer là dependency, không phải agent để chọn. Package đã cài nhưng bị unlist vẫn xuất hiện.++```json+{"type":"store.inspect","requestId":"22222222-2222-4222-8222-222222222222","packageId":"autonomous/blender"}+```++Response: `{type,requestId,machineId,package:Package,candidates:[Agent],candidatesTruncated:boolean}`.+Tối đa 5 candidate; dùng `agents.list` nếu cần xem thêm. Chỉ ghép candidate theo package identity được+lưu trong registry, không đoán theo tên hoặc recap. OS/người dùng quyết định session có đúng project+hay không; inspect/prepare không tự chiếm session.++| Field của Package | Ý nghĩa |+|---|---|+| `packageId,name,description,category,engine` | Dữ kiện từ catalog/manifest đã cài |+| `catalog,installed` | Hai boolean độc lập: có trên Store không đồng nghĩa đã cài |+| `verified,installAllowed` | Nhận diện nguồn chính thức và quyền cài tự động; không chứng minh tool chạy được |+| `viewerPackageId` | Shared viewer đã biết hoặc null |+| `version,broken` | Tree/commit đã cài nếu biết; lỗi package hoặc null |+| `capabilities` | `{source:"package_metadata",description,category}`: mô tả công bố, không phải capability đã test |+| `requirements` | `{engine,viewerPackageId,applications:null,note}`: manifest hiện chưa có danh sách dependency ứng dụng chuẩn hóa |+| `installation` | `not_installed / installed / installing / broken`; installing phản ánh install đang chạy trong service này |+| `readiness` | `{state,scope:"package_doctor",engineAuthentication:"unknown",taskSuccess:"unknown",checkedAt?,version?,lines?}` |+| `lastPreparation` | `{state,phase,error,updatedAt}` mới nhất trong bộ nhớ, hoặc null; lịch sử bền vững xem operation.get |++Readiness: `not_installed / unknown / passed / failed`. List/inspect không chạy scripts. Prepare chạy+doctor của package và viewer, lưu tối đa 10 dòng, mỗi dòng 400 ký tự, timestamp và version. Đổi version+hoặc restart daemon làm cache check mất hiệu lực. Không có doctor thì phạm vi kiểm tra là unknown.+Doctor pass là bằng chứng tại thời điểm kiểm tra, không chứng minh login/license/GPU, mọi tính năng+hay task cụ thể đều sẵn sàng. Install từ luồng khác được phản ánh khi installed index thay đổi.++Agent candidate có `{agentId,machineId,packageId,engine,workspace,state,runtime,error?}`.+`runtime` là `starting / ready / unavailable`; workspace là đường dẫn tuyệt đối canonical nếu biết.+`agents.list` cũng thêm các field tùy chọn `packageId,workspace,runtime`. Package null/absent nghĩa là+không biết, không được suy từ recap. Runtime ready cần terminal sống, engine process và native+conversation đã bind (terminal thường là ngoại lệ). Xác thực engine chưa được kiểm chứng độc lập.++## 2. Chuẩn bị agent, không giao task++```json+{+ "type":"agent.prepare",+ "requestId":"33333333-3333-4333-8333-333333333333",+ "machineId":"mac-example",+ "packageId":"autonomous/blender",+ "idempotencyKey":"prepare-airplane-001",+ "workspace":{"kind":"new","name":"airplane"}+}+```++Workspace bắt buộc, chọn đúng một dạng:++- `{"kind":"new","name":"airplane"}`: tạo trong `~/harnesses/` theo convention hiện có. Name tùy+ chọn, 1–100 ký tự ASCII chữ/số/`_`/`-`, bắt đầu bằng chữ/số. Bỏ name thì dùng tên package/thời gian.+ Nếu tên đã tồn tại, báo lỗi; không tự dùng lại folder.+- `{"kind":"existing","path":"/Users/example/harnesses/airplane"}`: thư mục tuyệt đối đã tồn tại,+ tối đa 4096 ký tự, không control characters. Resolve symlink trước khi kiểm tra. Chủ máy chọn rõ+ project này; materialize áp dụng template/instructions theo package. Nếu agent khác đang dùng+ workspace thì từ chối, không đổi project của session đó. Các request device cùng workspace được+ chặn tranh chấp trước bước tạo agent.++Không nhận `text`/`prompt`; không tự update package đã cài. Dùng lại Store install/setup/doctor,+`prepareProjectFolder`, `onCreateAgent`, `AgentCreationReceipts`. Package đã cài bỏ qua install/setup+nhưng chạy lại doctor. Dependency thiếu/doctor fail trả hướng dẫn. Package hỏng không tự ghi đè.++Response ngay sau khi ghi reservation bền vững:+`{type:"agent.prepare_result",requestId,status:"accepted",operation:Operation}`.+Retry cùng key/tham số, requestId mới → `status:"duplicate"`, cùng operation. Đổi tham số dưới cùng+key → `IDEMPOTENCY_CONFLICT`. Xem JSON đầy đủ khớp implementation trong+[blender.fixture.json](../contracts/autonomous-device-store-v1/blender.fixture.json).++Operation có:+`operationId` (64 ký tự hex thường), `machineId`, `packageId`, `state`, `phase`, `createdAt`,+`updatedAt` (Unix milliseconds), `agentId`, `workspace`, `error:{code,message}|null`, `guidance|null`,+`doctor:[]`, `taskDispatched:false`, `engineAuthentication:"unknown"`.+Các field chưa có giá trị như agentId/workspace dùng null. Lưu operationId được trả về, không tự tính.++## 3. Lifecycle, polling và phục hồi++```json+{"type":"operation.get","requestId":"44444444-4444-4444-8444-444444444444","operationId":"<64 ký tự hex nhận từ prepare>"}+```++Response `{type:"operation.get_result",requestId,operation:Operation}`. Chỉ identity đã tạo operation+được đọc nó; ID không tồn tại/thuộc device khác đều trả `OPERATION_NOT_FOUND`.+Poll khoảng 2 giây/lần, backoff khi rate limited. **V1 không thêm progress event**; polling là nguồn+trạng thái chuẩn. Sau reconnect hoặc resync, poll lại operation IDs đã lưu. Event replay/cursor và+serverInstanceId hiện có vẫn áp dụng cho task/turn.++| State | OS cần làm |+|---|---|+| `accepted` | Đã lưu ý định, chưa kết luận install/create xảy ra |+| `running` | Tiếp tục poll operation hiện tại |+| `ready` | Đã chuẩn bị package và agent runtime/conversation; **chưa giao task** |+| `failed` | Lỗi xác định như không có package; kiểm tra trước khi tạo ý định mới |+| `needs_user_action` | Hiển thị error.message + guidance; có thể cần dependency/login/workspace hoặc kết quả thực thi chưa rõ |++Phases: `accepted → install / clone / setup → doctor → workspace → create → launch → complete`.+Có thể bỏ qua hoặc lặp các phase khi package đã cài/shared dependencies. AgentId có thể đã có dù chưa+ready hoặc đang cần thao tác: mở agent đó để xử lý, không tạo thêm.++Ready chỉ xác nhận bước chuẩn bị. Không chứng minh đã dựng máy bay, đã đăng nhập hay model thành công.+Nếu engine/conversation chưa bind sau 10 phút, polling trả `ENGINE_ACTION_REQUIRED`; lỗi launch đã+biết báo sớm hơn. Hoàn tất prompt engine rồi poll lại có thể đưa cùng operation về ready. Agent biến+mất/đổi workspace khiến operation previously-ready trở thành cần thao tác.++Quy tắc retry/recovery:++- Key theo `(paired identity,idempotencyKey)` trên máy; 1–64 chữ/số ASCII/`_`/`-`.+- Ghi private journal trước side effect; creation receipt bảo vệ riêng bước spawn. Không tự hết hạn+ journal/receipt; giữ dữ liệu trong ADAPTER_DATA_DIR.+- Tối đa 4 preparation jobs đang chạy. Request device cùng package chia sẻ install; lock Store hiện+ có bao phủ Desktop/CLI. `DSH_BUSY` không cho phép chạy setup song song.+- Timeout/disconnect không hủy công việc đã accepted. Retry cùng prepare key/tham số để lấy lại ID+ hoặc poll ID cũ. Timeout không nghĩa là chưa thực thi.+- Restart: nếu creation receipt xác nhận created thì lấy lại agentId, kiểm tra registry/package/+ workspace/runtime; không spawn lại.+- Nếu journal bị ngắt mà chưa có creation xác nhận, trả `RECOVERY_REQUIRED`. Không tự chạy lại+ install/setup/tạo folder/spawn. Chủ máy kiểm tra side effects trước khi chủ động dùng key mới.+- Revoke pairing chặn bước tiếp theo ở boundary; setup/doctor/spawn đang chạy có thể đã tạo side+ effects và không luôn hủy được. Không tự xóa file/agent của người dùng. Transport bị revoke không+ được tiếp tục gửi/đọc.+- `receipt.get` hiện có dành cho turn/stop/answer, không đọc preparation. Dedupe delivery của nó còn+ trong bộ nhớ; thay đổi này **không** làm `turn.send` bền vững qua restart. Nếu task mất xác nhận+ qua restart, kiểm tra serverInstanceId và kết quả agent; không tự gửi lại vì receipt cũ biến mất.++## Lỗi++Trước accepted: `{type,requestId,error:{code,message}}`, không có operation.+Sau accepted: đọc `operation.error` và `guidance`, kể cả response duplicate.++| Code | Xử lý |+|---|---|+| `UNSUPPORTED_CAPABILITY`, `PROTO_UNSUPPORTED` | Cập nhật CLI, không gọi generic dispatcher |+| `HELLO_REQUIRED`, `RATE_LIMITED`, `BACKPRESSURE` | Hello/backoff, giữ nguyên key |+| `INVALID_REQUEST`, `MACHINE_MISMATCH` | Sửa payload/target, field lạ bị từ chối |+| `PACKAGE_NOT_FOUND`, `PACKAGE_REVIEW_REQUIRED` | Chọn package hợp lệ hoặc chủ máy review/cài |+| `PACKAGE_BROKEN`, `DEPENDENCY_NOT_READY` | Đọc doctor/broken evidence, sửa trên máy |+| `INVALID_WORKSPACE`, `WORKSPACE_IN_USE` | Chọn project khác hoặc chọn rõ candidate hiện có |+| `IDEMPOTENCY_CONFLICT` | Đối chiếu state caller, không dùng cùng key cho ý định khác |+| `OPERATION_NOT_FOUND`, `STORAGE_FAILED` | Kiểm tra identity/ID/storage; không suy ra chưa chạy |+| `INSTALL_UNCONFIRMED`, `CREATION_UNCONFIRMED`, `PREPARATION_UNCONFIRMED`, `RECOVERY_REQUIRED` | Side effects có thể tồn tại, kiểm tra trước retry mới |+| `ENGINE_ACTION_REQUIRED`, `AGENT_UNAVAILABLE` | Mở agent được trả về, xử lý login/trust/launch/target |+| `REVOKED`, `INTERNAL` | Dừng/đối chiếu, không tự tạo intent mới |++Lỗi Store/creator gốc cũng được chuyển tiếp: `CLONE_FAILED`, `SETUP_FAILED`, `DOCTOR_FAILED`,+`DSH_BUSY`, `TMUX_UNAVAILABLE`, `CWD_NOT_FOUND`, `TMUX_TOO_OLD_FOR_DSH`, `PROJECT_EXISTS`,+`PROJECT_PREPARATION_FAILED`... OS phải hiển thị code/message/guidance chưa biết, không coi là success.++## Luồng Blender hoàn chỉnh và phần Autonomous OS cần làm++1. Lưu user intent “I want to use Blender to draw an airplane for me”; kiểm tra đủ capabilities.+2. `store.list(query:"Blender")` → `store.inspect(packageId:"autonomous/blender")`. Dựa trên package+ identity/readiness/candidate, không recap. Nếu người dùng chọn session phù hợp đã có thì dùng ID+ đó và bỏ qua prepare.+3. Nếu cần agent mới, lưu `prepare-airplane-001` + workspace rồi gọi prepare. Lưu operationId, poll,+ thông báo tiến độ hoặc hướng dẫn cần thao tác. Không yêu cầu OS biết cách setup riêng Blender.+4. Khi ready, lưu machineId/agentId, tạo key task riêng **`task-airplane-001`**, rồi gửi đúng một lần:++ ```json+ {"type":"turn.send","requestId":"55555555-5555-4555-8555-555555555555","machineId":"mac-example","agentId":"agent-example","idempotencyKey":"task-airplane-001","text":"Use Blender to draw an airplane for me."}+ ```++ Không đưa task vào prepare/name/setup/first prompt. Dùng target vừa nhận, không ràng buộc với+ app focus không liên quan.+5. Lưu delivery receipt/serverInstanceId; theo dõi receipt/status/events/questions/recap. Permission+ prompt phải xử lý trên Desktop; `question.answer` không duyệt tool permissions. Chỉ báo dựng xong+ khi có kết quả công việc, không khi prepare ready.+6. OS cần: capability fallback, journal intent/keys, polling/reconnect, chọn candidate và UI/voice cho+ needs_user_action. Không cần credential hay script Blender mới.++## Kiểm thử và giới hạn++Tests bao phủ metadata/installed/readiness, install dùng chung, dependency lỗi, setup/doctor/+materialize **thật với package fixture local**, arguments tạo agent không bypass quyền, dedupe/+timeout/reconnect, restart và khoảng trống spawn/journal, symlink/workspace collision, revoke,+capability/role/encryption boundaries và schema/fixture khớp implementation.++Engine/model creation trong tests là mock. Dòng doctor Blender trong fixture là ví dụ tổng hợp.+Lượt triển khai này chưa cài Blender, chạy robot thật, gọi model có phí hay render máy bay. Cần một+lượt acceptance phối hợp Lamp → CLI mới → Blender thật sau khi cả hai phía tích hợp.++```sh+cd cli+npx tsx scripts/device-store-contract.ts --check+npx vitest run src/lib/autonomous-device --maxWorkers=1+```