Skip to content

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.

Scope agent creation status and cancel to their creator (#1435)

0xken151fb7c4fc08c0
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 7998eea8d..8f0494b44 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -224,9 +224,9 @@ export class BackendSocket {
/** The requests that start an agent's process, answered through their last argument: `agent_create`,
* `agent_create_status`, `agent_resume` and `agent_restart`, and `agent_fork` (cli.ts binds
* core/agents/launches.ts). Null answers UNSUPPORTED_ON_REMOTE, or UNSUPPORTED for a status. */
- createProvider: ((payload: Record<string, unknown>, asker: { local: boolean; owner: boolean }, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
- createStatusProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
- cancelCreateProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
+ createProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'owner' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
+ createStatusProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
+ cancelCreateProvider: ((payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
restartProvider: ((type: string, payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
forkProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null
/** Opens a NEW agent that starts with `agentId`'s whole history (lib/forkAgent.ts), exactly as
@@ -1064,12 +1064,12 @@ export class BackendSocket {
// What became of a launch a creationId names (core/agents/launches.ts, bound by cli.ts).
case 'agent_create_status':
- if (this.createStatusProvider) await this.createStatusProvider(payload, answer)
+ if (this.createStatusProvider) await this.createStatusProvider(payload, asker, answer)
else answer({ error: 'UNSUPPORTED' })
return
case 'agent_create_cancel':
- if (this.cancelCreateProvider) await this.cancelCreateProvider(payload, answer)
+ if (this.cancelCreateProvider) await this.cancelCreateProvider(payload, asker, answer)
else answer({ error: 'UNSUPPORTED' })
return
diff --git a/cli/src/core/agents/launchRequests.golden.spec.ts b/cli/src/core/agents/launchRequests.golden.spec.ts
index 2090db3b0..8dcd2eee7 100644
--- a/cli/src/core/agents/launchRequests.golden.spec.ts
+++ b/cli/src/core/agents/launchRequests.golden.spec.ts
@@ -91,14 +91,14 @@ it.each(['linux', 'darwin'])('preserves healthy launch requests and durable rece
: requests.create(payload, { local: true }, reply)
await invoke()
await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
- await requests.createStatus({ creationId }, reply)
+ await requests.createStatus({ creationId }, { local: true }, reply)
await invoke() // A duplicate in flight joins the same operation.
finish()
await vi.waitFor(() => expect(replies).toHaveLength(3))
await invoke() // A duplicate after completion only returns the receipt.
await vi.waitFor(() => expect(replies).toHaveLength(4))
const recovered = createLaunchRequests({ ...deps, receipts: new AgentCreationReceipts(directory) })
- await recovered.createStatus({ creationId }, reply)
+ await recovered.createStatus({ creationId }, { local: true }, reply)
expect(fixture.events.filter(value => Array.isArray(value) && value[0] === 'dispatch')).toHaveLength(1)
const key = `${platform}:${kind}`
observations[key] = JSON.parse(JSON.stringify({ events: fixture.events, replies }).split(root).join('<root>'))
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index effd7e07c..014370a13 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -100,7 +100,7 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat
return {
deps, create, fork, resume, restart, replies, requests,
ask: async (payload: Record<string, unknown>, local = true) => { await requests.create(payload, { local }, reply); return replies.at(-1) },
- status: async (payload: Record<string, unknown>) => { await requests.createStatus(payload, reply); return replies.at(-1) },
+ status: async (payload: Record<string, unknown>) => { await requests.createStatus(payload, { local: true }, reply); return replies.at(-1) },
relaunch: async (type: string, payload: Record<string, unknown>) => { await requests.relaunch(type, payload, reply); return replies.at(-1) },
forkAsk: async (payload: Record<string, unknown>) => { await requests.fork(payload, reply); return replies.at(-1) },
}
@@ -470,7 +470,7 @@ describe('agent_create with a receipt', () => {
expect(create).toHaveBeenCalledWith(expect.objectContaining({ cwd, prompt: 'Keep this task', grid: target }))
expect(preTrustClaudeProject).not.toHaveBeenCalled()
const answer = vi.fn()
- await recovered.createStatus({ creationId: CREATION }, answer)
+ await recovered.createStatus({ creationId: CREATION }, { local: true }, answer)
expect(answer).toHaveBeenCalledWith({ creationId: CREATION, state: 'created', agent: { id: 'new-agent' } })
await recovered.recover()
expect(create).toHaveBeenCalledOnce()
@@ -483,7 +483,7 @@ describe('agent_create with a receipt', () => {
await ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })
await vi.waitFor(() => expect(replies).toHaveLength(1))
const answer = vi.fn()
- await requests.cancelCreate({ creationId: CREATION }, answer)
+ await requests.cancelCreate({ creationId: CREATION }, { local: true }, answer)
expect(answer).toHaveBeenLastCalledWith({ creationId: CREATION, state: 'cancelled' })
resolveNewAgentModel.mockResolvedValue({ networkId: 'fixture-grid' } as never)
requests.open(); await requests.recover()
@@ -791,9 +791,9 @@ describe('agent_create with a receipt', () => {
})
it('says why a receipt could not be kept, and answers INTERNAL when the answer cannot be put together', async () => {
- const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ const storage = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
expect(await storage.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
- const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ const broken = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
expect(await broken.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
await frameless.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
@@ -870,14 +870,14 @@ describe('durable model request validation', () => {
it('rejects invalid cancellation IDs and reports storage uncertainty without acknowledging cancellation', async () => {
const { deps, requests } = setup()
const answer = vi.fn()
- await requests.cancelCreate({ creationId: '../invalid' }, answer)
+ await requests.cancelCreate({ creationId: '../invalid' }, { local: true }, answer)
expect(answer).toHaveBeenLastCalledWith({ error: 'INVALID_CREATION_ID' })
const cancel = vi.spyOn(deps.receipts, 'cancelIntent')
cancel.mockImplementationOnce(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') })
- await requests.cancelCreate({ creationId: CREATION }, answer)
+ await requests.cancelCreate({ creationId: CREATION }, { local: true }, answer)
expect(answer).toHaveBeenLastCalledWith({ error: 'CREATION_STORAGE_FAILED' })
cancel.mockImplementationOnce(() => { throw new Error('unknown') })
- await requests.cancelCreate({ creationId: CREATION }, answer)
+ await requests.cancelCreate({ creationId: CREATION }, { local: true }, answer)
expect(answer).toHaveBeenLastCalledWith({ error: 'INTERNAL' })
})
})
@@ -901,9 +901,9 @@ describe('agent_create_status', () => {
})
it('says why a receipt could not be read', async () => {
- const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ const storage = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
expect(await storage.status({ creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
- const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })
+ const broken = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })
expect(await broken.status({ creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
})
})
@@ -958,9 +958,9 @@ describe('agent_resume and agent_restart', () => {
})
it('say why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {
- const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ const storage = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
expect(await storage.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
- const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ const broken = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
expect(await broken.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
await frameless.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })
@@ -1016,9 +1016,9 @@ describe('agent_fork', () => {
})
it('says why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {
- const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })
+ const storage = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })
expect(await storage.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_CONFLICT' })
- const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ const broken = setup({ receipts: { has: vi.fn(() => false), creator: vi.fn(), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
expect(await broken.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
await frameless.forkAsk({ agentId: 'a1', creationId: CREATION })
@@ -1092,3 +1092,124 @@ describe('agent_create, from a guest', () => {
await vi.waitFor(() => expect(unbuilt.replies.at(-1)).toEqual({ error: 'INTERNAL' }))
})
})
+
+describe('agent_create_status and agent_create_cancel, by who created the launch', () => {
+ // A guest sees and cancels only its own creations; for anyone else's id it hears what an unknown id gets.
+ const KIM = '[email protected]', LEE = '[email protected]'
+ const OTHER = 'creation-fedcba9876543210'
+ const guestCreate = () => vi.fn(async () => ({ ok: true as const, session: session('guest-agent', { guest: KIM }) }))
+ const as = (run: ReturnType<typeof setup>, guest?: string) => ({
+ status: async (creationId: string) => { const answer = vi.fn(); await run.requests.createStatus({ creationId }, guest ? { local: false, guest } : { local: true }, answer); return answer.mock.calls.at(-1)![0] },
+ cancel: async (creationId: string) => { const answer = vi.fn(); await run.requests.cancelCreate({ creationId }, guest ? { local: false, guest } : { local: true }, answer); return answer.mock.calls.at(-1)![0] },
+ })
+ const ownerHeld = async (run: ReturnType<typeof setup>, id = CREATION) => {
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })
+ resolveNewAgentModel.mockResolvedValue(null)
+ await run.ask({ engine: 'claude', cwd: '/fixture/work', creationId: id })
+ await vi.waitFor(() => expect(run.replies.at(-1)).toMatchObject({ state: 'pending' }))
+ }
+ const guestMade = async (run: ReturnType<typeof setup>, guest = KIM, id = CREATION) => {
+ await run.requests.create({ creationId: id, engine: 'claude' }, { local: false, guest }, (result) => { run.replies.push(result) })
+ await vi.waitFor(() => expect(run.replies.at(-1)).toMatchObject({ creationId: id, state: 'created' }))
+ }
+ const withGuests = () => setup({ guestCreate: guestCreate, byAgent: (id) => id === 'guest-agent' || id === 'new-agent' ? session(id) : undefined })
+
+ it('answers a guest for the owner\'s pending creation exactly as for an unknown id, and cancels nothing', async () => {
+ const run = withGuests()
+ await ownerHeld(run)
+ const unknown = await as(run, KIM).status(OTHER)
+ expect(unknown).toEqual({ creationId: OTHER, state: 'missing' })
+ expect(await as(run, KIM).status(CREATION)).toEqual({ ...unknown, creationId: CREATION })
+ expect(await as(run, KIM).cancel(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run, KIM).cancel(OTHER)).toEqual({ creationId: OTHER, state: 'missing' })
+ expect(await as(run).status(CREATION)).toMatchObject({ state: 'pending' })
+ // The guest's cancel of an unknown id wrote nothing: no cancelled mark, no receipt file.
+ expect(await as(run).status(OTHER)).toEqual({ creationId: OTHER, state: 'missing' })
+ expect(existsSync(join(dir, `receipts-${stores}`, `${OTHER}.json`))).toBe(false)
+ })
+
+ it('answers a guest for the owner\'s finished creation as for an unknown id, and a cancel leaves it', async () => {
+ const run = withGuests()
+ await run.ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies.at(-1)).toMatchObject({ state: 'created' }))
+ expect(await as(run, KIM).status(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run, KIM).cancel(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run).status(CREATION)).toMatchObject({ state: 'created', agent: { id: 'new-agent' } })
+ })
+
+ it('keeps one guest\'s creation from another, and shows a guest its own', async () => {
+ const run = withGuests()
+ await guestMade(run, KIM)
+ expect(await as(run, LEE).status(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run, LEE).cancel(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run, KIM).status(CREATION)).toEqual({ creationId: CREATION, state: 'created', agent: { id: 'guest-agent' } })
+ expect(await as(run, KIM).cancel(CREATION)).toMatchObject({ creationId: CREATION, state: 'created' })
+ })
+
+ it('lets the owner read and cancel its own creations and a guest\'s', async () => {
+ const run = withGuests()
+ await guestMade(run, KIM)
+ expect(await as(run).status(CREATION)).toMatchObject({ state: 'created', agent: { id: 'guest-agent' } })
+ await ownerHeld(run, OTHER)
+ expect(await as(run).status(OTHER)).toMatchObject({ state: 'pending' })
+ expect(await as(run).cancel(OTHER)).toEqual({ creationId: OTHER, state: 'cancelled' })
+ expect(await as(run).cancel(CREATION)).toMatchObject({ state: 'created' })
+ })
+
+ it('treats a receipt written before creators were recorded as the owner\'s, and keeps a guest\'s across a restart', async () => {
+ const run = withGuests()
+ await guestMade(run, KIM)
+ const reloaded = createLaunchRequests({ ...run.deps, receipts: new AgentCreationReceipts(join(dir, `receipts-${stores}`)) })
+ stopRequests.push(reloaded.stop)
+ const reread = async (guest: string | undefined, id: string) => {
+ const answer = vi.fn(); await reloaded.createStatus({ creationId: id }, guest ? { local: false, guest } : { local: true }, answer); return answer.mock.calls.at(-1)![0]
+ }
+ expect(await reread(KIM, CREATION)).toMatchObject({ state: 'created' })
+ expect(await reread(LEE, CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ writeFileSync(join(dir, `receipts-${stores}`, `${OTHER}.json`),
+ JSON.stringify({ version: 1, fingerprint: creationFingerprint({ old: true }), outcome: { state: 'created', agentId: 'new-agent' } }), { mode: 0o600 })
+ expect(await reread(KIM, OTHER)).toEqual({ creationId: OTHER, state: 'missing' })
+ expect(await reread(undefined, OTHER)).toMatchObject({ state: 'created' })
+ })
+
+ it('refuses a guest that reuses the owner\'s creation id, without telling what became of it', async () => {
+ const run = withGuests()
+ await run.ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies.at(-1)).toMatchObject({ state: 'created' }))
+ run.replies.length = 0
+ await run.requests.create({ creationId: CREATION, engine: 'claude' }, { local: false, guest: KIM }, (result) => { run.replies.push(result) })
+ expect(run.replies).toEqual([{ error: 'CREATION_CONFLICT' }])
+ await ownerHeld(run, OTHER)
+ run.replies.length = 0
+ await run.requests.create({ creationId: OTHER, engine: 'claude' }, { local: false, guest: KIM }, (result) => { run.replies.push(result) })
+ expect(run.replies).toEqual([{ error: 'CREATION_CONFLICT' }])
+ })
+
+ it('lets a guest repeat its own create and still get its receipt', async () => {
+ const run = withGuests()
+ await guestMade(run, KIM)
+ run.replies.length = 0
+ await run.requests.create({ creationId: CREATION, engine: 'claude' }, { local: false, guest: KIM }, (result) => { run.replies.push(result) })
+ await vi.waitFor(() => expect(run.replies).toEqual([{ creationId: CREATION, state: 'created', agent: { id: 'guest-agent' } }]))
+ })
+
+ it('refuses an invalid id to a guest as to anyone, and hides damaged evidence from a guest but not from the owner', async () => {
+ const run = withGuests()
+ expect(await as(run, KIM).status('short')).toEqual({ error: 'INVALID_CREATION_ID' })
+ expect(await as(run, KIM).cancel('short')).toEqual({ error: 'INVALID_CREATION_ID' })
+ const damaged = () => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }
+ vi.spyOn(run.deps.receipts, 'creator').mockImplementation(damaged)
+ expect(await as(run, KIM).status(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ expect(await as(run, KIM).cancel(CREATION)).toEqual({ creationId: CREATION, state: 'missing' })
+ vi.spyOn(run.deps.receipts, 'status').mockImplementation(damaged)
+ vi.spyOn(run.deps.receipts, 'cancelIntent').mockImplementation(damaged)
+ expect(await as(run).status(CREATION)).toEqual({ error: 'CREATION_STORAGE_FAILED' })
+ expect(await as(run).cancel(CREATION)).toEqual({ error: 'CREATION_STORAGE_FAILED' })
+ })
+
+ it('answers INTERNAL, not missing, when a guest\'s creator lookup fails for another reason', async () => {
+ const run = withGuests()
+ vi.spyOn(run.deps.receipts, 'creator').mockImplementation(() => { throw new Error('bug') })
+ expect(await as(run, KIM).status(CREATION)).toEqual({ error: 'INTERNAL' })
+ })
+})
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index f6e83f900..1a77ccf25 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -12,6 +12,7 @@ import { readdir, rmdir } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, isAbsolute } from 'node:path'
import type { BackendSocket } from '../../backendSocket.js'
+import type { Asker } from '../api.js'
import { installedDsh } from '../../dsh/installed.js'
import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'
import { folderTrust } from '../../engines/launchPrep.js'
@@ -54,7 +55,7 @@ export type ResumeAgent = (agentId: string, permissionMode?: string) => ReturnTy
export interface LaunchRequestDeps {
/** The receipts of launches asked for with a `creationId`. */
- receipts: Pick<AgentCreationReceipts, 'run' | 'status' | 'has' | 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>
+ receipts: Pick<AgentCreationReceipts, 'run' | 'status' | 'creator' | 'has' | 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>
/** Each launch, read when a request comes in: null on a machine that cannot launch agents. */
createAgent: () => CreateAgent | null
prepareCreate?: (input: Parameters<CreateAgent>[0], authority: LaunchAuthority, context?: { local: boolean }) => Promise<LaunchPreparation<Awaited<ReturnType<CreateAgent>>>>
@@ -251,11 +252,21 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
return status
}
+ /** A guest sees only its own creations. For anyone else's id it hears what an unknown id gets, so the
+ * answer does not tell whether the id exists. The owner administers the machine and sees them all. */
+ const hiddenFrom = (asker: Pick<Asker, 'local' | 'guest'>, creationId: string): boolean => {
+ if (asker.guest === undefined) return false
+ // Damaged evidence for this id is hidden the same way; the guest's own retry still meets it in `run`.
+ try { return receipts.creator(creationId) !== asker.guest }
+ catch (error) { if (error instanceof AgentCreationReceiptError) return true; throw error }
+ }
+
/** Answers `agent_create_status`: what became of the launch a `creationId` names. */
- const createStatus = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const createStatus = async (payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: Reply): Promise<void> => {
const creationId = payload.creationId
if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
try {
+ if (hiddenFrom(asker, creationId)) { reply({ creationId, state: 'missing' }); return }
reply({ creationId, ...await creationStatusPayload(receipts.status(creationId)) })
} catch (error) {
reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
@@ -280,7 +291,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
const result = await launch(payload, guest)
return result.ok ? { state: 'created', agentId: result.session.agentId }
: { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail } : {}) }
- }).then(async (status) => {
+ }, guest).then(async (status) => {
reply({ creationId, ...await creationStatusPayload(status) })
}).catch(() => reply({ error: 'INTERNAL' }))
} catch (error) {
@@ -290,7 +301,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
/** Answers `agent_create`. `asker.local` says the frame came from this machine; `asker.guest`, that a guest
* of a machine shared with them asks (core/guestPolicy.ts). */
- const create = async (payload: Record<string, unknown>, asker: { local: boolean; guest?: string }, reply: Reply): Promise<void> => {
+ const create = async (payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: Reply): Promise<void> => {
if (asker.guest !== undefined) { await createForGuest(payload, asker.guest, reply); return }
const engine = payload.engine as AgentEngine | undefined
const cwd = payload.cwd
@@ -587,9 +598,13 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
reply({ agent: await toProject(result.session), level: result.level })
}
- const cancelCreate = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const cancelCreate = async (payload: Record<string, unknown>, asker: Pick<Asker, 'local' | 'guest'>, reply: Reply): Promise<void> => {
if (!validCreationId(payload.creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
- try { reply({ creationId: payload.creationId, ...await creationStatusPayload(receipts.cancelIntent(payload.creationId)) }) }
+ try {
+ // A guest cancels nothing of another's, and leaves no cancelled mark for an id that is not its own.
+ if (hiddenFrom(asker, payload.creationId)) { reply({ creationId: payload.creationId, state: 'missing' }); return }
+ reply({ creationId: payload.creationId, ...await creationStatusPayload(receipts.cancelIntent(payload.creationId)) })
+ }
catch (error) { reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' }) }
}
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 9edcbe1a3..034121782 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -34,17 +34,17 @@ describe('what an experiment in its own process may ask of the core', () => {
expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'creation_status', { creationId: id })).toEqual({ observation: known })
expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'creation_status', {})).toEqual({ observation: null })
expect(await creationForExperiment(null, id)).toBeNull()
- const read = vi.fn(async (input, reply) => { reply({ ...input, state: 'created', agent: { id: 'native', private: 'not projected' } }) })
+ const read = vi.fn(async (input, _asker, reply) => { reply({ ...input, state: 'created', agent: { id: 'native', private: 'not projected' } }) })
expect(await creationForExperiment(read, 'invalid')).toBeNull()
expect(read).not.toHaveBeenCalled()
expect(await creationForExperiment(read, id)).toEqual({ creationId: id, state: 'created', agentId: 'native' })
expect(await creationForExperiment(async () => {}, id)).toBeNull()
expect(await creationForExperiment(async () => { throw new Error('Disk unavailable') }, id)).toBeNull()
- expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'cancelled' }) }, id)).toEqual(known)
- expect(await creationForExperiment(async (_, reply) => { reply({ creationId: 'other', state: 'cancelled' }) }, id)).toBeNull()
- expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'unavailable', createdAgentId: 'closed-native' }) }, id))
+ expect(await creationForExperiment(async (input, _asker, reply) => { reply({ ...input, state: 'cancelled' }) }, id)).toEqual(known)
+ expect(await creationForExperiment(async (_, _asker, reply) => { reply({ creationId: 'other', state: 'cancelled' }) }, id)).toBeNull()
+ expect(await creationForExperiment(async (input, _asker, reply) => { reply({ ...input, state: 'unavailable', createdAgentId: 'closed-native' }) }, id))
.toEqual({ creationId: id, state: 'created', agentId: 'closed-native' })
- expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'unavailable' }) }, id)).toBeNull()
+ expect(await creationForExperiment(async (input, _asker, reply) => { reply({ ...input, state: 'unavailable' }) }, id)).toBeNull()
})
it('requires fresh native stop evidence, including when a core is older', async () => {
const core = fakeCore({ agents: { stopped: async id => id === 'stopped' } })
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 28c5436de..a00ea0281 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -147,7 +147,7 @@ export async function createForExperiment(create: BackendSocket['onCreateAgent']
export async function creationForExperiment(read: BackendSocket['createStatusProvider'], creationId: string) {
if (!read || !/^[A-Za-z0-9_-]{16,96}$/.test(creationId)) return null
let reply: Record<string, unknown> | null = null
- try { await read({ creationId }, value => { reply = value }) } catch { return null }
+ try { await read({ creationId }, { local: true }, value => { reply = value }) } catch { return null }
const frame = reply as Record<string, unknown> | null
const agent = frame?.agent as { id?: unknown } | undefined
// A closed terminal is unavailable to a window, but its durable creation
diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.ts
index cabac0173..cdddd86c9 100644
--- a/cli/src/lib/agentCreationReceipt.spec.ts
+++ b/cli/src/lib/agentCreationReceipt.spec.ts
@@ -406,3 +406,60 @@ describe('recoverable undispatched creation intents', () => {
expect(prepare).not.toHaveBeenCalled()
})
})
+
+describe('who created a launch', () => {
+ const guest = '[email protected]'
+ const created = { state: 'created' as const, agentId: 'fixture-agent' }
+ const done = async () => created
+
+ it('records a guest on its receipt, pending and finished, and keeps it across a restart', async () => {
+ const { directory, receipts } = fixture()
+ let finish!: (outcome: AgentCreationOutcome) => void
+ const run = receipts.run(id, fingerprint, () => new Promise<AgentCreationOutcome>((resolve) => { finish = resolve }), guest)
+ expect(receipts.creator(id)).toBe(guest)
+ expect(new AgentCreationReceipts(directory).creator(id)).toBe(guest)
+ await Promise.resolve(); finish(created); await run
+ expect(receipts.creator(id)).toBe(guest)
+ expect(new AgentCreationReceipts(directory).creator(id)).toBe(guest)
+ expect(new AgentCreationReceipts(directory).status(id)).toEqual(created)
+ })
+
+ it('reads a receipt that records no creator, an owner\'s launch or an unknown id, as the owner\'s', async () => {
+ const { directory, receipts } = fixture()
+ expect(receipts.creator(id)).toBeNull()
+ await receipts.run(id, fingerprint, done)
+ expect(receipts.creator(id)).toBeNull()
+ writeFileSync(join(directory, `${id}-old.json`), JSON.stringify({ version: 1, fingerprint, outcome: created }))
+ expect(receipts.creator(`${id}-old`)).toBeNull()
+ })
+
+ it('leaves an owner\'s receipt bytes as they were before the field existed', async () => {
+ const { directory, receipts } = fixture()
+ await receipts.run(id, fingerprint, done)
+ expect(JSON.parse(readFileSync(join(directory, `${id}.json`), 'utf8'))).toEqual({ version: 1, fingerprint, outcome: created })
+ })
+
+ it('reads a creator that is not a name as damaged evidence', () => {
+ const { directory, receipts } = fixture()
+ mkdirSync(directory, { mode: 0o700 })
+ writeFileSync(join(directory, `${id}.json`), JSON.stringify({ version: 1, fingerprint, guest: 7, outcome: created }), { mode: 0o600 })
+ expect(() => receipts.creator(id)).toThrow('CREATION_STORAGE_FAILED')
+ })
+
+ it('refuses a guest an owner\'s intent or cancelled id, whatever the fingerprint, and reveals nothing of it', async () => {
+ const { receipts } = fixture()
+ const held = { service: 'models', detail: 'Waiting.' }
+ await receipts.runIntent(id, fingerprint, { kind: 'x' }, held, async () => null)
+ expect(() => receipts.run(id, fingerprint, vi.fn(), guest)).toThrow('CREATION_CONFLICT')
+ receipts.cancelIntent(`${id}-gone`)
+ expect(() => receipts.run(`${id}-gone`, fingerprint, vi.fn(), guest)).toThrow('CREATION_CONFLICT')
+ })
+
+ it('refuses a guest a tombstone written between its read and its reservation', () => {
+ const { directory, receipts } = fixture()
+ mkdirSync(directory, { mode: 0o700 })
+ vi.spyOn(receipts as unknown as { read: () => unknown }, 'read').mockReturnValueOnce(null)
+ writeFileSync(join(directory, `${id}.json`), JSON.stringify({ version: 2, cancelled: true }), { mode: 0o600 })
+ expect(() => receipts.run(id, fingerprint, vi.fn(), guest)).toThrow('CREATION_CONFLICT')
+ })
+})
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 6743f108a..80db07fb2 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -38,6 +38,8 @@ type IntentResult = { fingerprint: string; token: string; outcome: AgentCreation
type Receipt = {
version: 1
fingerprint: string
+ /** The guest a launch was made for. Absent for the owner's, and for every receipt written before guests existed. */
+ guest?: string
outcome: AgentCreationOutcome | { state: 'pending' }
}
@@ -108,7 +110,16 @@ export class AgentCreationReceipts {
: receipt.outcome
}
- run(id: string, fingerprint: string, create: () => Promise<AgentCreationOutcome>): Promise<AgentCreationStatus> {
+ /** Whose launch an id names: a guest's key, or null for the owner's, an intent's and an unknown id (which a
+ * guest hears the same way). */
+ creator(id: string): string | null {
+ const receipt = this.read(id)
+ return receipt?.version === 1 && receipt.guest !== undefined ? receipt.guest : null
+ }
+
+ /** `guest` marks a launch made for a guest: it is kept on the receipt so that only that guest, and the owner, can
+ * ask what became of it. A guest never attaches to a receipt that is not its own, whatever its fingerprint. */
+ run(id: string, fingerprint: string, create: () => Promise<AgentCreationOutcome>, guest?: string): Promise<AgentCreationStatus> {
const running = this.inFlight.get(id)
if (running) {
if (running.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
@@ -116,6 +127,7 @@ export class AgentCreationReceipts {
}
const receipt = this.read(id)
if (receipt) {
+ if (guest !== undefined && receipt.version === 2) throw new AgentCreationReceiptError('CREATION_CONFLICT')
if (receipt.version === 2 && 'cancelled' in receipt) return Promise.resolve(this.intentStatus(id, receipt))
if (receipt.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
return Promise.resolve(this.status(id))
@@ -123,10 +135,11 @@ export class AgentCreationReceipts {
// O_EXCL is also the guard against another daemon reaching the same intent.
// A partial/corrupt reservation is refused, never treated as a missing one.
try {
- this.write(id, { version: 1, fingerprint, outcome: { state: 'pending' } }, true)
+ this.write(id, { version: 1, fingerprint, ...(guest === undefined ? {} : { guest }), outcome: { state: 'pending' } }, true)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
const existing = this.read(id)
+ if (guest !== undefined && existing?.version === 2) throw new AgentCreationReceiptError('CREATION_CONFLICT')
if (existing?.version === 2 && 'cancelled' in existing) return Promise.resolve(this.intentStatus(id, existing))
if (existing?.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
return Promise.resolve(this.status(id))
@@ -137,7 +150,7 @@ export class AgentCreationReceipts {
let outcome: AgentCreationOutcome
try { outcome = await create() }
catch { outcome = { state: 'unconfirmed' } }
- const completed: Receipt = { version: 1, fingerprint, outcome }
+ const completed: Receipt = { version: 1, fingerprint, ...(guest === undefined ? {} : { guest }), outcome }
try { this.write(id, completed, false) }
catch { this.unsaved.set(id, completed) }
return outcome
@@ -460,7 +473,8 @@ export class AgentCreationReceipts {
if (completedIntent || this.readIntentPart(this.intentFile(id, 'claim')) || this.readIntentPart(this.intentFile(id, 'result'))) {
throw new Error('Legacy receipt has conflicting intent evidence')
}
- if (value.version !== 1 || !/^[a-f0-9]{64}$/.test(value.fingerprint ?? '') || !outcome ||
+ if (value.version !== 1 || !/^[a-f0-9]{64}$/.test(value.fingerprint ?? '') || !outcome
+ || (value.guest !== undefined && (typeof value.guest !== 'string' || !value.guest)) ||
!['pending', 'unconfirmed', 'created', 'failed'].includes(outcome.state) ||
(outcome.state === 'created' && (typeof outcome.agentId !== 'string' || !outcome.agentId ||
(outcome.level !== undefined && outcome.level !== 'native' && outcome.level !== 'handoff') ||