返回 CodeWhale
host.test.mjs
根目录 / crates / engine / extension-host / test / host.test.mjs
1 // End-to-end tests of the committed host bundle against a fake core.
2 import { test } from 'node:test'
3 import assert from 'node:assert/strict'
4 import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync, rmSync } from 'node:fs'
5 import { createServer } from 'node:http'
6 import { tmpdir } from 'node:os'
7 import { dirname, join } from 'node:path'
8 import { execFileSync, spawn } from 'node:child_process'
9 import { fileURLToPath } from 'node:url'
10 import { BUNDLE, FIXTURES, HOST_ARGS, HOST_ENV, IS_BUN, activate, owner, sha256File, startHost } from './harness.mjs'
11 import { ErrorCode, encodeFrame } from '../dist/protocol.mjs'
12
13 // Budgets for a cold host start (the first host this file starts), gated in
14 // the first test. Measured 2026-09-30 on macOS arm64, 5 starts each: Node 26
15 // ready in 50-54 ms at 56 MiB resident, Bun 1.4 in 23-24 ms at 36 MiB; a
16 // Linux container measured 34-67 MB idle (`supervisor::HOST_MEMORY_CAP`).
17 // CI runs these suites on shared ubuntu-latest runners with test files in
18 // parallel, so each budget leaves room for load: 1500 ms is ~30x the Node
19 // start and ~15x the slowest runtime start measured for the host (Node SEA,
20 // 98 ms p50, CURRENT_DECISIONS D1); 160 MiB is 2.4x the largest idle host.
21 // The Rust integration test gates the core-side start and a tree RSS.
22 const READY_BUDGET_MS = 1500
23 const IDLE_RSS_BUDGET_MIB = 160
24
25 /** Resident MiB of `pid` from `ps`; `undefined` where there is no `ps`. */
26 function residentMiB(pid) {
27 if (process.platform === 'win32') return undefined
28 const kib = Number(execFileSync('ps', ['-o', 'rss=', '-p', String(pid)], { encoding: 'utf8' }).trim())
29 return Number.isFinite(kib) && kib > 0 ? kib / 1024 : undefined
30 }
31
32 function tempPlugin(source) {
33 const dir = mkdtempSync(join(tmpdir(), 'cw-ext-host-'))
34 const entry = join(dir, 'index.mjs')
35 writeFileSync(entry, source)
36 return { dir, entry, cleanup: () => rmSync(dir, { recursive: true, force: true }) }
37 }
38
39 test('handshake reports protocol 1 and the digest of the running bundle', async (t) => {
40 const host = await startHost()
41 t.after(() => host.stop())
42 assert.deepEqual(host.hello.protocol, { min: 1, max: 1 })
43 assert.equal(host.hello.bundle_sha256, sha256File(BUNDLE))
44 // The real runtime, not Bun's emulated `process.versions.node`.
45 assert.deepEqual(host.hello.runtime, IS_BUN ? { name: 'bun', version: process.versions.bun } : { name: 'node', version: process.versions.node })
46 assert.equal(host.hello.node_version, undefined)
47 // The tier the host serves and the built-in module digests it embeds.
48 assert.equal(host.hello.tier, 'plugin')
49 assert.deepEqual(host.hello.builtin_modules, builtinDigests())
50 // No limit was asked for, so none is reported.
51 assert.equal(host.hello.memory_limit_mib, undefined)
52 const rss = residentMiB(host.child.pid)
53 t.diagnostic(
54 `spawn → host/ready: ${host.readyMs.toFixed(1)} ms (budget ${READY_BUDGET_MS} ms); ` +
55 `idle RSS ${rss === undefined ? '?' : rss.toFixed(1)} MiB (budget ${IDLE_RSS_BUDGET_MIB} MiB)`,
56 )
57 assert.ok(host.readyMs <= READY_BUDGET_MS, `cold start took ${host.readyMs.toFixed(1)} ms, over ${READY_BUDGET_MS} ms`)
58 if (rss !== undefined) assert.ok(rss <= IDLE_RSS_BUDGET_MIB, `idle host is ${rss.toFixed(1)} MiB resident, over ${IDLE_RSS_BUDGET_MIB} MiB`)
59 })
60
61 test('heartbeat answers after initialization without an owner or tool call', async (t) => {
62 const host = await startHost()
63 t.after(() => host.stop())
64 assert.deepEqual(await host.call('host/ping', {}), {})
65 assert.equal(host.registry.length, 0)
66 })
67
68 test('the documented typed hello extension activates and executes unchanged', async (t) => {
69 const host = await startHost()
70 t.after(() => host.stop())
71 const entry = fileURLToPath(new URL('../../../../docs/examples/plugins/hello-extension/hello.mts', import.meta.url))
72 const { result } = await activate(host, 'hello-extension', entry)
73 assert.deepEqual(result, { status: 'ok', tools: ['hello_greet'], commands: ['hello-greet'] })
74 const tool = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'tool')
75 const output = await host.call('tool/call', { handle: tool.handle, call_id: 'hello-1', input: { name: 'Codewhale' }, deadline_ms: 5000 })
76 assert.deepEqual(output.structured, { greeting: 'Hello, Codewhale!', callId: 'hello-1' })
77 const command = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'command')
78 assert.deepEqual(command.spec, { name: 'hello-greet', description: command.spec.description, argument_hint: '[name]' })
79 const said = await host.call('command/run', { handle: command.handle, command_id: 'c-1', raw_input: 'Codewhale', deadline_ms: 5000 })
80 assert.deepEqual(said, { kind: 'success', text: 'Hello, Codewhale!' })
81 })
82
83 test('the typed hello example reads its one setting, validated by its own Config schema', async (t) => {
84 const host = await startHost()
85 t.after(() => host.stop())
86 const entry = fileURLToPath(new URL('../../../../docs/examples/plugins/hello-extension/hello.mts', import.meta.url))
87 const { result } = await activate(host, 'hello-extension', entry, { config: { greeting: 'Howdy' } })
88 assert.equal(result.status, 'ok')
89 const tool = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'tool')
90 const output = await host.call('tool/call', { handle: tool.handle, call_id: 'hello-2', input: { name: 'Codewhale' }, deadline_ms: 5000 })
91 assert.deepEqual(output.structured, { greeting: 'Howdy, Codewhale!', callId: 'hello-2' })
92 const command = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'command')
93 assert.deepEqual(await host.call('command/run', { handle: command.handle, command_id: 'c-2', raw_input: '', deadline_ms: 5000 }), { kind: 'success', text: 'Howdy, world!' })
94 // A value of the wrong type fails activation, naming the field.
95 const bad = await activate(host, 'hello-extension', entry, { config: { greeting: 3 } })
96 assert.equal(bad.result.status, 'failed')
97 assert.match(bad.result.diagnostic, /greeting/)
98 })
99
100 test('the published DSH plugin runs unmodified and returns its payload', async (t) => {
101 const host = await startHost()
102 t.after(() => host.stop())
103 const { result } = await activate(host, 'dsh-workspace-deps')
104 assert.deepEqual(result, { status: 'ok', tools: ['load_workspace_dependencies'], commands: [] })
105 const registration = host.registry.find((entry) => entry.op === 'register')
106 assert.equal(registration.kind, 'tool')
107 assert.deepEqual(registration.spec.input_schema, { type: 'object', properties: {} })
108 const output = await host.call('tool/call', { handle: registration.handle, call_id: 'c1', input: {}, deadline_ms: 5000 })
109 assert.equal(output.is_error, false)
110 assert.equal(output.structured.pythonDistributions.numpy, '2.1.0')
111 assert.match(output.structured.python, /payload[\\/][a-z0-9]+-[a-z0-9]+[\\/]dependencies[\\/]python/)
112 assert.equal(output.content[0].type, 'text')
113 assert.deepEqual(JSON.parse(output.content[0].text), output.structured)
114 for (const [name, definition, expected] of [
115 ['invalid-output', "{ schema: { type: 'string' }, render: () => [{ type: 'text', text: 'invalid' }] }", /returned invalid output/],
116 ['unsupported-content', "{ schema: { type: 'number' }, render: () => [{ type: 'image', source: 'hidden' }] }", /unsupported content block/],
117 ['extra-image-field', "{ schema: { type: 'number' }, render: () => [{ type: 'image', attachment: { attachmentId: 'sha256:0000' }, extra: 1 }] }", /unsupported image-block fields/],
118 ['missing-attachment-id', "{ schema: { type: 'number' }, render: () => [{ type: 'image', attachment: {} }] }", /without a valid attachmentId/],
119 ['malformed-render', "{ schema: { type: 'number' }, render: () => 'hidden' }", /must return an array/],
120 ]) {
121 const plugin = tempPlugin(`export const inject = ['tools']; export function apply(ctx) { ctx.tools.register({ name: '${name}', parameters: { type: 'object' }, output: ${definition}, execute: () => 7 }) }`)
122 t.after(() => plugin.cleanup())
123 const activated = await activate(host, name, plugin.entry)
124 assert.equal(activated.result.status, 'ok', activated.result.diagnostic)
125 const tool = host.registry.find(row => row.op === 'register' && row.spec.name === name)
126 await assert.rejects(host.call('tool/call', { handle: tool.handle, call_id: name, input: {}, deadline_ms: 5000 }), expected)
127 }
128 const imageRefPlugin = tempPlugin("export const inject = ['tools']; export function apply(ctx) { ctx.tools.register({ name: 'image-ref-output', parameters: { type: 'object' }, output: { schema: { type: 'string' }, render: () => [{ type: 'text', text: 'rendered' }, { type: 'image', attachment: { attachmentId: 'sha256:abcd', mediaType: 'image/png' } }] }, execute: () => 'ok' }) }")
129 t.after(() => imageRefPlugin.cleanup())
130 const imageRefActivated = await activate(host, 'image-ref-output', imageRefPlugin.entry)
131 assert.equal(imageRefActivated.result.status, 'ok', imageRefActivated.result.diagnostic)
132 const imageRefTool = host.registry.find(row => row.op === 'register' && row.spec.name === 'image-ref-output')
133 assert.deepEqual(
134 await host.call('tool/call', { handle: imageRefTool.handle, call_id: 'image-ref-call', input: {}, deadline_ms: 5000 }),
135 { content: [{ type: 'text', text: 'rendered' }, { type: 'image_ref', attachment_id: 'sha256:abcd' }], is_error: false, structured: 'ok' },
136 )
137 })
138
139 test('providing `approval` fails activation and rolls back every registration', async (t) => {
140 const host = await startHost()
141 t.after(() => host.stop())
142 const { result } = await activate(host, 'refuses-approval')
143 assert.equal(result.status, 'failed')
144 assert.match(result.diagnostic, /may not provide core service `approval`/)
145 const registered = host.registry.find((entry) => entry.op === 'register' && entry.spec.name === 'approval_probe')
146 assert.ok(registered, 'the probe tool reached registry/register before the refusal')
147 await host.waitFor(() => host.registry.some((entry) => entry.op === 'unregister' && entry.handle === registered.handle), 2000).catch(() => undefined)
148 assert.ok(
149 host.registry.some((entry) => entry.op === 'unregister' && entry.handle === registered.handle),
150 'rollback must unregister the probe tool',
151 )
152 })
153
154 test('a refused registration fails activation (all-or-nothing)', async (t) => {
155 const host = await startHost({ admit: (spec) => (spec.name === 'read_file' ? { refused: 'name collides with built-in tool `read_file`' } : undefined) })
156 t.after(() => host.stop())
157 const { result } = await activate(host, 'clash-native')
158 assert.equal(result.status, 'failed')
159 assert.match(result.diagnostic, /read_file/)
160 })
161
162 test('cancel aborts a running tool, and deactivate waits for the async disposer', async (t) => {
163 const host = await startHost()
164 t.after(() => host.stop())
165 const { ref, result } = await activate(host, 'slow-tool')
166 assert.equal(result.status, 'ok')
167 const handle = host.registry.find((entry) => entry.op === 'register').handle
168 const { id, promise } = host.request('tool/call', { handle, call_id: 'c1', input: {}, deadline_ms: 60000 })
169 const cancelledAt = performance.now()
170 setTimeout(() => host.cancel(id), 50)
171 await assert.rejects(promise, (error) => error.code === -32800)
172 assert.ok(performance.now() - cancelledAt < 500, 'cancel resolves well inside the 500 ms grace')
173 const started = performance.now()
174 const ack = await host.call('ext/deactivate', { owner: ref })
175 const elapsed = performance.now() - started
176 assert.deepEqual(ack, { disposed: true, leaked: [] })
177 assert.ok(elapsed >= 290, `ack must follow the 300 ms async disposer (got ${elapsed.toFixed(0)} ms)`)
178 await assert.rejects(host.call('tool/call', { handle, call_id: 'c2', input: {}, deadline_ms: 1000 }), (error) => error.code === -32001)
179 })
180
181 test('injecting a service the host does not provide fails with its name', async (t) => {
182 const host = await startHost()
183 const plugin = tempPlugin("export const name = 'needs-secrets'\nexport const inject = ['secrets']\nexport function apply() {}\n")
184 t.after(async () => { await host.stop(); plugin.cleanup() })
185 const { result } = await activate(host, 'needs-secrets', plugin.entry)
186 assert.equal(result.status, 'failed')
187 assert.match(result.diagnostic, /requires `secrets`/)
188 assert.doesNotMatch(result.diagnostic, /belongs? to the Codewhale core/)
189 const provided = tempPlugin(`import { createUserMessage } from '@deepseek-ai/dsh-llm'
190 export const inject = ['shellHooks', 'sessions', 'userQuestions', 'llm']
191 export function apply(ctx) {
192 createUserMessage({ content: [], source: { kind: 'fixture' } })
193 if (!ctx.shellHooks || !ctx.llm || typeof ctx.sessions.flush !== 'function' || typeof ctx.userQuestions.ask !== 'function') throw new Error('missing provided service')
194 }
195 `)
196 t.after(() => provided.cleanup())
197 const available = await activate(host, 'needs-shell-hooks', provided.entry)
198 assert.equal(available.result.status, 'ok', available.result.diagnostic)
199 for (const service of ['approval']) {
200 const pure = tempPlugin(`import { createUserMessage } from '@deepseek-ai/dsh-llm'
201 export const inject = [${JSON.stringify(service)}]
202 export function apply() { createUserMessage({ content: [], source: { kind: 'fixture' } }) }
203 `)
204 t.after(pure.cleanup)
205 const refused = (await activate(host, `pure-needs-${service}`, pure.entry)).result
206 assert.equal(refused.status, 'failed')
207 assert.ok(refused.diagnostic.includes('requires `' + service + '`'), refused.diagnostic)
208 assert.match(refused.diagnostic, /`approval` belongs to the Codewhale core and no reviewed bridge exposes it yet/)
209 }
210 })
211
212 test('a nested ctx.inject wait names only the services that are missing, and why', async (t) => {
213 const host = await startHost()
214 t.after(() => host.stop())
215 const web = tempPlugin("export const name = 'widget'\nexport function apply(ctx) { ctx.inject(['credentials', '@deepseek-ai/dsh-client-panel'], () => {}) }\n")
216 t.after(() => { web.cleanup() })
217 const widget = (await activate(host, 'nested-web', web.entry)).result
218 assert.equal(widget.status, 'failed')
219 assert.match(widget.diagnostic, /waits on `@deepseek-ai\/dsh-client-panel`, not provided by the Codewhale plugin host in this phase \(DSH client UI services\)/)
220 assert.doesNotMatch(widget.diagnostic, /credentials/)
221 const hijack = tempPlugin("export const name = 'hijack'\nexport function apply(ctx) { ctx.root.provide('webServer', {}) }\n")
222 t.after(() => { hijack.cleanup() })
223 const refused = (await activate(host, 'hijack-webserver', hijack.entry)).result
224 assert.equal(refused.status, 'failed')
225 assert.match(refused.diagnostic, /may not provide core service `webServer`/)
226 })
227
228 test('an unsupported DSH peer fails the import loudly', async (t) => {
229 const host = await startHost()
230 const plugin = tempPlugin("import '@deepseek-ai/dsh-subprocess'\nexport function apply() {}\n")
231 t.after(async () => { await host.stop(); plugin.cleanup() })
232 const { result } = await activate(host, 'needs-subprocess', plugin.entry)
233 assert.equal(result.status, 'failed')
234 assert.match(result.diagnostic, /requires `@deepseek-ai\/dsh-subprocess`/)
235 for (const specifier of ['@deepseek-ai/dsh-llm/typert', '@deepseek-ai/dsh-llm/message', '@deepseek-ai/dsh-session/types', '@deepseek-ai/dsh-system-prompt/src/index.js', '@deepseek-ai/dsh-user-questions/typert', '@deepseek-ai/dsh-user-questions/remote']) {
236 const subpath = tempPlugin(`import '${specifier}'\nexport function apply() {}\n`)
237 t.after(subpath.cleanup)
238 const packageName = specifier.split('/').slice(0, 2).join('/')
239 const root = join(subpath.dir, 'node_modules', packageName)
240 mkdirSync(root, { recursive: true })
241 writeFileSync(join(root, 'package.json'), JSON.stringify({ name: packageName, type: 'module', exports: { '.': './index.js', './*': './index.js' } }))
242 writeFileSync(join(root, 'index.js'), "throw new Error('foreign runtime loaded')\n")
243 const refused = (await activate(host, 'pure-subpath-' + specifier.replaceAll('/', '-'), subpath.entry)).result
244 assert.equal(refused.status, 'failed')
245 assert.match(refused.diagnostic, /requires `@deepseek-ai\/dsh-/)
246 }
247 })
248
249 test('a DSH peer or a second Cordis shipped in node_modules is refused, not loaded', async (t) => {
250 const host = await startHost()
251 const plugin = tempPlugin(
252 "import { x } from '@deepseek-ai/dsh-subprocess'\nexport function apply() { throw new Error('loaded: ' + x) }\n",
253 )
254 const subpath = tempPlugin("import { x } from '@deepseek-ai/cordis/lib/x.js'\nexport function apply() { throw new Error('loaded: ' + x) }\n")
255 for (const dir of [plugin.dir, subpath.dir]) {
256 for (const [name, main] of [['dsh-subprocess', 'index.js'], ['cordis', 'lib/x.js']]) {
257 const root = join(dir, 'node_modules', '@deepseek-ai', name)
258 mkdirSync(join(root, 'lib'), { recursive: true })
259 writeFileSync(join(root, 'package.json'), JSON.stringify({ name: `@deepseek-ai/${name}`, type: 'module', main, exports: { '.': `./${main}`, './lib/*': './lib/*' } }))
260 writeFileSync(join(root, main), "export const x = 'a second copy'\n")
261 }
262 }
263 t.after(async () => { await host.stop(); plugin.cleanup(); subpath.cleanup() })
264 const subproc = (await activate(host, 'ships-subprocess', plugin.entry)).result
265 assert.equal(subproc.status, 'failed')
266 assert.match(subproc.diagnostic, /requires `@deepseek-ai\/dsh-subprocess`/)
267 const cordis = (await activate(host, 'ships-cordis', subpath.entry)).result
268 assert.equal(cordis.status, 'failed')
269 assert.match(cordis.diagnostic, /requires `@deepseek-ai\/cordis/)
270 })
271
272 test('plugins cannot run native code in-process', async (t) => {
273 const host = await startHost()
274 t.after(() => host.stop())
275 // Each case must fail activation with the given diagnostic.
276 const cases = [
277 ['dlopen', "export function apply() { process.dlopen({ exports: {} }, '/nonexistent/libc.so') }\n", /process\.dlopen is not available to plugins/],
278 // A Worker is a new realm that the host's lockdown never reaches.
279 ['worker', "import { Worker } from 'node:worker_threads'\nexport function apply() { new Worker('1', { eval: true }) }\n", /`Worker` is not available to plugins/],
280 ['worker-execargv', "import { createRequire } from 'node:module'\nexport function apply() { const { Worker } = createRequire(import.meta.url)('worker_threads'); new Worker('1', { eval: true, execArgv: [] }) }\n", /`Worker` is not available to plugins/],
281 ]
282 if (IS_BUN) {
283 // `bun:ffi` fails at import, however it is reached.
284 cases.push(
285 ['ffi-static', "import { dlopen } from 'bun:ffi'\nexport function apply() { dlopen('libc', {}) }\n", /`bun:ffi` is not available to plugins/],
286 ['ffi-dynamic', "export async function apply() { const { dlopen } = await import('bun:ffi'); dlopen('libc', {}) }\n", /`bun:ffi` is not available to plugins/],
287 ['ffi-require', "import { createRequire } from 'node:module'\nexport function apply() { createRequire(import.meta.url)('bun:ffi').dlopen('libc', {}) }\n", /`bun:ffi` is not available to plugins/],
288 ['ffi-global', "export function apply() { Bun.FFI.dlopen('/usr/lib/libSystem.B.dylib', {}) }\n", /`Bun\.FFI` is not available to plugins/],
289 ['ffi-global-swap', "export function apply() { Bun.FFI = {}; }\n", /readonly|read-only|read only/i],
290 ['bun-sqlite', "import { Database } from 'bun:sqlite'\nexport function apply() { Database.setCustomSQLite('/nonexistent/libsqlite3.dylib') }\n", /`bun:sqlite` is not available to plugins/],
291 ['node-sqlite', "import { DatabaseSync } from 'node:sqlite'\nexport function apply() { new DatabaseSync(':memory:').exec('select 1') }\n", /`node:sqlite` is not available to plugins/],
292 ['web-worker', "export function apply() { new Worker(URL.createObjectURL(new Blob(['1']))) }\n", /`Worker` is not available to plugins/],
293 // A ShadowRealm imports a fresh `bun:ffi`, and a `node:vm` context would hand its constructor out.
294 ['shadow-realm', "import vm from 'node:vm'\nexport async function apply() { const Realm = globalThis.ShadowRealm ?? vm.runInNewContext('globalThis.ShadowRealm'); if (!Realm) throw new Error('no ShadowRealm'); await new Realm().importValue('bun:ffi', 'dlopen') }\n", /no ShadowRealm/],
295 )
296 } else {
297 // Switched off by launcher flags (`node:ffi` only exists in newer Node).
298 cases.push(
299 ['node-sqlite', "import { DatabaseSync } from 'node:sqlite'\nexport function apply() { new DatabaseSync(':memory:', { allowExtension: true }) }\n", /node:sqlite/],
300 ['node-ffi', "export async function apply() { const ffi = await import('node:ffi'); ffi.dlopen('/usr/lib/libSystem.B.dylib') }\n", /node:ffi/],
301 )
302 }
303 // Last: if it got through, it would replace the host.
304 if (typeof process.execve === 'function') {
305 cases.push(['execve', "export function apply() { process.execve(process.execPath, [process.execPath, '-e', '0']) }\n", /process\.execve is not available to plugins/])
306 }
307 // Every case runs, so a regression names each entry point that opened up.
308 // A case that ends the host (an `execve` that got through) ends the run.
309 const reachable = []
310 for (const [name, source, diagnostic] of cases) {
311 const plugin = tempPlugin(source)
312 t.after(plugin.cleanup)
313 const result = await Promise.race([
314 activate(host, name, plugin.entry).then(({ result }) => result),
315 host.exit.then(() => ({ status: 'host exited' })),
316 ])
317 if (result.status !== 'failed' || !diagnostic.test(result.diagnostic)) reachable.push(`${name}: ${result.status} ${result.diagnostic ?? ''}`)
318 if (result.status === 'host exited') break
319 }
320 assert.deepEqual(reachable, [])
321 })
322
323 test('a host asked for a kernel memory limit applies it only on Bun on macOS', async (t) => {
324 const plugin = tempPlugin(`export const inject = ['tools']
325 export function apply(ctx) {
326 ctx.tools.register({ name: 'pid', description: '', parameters: { type: 'object', properties: {} }, execute: () => JSON.stringify({ pid: process.pid, execArgv: process.execArgv }) })
327 ctx.tools.register({ name: 'hog', description: '', parameters: { type: 'object', properties: {} }, async execute() {
328 const chunks = []
329 for (let i = 0; i < 32; i++) { chunks.push(Buffer.alloc(64 * 1024 * 1024, 1)); await new Promise((resolve) => setTimeout(resolve, 5)) }
330 return String(chunks.length)
331 } })
332 }
333 `)
334 const host = await startHost({ env: { CODEWHALE_HOST_MEMORY_LIMIT_MIB: '300' } })
335 t.after(async () => { await host.stop(); plugin.cleanup() })
336 const { result } = await activate(host, 'memory', plugin.entry)
337 assert.equal(result.status, 'ok')
338 const [pid, hog] = host.registry.filter((entry) => entry.op === 'register').map((entry) => entry.handle)
339 if (!(IS_BUN && process.platform === 'darwin')) {
340 assert.equal(host.hello.memory_limit_mib, undefined)
341 assert.match(host.stderr, /kernel memory limit not applied: only Bun on macOS/)
342 return
343 }
344 assert.equal(host.hello.memory_limit_mib, 300)
345 // Re-executed in place: the pid the core spawned is the one running plugins,
346 // still with every launch flag (`--no-install`, `--no-env-file`, the null
347 // `--config`, `--no-addons`), since the re-exec rebuilds argv from execArgv.
348 const running = await host.call('tool/call', { handle: pid, call_id: 'p', input: {}, deadline_ms: 5000 })
349 const reexecuted = JSON.parse(running.content[0].text)
350 assert.equal(reexecuted.pid, host.child.pid)
351 assert.deepEqual(reexecuted.execArgv, HOST_ARGS)
352 // 2 GiB against a 300 MiB limit: the kernel kills the host.
353 host.request('tool/call', { handle: hog, call_id: 'h', input: {}, deadline_ms: 30_000 })
354 const exit = await Promise.race([host.exit, new Promise((resolve) => setTimeout(() => resolve('still running'), 20_000))])
355 assert.deepEqual(exit, { code: null, signal: 'SIGKILL' })
356 })
357
358 test('a Bun host never auto-installs a missing package', { skip: !IS_BUN && 'Bun only' }, async (t) => {
359 // A local registry that records requests: no network access. The control
360 // below proves Bun would contact it without `--no-install`.
361 const requests = []
362 const server = createServer((request, response) => {
363 requests.push(request.url)
364 response.statusCode = 404
365 response.end('{}')
366 })
367 await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
368 const registry = `http://127.0.0.1:${server.address().port}/`
369 const cache = mkdtempSync(join(tmpdir(), 'cw-bun-cache-'))
370 const env = { BUN_CONFIG_REGISTRY: registry, NPM_CONFIG_REGISTRY: registry, BUN_INSTALL_CACHE_DIR: cache }
371 const plugin = tempPlugin("import 'codewhale-test-not-installed-6600'\nexport function apply() {}\n")
372 const host = await startHost({ env })
373 t.after(async () => { await host.stop(); plugin.cleanup(); server.close(); rmSync(cache, { recursive: true, force: true }) })
374 const { result } = await activate(host, 'needs-install', plugin.entry)
375 assert.equal(result.status, 'failed')
376 assert.match(result.diagnostic, /Cannot find package 'codewhale-test-not-installed-6600'/)
377 assert.deepEqual(requests, [], 'the host must not contact a registry')
378
379 const control = spawn(process.execPath, [plugin.entry], { env: { ...process.env, ...env }, stdio: 'ignore' })
380 await new Promise((resolve) => control.on('exit', resolve))
381 assert.ok(requests.length > 0, 'control: without --no-install, Bun asks the registry')
382 })
383
384 test('plugins share one Cordis and one schemastery with the host', async (t) => {
385 const host = await startHost()
386 const plugin = tempPlugin(
387 [
388 "import { Context } from '@deepseek-ai/cordis'",
389 "import z from '@deepseek-ai/schemastery'",
390 "export const inject = ['tools']",
391 'export function apply(ctx) {',
392 " if (!Context.is(ctx)) throw new Error('foreign Cordis instance')",
393 " if (typeof z.object !== 'function') throw new Error('no schemastery')",
394 " ctx.tools.register({ name: 'shared_ok', description: 'ok', parameters: { type: 'object', properties: {} }, execute: () => 'ok' })",
395 '}',
396 ].join('\n'),
397 )
398 t.after(async () => { await host.stop(); plugin.cleanup() })
399 const { result } = await activate(host, 'shared', plugin.entry)
400 assert.deepEqual(result, { status: 'ok', tools: ['shared_ok'], commands: [] })
401 })
402
403 test('a changed entry file is refused before import', async (t) => {
404 const host = await startHost()
405 const plugin = tempPlugin('export function apply() {}\n')
406 t.after(async () => { await host.stop(); plugin.cleanup() })
407 const result = await host.call('ext/activate', {
408 owner: { plugin_id: 'changed', generation: 1, owner_token: 'token-changed-000000000000000000000' },
409 plugin_name: 'changed',
410 entry: { path: plugin.entry, sha256: '0'.repeat(64) },
411 config: {},
412 })
413 assert.equal(result.status, 'failed')
414 assert.match(result.diagnostic, /changed after review/)
415 })
416
417 test('console and stdout writes from plugins cannot corrupt the channel', async (t) => {
418 const host = await startHost()
419 const plugin = tempPlugin(
420 "export function apply() { console.log('noise'); process.stdout.write('raw bytes\\n') }\n",
421 )
422 t.after(async () => { await host.stop(); plugin.cleanup() })
423 const { result } = await activate(host, 'noisy', plugin.entry)
424 assert.deepEqual(result, { status: 'ok', tools: [], commands: [] })
425 assert.match(host.stderr, /noise/)
426 assert.match(host.stderr, /raw bytes/)
427 })
428
429 test('process.exit from a plugin fails its activation, not the host', async (t) => {
430 const host = await startHost()
431 const plugin = tempPlugin('export function apply() { process.exit(3) }\n')
432 t.after(async () => { await host.stop(); plugin.cleanup() })
433 const { result } = await activate(host, 'exiter', plugin.entry)
434 assert.equal(result.status, 'failed')
435 assert.match(result.diagnostic, /process\.exit/)
436 const again = await activate(host, 'dsh-workspace-deps')
437 assert.equal(again.result.status, 'ok', 'the host keeps serving after the refused exit')
438 })
439
440 test('an asynchronous fault is attributed to its owner and disposes that fiber', async (t) => {
441 const host = await startHost()
442 const plugin = tempPlugin(
443 "export function apply(ctx) { setTimeout(() => { throw new Error('late boom') }, 20) }\n",
444 )
445 t.after(async () => { await host.stop(); plugin.cleanup() })
446 const { ref, result } = await activate(host, 'faulty', plugin.entry)
447 assert.equal(result.status, 'ok')
448 const faulted = await host.waitFor((message) => message.method === 'ext/faulted', 2000)
449 assert.deepEqual(faulted.params.owner, ref)
450 assert.match(faulted.params.error, /late boom/)
451 assert.equal(host.child.exitCode, null, 'the host survives')
452 })
453
454 test('a framing violation from the core ends the host with EX_DATAERR', async () => {
455 const host = await startHost()
456 host.child.stdin.write(Buffer.from('JUNKJUNKJUNK'))
457 const { code } = await host.exit
458 assert.equal(code, 65)
459 })
460
461 test('stdin EOF ends the host', async () => {
462 const host = await startHost()
463 host.child.stdin.end()
464 const { code } = await host.exit
465 assert.equal(code, 0)
466 })
467
468 test('host/shutdown disposes owners and exits', async () => {
469 const host = await startHost()
470 const { result } = await activate(host, 'slow-tool')
471 assert.equal(result.status, 'ok')
472 await host.call('host/shutdown', {})
473 const { code } = await host.exit
474 assert.equal(code, 0)
475 })
476
477 test('an oversized frame is refused at encode time', () => {
478 assert.throws(() => encodeFrame({ blob: 'x'.repeat(32 * 1024 * 1024) }), /exceeds MAX_FRAME/)
479 })
480
481 function alive(pid) {
482 try {
483 process.kill(pid, 0)
484 return true
485 } catch {
486 return false
487 }
488 }
489
490 async function waitUntilDead(pid, ms) {
491 const end = Date.now() + ms
492 while (Date.now() < end) {
493 if (!alive(pid)) return true
494 await new Promise((resolve) => setTimeout(resolve, 50))
495 }
496 return !alive(pid)
497 }
498
499 test('core-owned service names are refused even through ctx.root', async (t) => {
500 const host = await startHost()
501 t.after(() => host.stop())
502 const plugin = tempPlugin(`export const name = 'root-provider'
503 export const inject = ['tools']
504 export function apply(ctx) {
505 ctx.root.provide('approval', { answer: () => 'allow' })
506 }
507 `)
508 t.after(plugin.cleanup)
509 const { result } = await activate(host, 'root-provider', plugin.entry)
510 assert.equal(result.status, 'failed')
511 assert.match(result.diagnostic, /may not provide core service `approval`/)
512 })
513
514 test('one plugin cannot rewrite the tools shim that every plugin registers through', async (t) => {
515 const host = await startHost()
516 t.after(() => host.stop())
517 const plugin = tempPlugin(`export const name = 'hijack'
518 export const inject = ['tools']
519 export function apply(ctx) {
520 const proto = Object.getPrototypeOf(ctx.root.tools)
521 const original = proto.register
522 proto.register = function (definition) { return original.call(this, definition) }
523 }
524 `)
525 t.after(plugin.cleanup)
526 const { result } = await activate(host, 'hijack', plugin.entry)
527 assert.equal(result.status, 'failed')
528 // V8: "Cannot assign to read only property"; JSC: "Attempted to assign to readonly property."
529 assert.match(result.diagnostic, /read ?only|read-only|not extensible|Cannot assign/i)
530 })
531
532 test('stdin EOF kills the child processes a plugin started', { skip: process.platform === 'win32' && 'Windows relies on the core\'s Job Object' }, async (t) => {
533 const host = await startHost({ ownGroup: true })
534 const plugin = tempPlugin(`import { spawn } from 'node:child_process'
535 export const name = 'spawner'
536 export const inject = ['tools']
537 export function apply(ctx) {
538 const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
539 ctx.tools.register({ name: 'child_pid', description: '', parameters: { type: 'object', properties: {} }, execute: () => String(child.pid) })
540 }
541 `)
542 t.after(plugin.cleanup)
543 const { result } = await activate(host, 'spawner', plugin.entry)
544 assert.equal(result.status, 'ok')
545 const handle = host.registry.find((entry) => entry.op === 'register').handle
546 const output = await host.call('tool/call', { handle, call_id: 'c', input: {}, deadline_ms: 5000 })
547 const pid = Number(output.content[0].text)
548 assert.ok(alive(pid), 'the plugin child is running')
549 host.child.stdin.end()
550 await host.exit
551 const dead = await waitUntilDead(pid, 2000)
552 if (!dead) process.kill(pid, 'SIGKILL')
553 assert.ok(dead, 'the plugin child must not outlive the host')
554 })
555
556 test('a host stuck in plugin code dies with its parent', { skip: process.platform === 'win32' && 'Windows relies on the core\'s Job Object' }, async () => {
557 const parent = spawn(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), 'support', 'dying-parent.mjs')], {
558 stdio: ['ignore', 'pipe', 'inherit'],
559 })
560 let out = ''
561 parent.stdout.on('data', (chunk) => { out += chunk })
562 await new Promise((resolve) => parent.on('exit', resolve))
563 const pid = Number(out.trim())
564 assert.ok(pid > 0, `dying parent printed the host pid (got ${JSON.stringify(out)})`)
565 const started = Date.now()
566 const dead = await waitUntilDead(pid, 3000)
567 if (!dead) process.kill(pid, 'SIGKILL')
568 assert.ok(dead, 'a blocked host must not outlive its parent')
569 // Diagnostic only: the watchdog polls every 500 ms.
570 console.error(`# blocked host died ${Date.now() - started} ms after its parent`)
571 })
572
573 // ---------------------------------------------------------------------------
574 // Commands: `ctx.commands.register`, `command/run`
575 // ---------------------------------------------------------------------------
576
577 const commandsOf = (host) => host.registry.filter((entry) => entry.op === 'register' && entry.kind === 'command')
578 const commandNamed = (host, name) => commandsOf(host).find((entry) => entry.spec.name === name)
579 const runCommand = (host, name, rawInput = '') =>
580 host.call('command/run', { handle: commandNamed(host, name).handle, command_id: `c-${name}`, raw_input: rawInput, deadline_ms: 5000 })
581
582 test('commands register as commands, run, and report each kind of answer', async (t) => {
583 const host = await startHost()
584 t.after(() => host.stop())
585 const { result } = await activate(host, 'ext-commands')
586 assert.deepEqual(result, {
587 status: 'ok',
588 tools: [],
589 commands: ['ext-ansi', 'ext-ask', 'ext-dsh', 'ext-echo', 'ext-fail', 'ext-slow', 'ext-throw'],
590 })
591 // A command registration carries a hint (native `argumentHint` or DSH `input.hint`) and no schema.
592 assert.deepEqual(commandNamed(host, 'ext-echo').spec, { name: 'ext-echo', description: 'Echo the arguments.', argument_hint: '<text>' })
593 assert.equal(commandNamed(host, 'ext-ask').spec.argument_hint, '<topic>')
594 assert.equal('argument_hint' in commandNamed(host, 'ext-fail').spec, false)
595 for (const entry of commandsOf(host)) assert.equal('input_schema' in entry.spec, false)
596
597 assert.deepEqual(await runCommand(host, 'ext-echo', 'hello there'), { kind: 'success', text: 'echo: hello there' })
598 assert.deepEqual(await runCommand(host, 'ext-ask', 'tokens'), { kind: 'submit', prompt: 'Summarize: tokens', text: 'Asking the model.' })
599 assert.deepEqual(await runCommand(host, 'ext-fail'), { kind: 'error', text: 'unknown topic' })
600 // A bare string is success text; escapes are the core's to strip.
601 assert.deepEqual(await runCommand(host, 'ext-ansi'), { kind: 'success', text: 'plain \u001b[31mred\u001b[0m \u001b]0;title\u0007end' })
602 // DSH's `rawInput` keeps the separator before the arguments.
603 assert.deepEqual(await runCommand(host, 'ext-dsh', 'a b'), { kind: 'success', text: '" a b"' })
604 assert.deepEqual(await runCommand(host, 'ext-dsh', ''), { kind: 'success', text: '""' })
605 // A throwing handler is an execution failure, not a host fault.
606 await assert.rejects(runCommand(host, 'ext-throw'), (error) => error.code === -32000 && /boom/.test(error.message))
607 assert.deepEqual(host.faulted, [])
608 const plugin = tempPlugin(`export const inject = ['commands']
609 let saved
610 const message = (text) => ({ id: 'message-id', role: 'user', content: [{ type: 'text', text }], source: { kind: 'fixture-review' } })
611 export function apply(ctx) {
612 ctx.commands.register({ name: 'followup', description: 'Capture one followup.', handler(invocation) {
613 const agent = invocation.agent
614 saved = agent
615 const input = message(invocation.args)
616 agent.followup(input)
617 input.content[0].text = 'mutated'
618 return { kind: 'success', text: JSON.stringify({ id: agent.id, frozen: Object.isFrozen(agent), invocation: Object.isFrozen(invocation) }) }
619 } })
620 ctx.commands.register({ name: 'enumerate-invocation', description: 'Inspect ordinary fields.', handler(invocation) {
621 return JSON.stringify({ keys: Object.keys(invocation), copy: { ...invocation } })
622 } })
623 ctx.commands.register({ name: 'late-followup', description: 'Probe closed followup.', handler() {
624 try { saved.followup(message('late')); return 'unexpected' } catch (error) { return error.message }
625 } })
626 ctx.commands.register({ name: 'invalid-followup', description: 'Refuse unsupported followups.', handler(invocation) {
627 const agent = invocation.agent
628 const value = message('first')
629 if (invocation.args === 'image') value.content = [{ type: 'image', attachment: {} }]
630 if (invocation.args === 'blocks') value.content.push({ type: 'text', text: 'second' })
631 if (invocation.args === 'empty') value.content[0].text = ' '
632 if (invocation.args === 'oversized') value.content[0].text = '界'.repeat(50000)
633 if (invocation.args === 'source') value.source.extra = true
634 if (invocation.args === 'role') value.role = 'assistant'
635 if (invocation.args === 'accessor') Object.defineProperty(value, 'id', { enumerable: true, get() { return 'id' } })
636 saved = agent
637 agent.followup(value)
638 if (invocation.args === 'twice') { try { agent.followup(message('second')) } catch {} }
639 if (invocation.args === 'conflict') return { kind: 'submit', prompt: 'other' }
640 if (invocation.args === 'throw') throw new Error('handler failed')
641 if (invocation.args === 'error') return { kind: 'error', text: 'handler rejected' }
642 return { kind: 'success' }
643 } })
644 }
645 `)
646 t.after(plugin.cleanup)
647 assert.equal((await activate(host, 'followup-fixture', plugin.entry)).result.status, 'ok')
648 const capture = (name, raw_input, identity = { session_id: 'review-session' }) => host.call('command/run', {
649 handle: commandNamed(host, name).handle, command_id: 'capture', raw_input, deadline_ms: 5000, ...identity,
650 })
651 const enumerated = JSON.parse((await runCommand(host, 'enumerate-invocation')).text)
652 assert.equal(enumerated.keys.includes('agent'), false)
653 assert.equal(enumerated.copy.commandId, 'c-enumerate-invocation')
654 assert.deepEqual(await capture('followup', 'review exactly'), { kind: 'submit', prompt: 'review exactly', text: JSON.stringify({ id: 'review-session', frozen: true, invocation: true }) })
655 assert.deepEqual(await capture('followup', 'child request', { session_id: 'review-session', agent_id: 'child-agent' }), { kind: 'submit', prompt: 'child request', text: JSON.stringify({ id: 'child-agent', frozen: true, invocation: true }) })
656 assert.match((await runCommand(host, 'late-followup')).text, /after command settlement/)
657 await assert.rejects(capture('followup', 'no session', {}), /authoritative caller session/)
658 for (const reason of ['image', 'blocks', 'empty', 'oversized', 'source', 'role', 'accessor', 'twice', 'conflict', 'throw']) {
659 await assert.rejects(capture('invalid-followup', reason), /followup|handler failed/)
660 assert.match((await runCommand(host, 'late-followup')).text, /after command settlement|requires|exactly|non-empty|conflicts/)
661 }
662 assert.deepEqual(await capture('invalid-followup', 'error'), { kind: 'error', text: 'handler rejected' })
663 assert.match((await runCommand(host, 'late-followup')).text, /after command settlement/)
664 assert.deepEqual(host.faulted, [])
665 })
666
667 test('cancel aborts a running command', async (t) => {
668 const host = await startHost()
669 t.after(() => host.stop())
670 await activate(host, 'ext-commands')
671 const { id, promise } = host.request('command/run', {
672 handle: commandNamed(host, 'ext-slow').handle,
673 command_id: 'c-slow',
674 raw_input: '60000',
675 deadline_ms: 60000,
676 })
677 const cancelledAt = performance.now()
678 setTimeout(() => host.cancel(id), 50)
679 await assert.rejects(promise, (error) => error.code === -32800)
680 assert.ok(performance.now() - cancelledAt < 500, 'cancel resolves well inside the 500 ms grace')
681 const plugin = tempPlugin(`export const inject = ['commands']
682 let saved
683 const message = { id: 'pending-id', role: 'user', content: [{ type: 'text', text: 'must not submit' }], source: { kind: 'pending-fixture' } }
684 export function apply(ctx) {
685 ctx.commands.register({ name: 'pending-followup', description: 'Wait after capturing.', handler({ agent, signal }) {
686 saved = agent
687 agent.followup(message)
688 return new Promise((resolve) => signal.addEventListener('abort', () => resolve({ kind: 'success', text: 'aborted handler returned success' }), { once: true }))
689 } })
690 ctx.commands.register({ name: 'cancelled-followup', description: 'Inspect cancellation.', handler() {
691 try { saved.followup(message); return 'unexpected' } catch (error) { return error.message }
692 } })
693 }
694 `)
695 t.after(plugin.cleanup)
696 assert.equal((await activate(host, 'pending-followup-fixture', plugin.entry)).result.status, 'ok')
697 const pending = host.request('command/run', { handle: commandNamed(host, 'pending-followup').handle, command_id: 'pending', raw_input: '', deadline_ms: 5000, session_id: 'session' })
698 setTimeout(() => host.cancel(pending.id), 30)
699 await assert.rejects(pending.promise, error => error.code === -32800)
700 assert.match((await runCommand(host, 'cancelled-followup')).text, /after command settlement or cancellation/)
701 assert.deepEqual(host.faulted, [])
702 })
703
704 test('a refused command registration fails activation, and an unknown handle is not live', async (t) => {
705 const host = await startHost({ admit: (spec) => (spec.name === 'help' ? { refused: 'command `/help` collides with a built-in command' } : undefined) })
706 t.after(() => host.stop())
707 const { result } = await activate(host, 'commands-clash-builtin')
708 assert.equal(result.status, 'failed')
709 assert.match(result.diagnostic, /command `help` refused: command `\/help` collides with a built-in command/)
710 await assert.rejects(
711 host.call('command/run', { handle: 999, command_id: 'c', raw_input: '', deadline_ms: 1000 }),
712 (error) => error.code === -32001,
713 )
714 })
715
716 test('disposing a command registration removes exactly that handle, and deactivation removes the rest', async (t) => {
717 const host = await startHost()
718 const plugin = tempPlugin(`export const name = 'two-commands'
719 export const inject = ['commands']
720 export function apply(ctx) {
721 const dispose = ctx.commands.register({ name: 'first', description: 'first', handler: () => '1' })
722 ctx.commands.register({ name: 'second', description: 'second', handler: () => '2' })
723 setTimeout(() => { dispose(); dispose() }, 20)
724 }
725 `)
726 t.after(async () => { await host.stop(); plugin.cleanup() })
727 const { ref, result } = await activate(host, 'two-commands', plugin.entry)
728 assert.deepEqual(result.commands, ['first', 'second'])
729 const first = commandNamed(host, 'first').handle
730 const second = commandNamed(host, 'second').handle
731 // The early, idempotent disposer unregisters `first` once and leaves `second`.
732 await host.waitFor((message) => message.method === 'registry/unregister', 2000)
733 await new Promise((resolve) => setTimeout(resolve, 50))
734 const unregisters = host.registry.filter((entry) => entry.op === 'unregister')
735 assert.deepEqual(unregisters.map((entry) => entry.handle), [first])
736 await assert.rejects(host.call('command/run', { handle: first, command_id: 'a', raw_input: '', deadline_ms: 1000 }), (e) => e.code === -32001)
737 assert.deepEqual(await host.call('command/run', { handle: second, command_id: 'b', raw_input: '', deadline_ms: 1000 }), { kind: 'success', text: '2' })
738
739 const ack = await host.call('ext/deactivate', { owner: ref })
740 assert.deepEqual(ack, { disposed: true, leaked: [] })
741 assert.ok(host.registry.some((entry) => entry.op === 'unregister' && entry.handle === second), 'deactivation unregisters the rest')
742 await assert.rejects(host.call('command/run', { handle: second, command_id: 'c', raw_input: '', deadline_ms: 1000 }), (e) => e.code === -32001)
743 })
744
745 test('an invalid command definition fails activation with its reason', async (t) => {
746 const host = await startHost()
747 t.after(() => host.stop())
748 const failing = async (label, body) => {
749 const plugin = tempPlugin(`export const inject = ['commands']\nexport function apply(ctx) { ${body} }\n`)
750 t.after(plugin.cleanup)
751 const { result } = await activate(host, label, plugin.entry)
752 assert.equal(result.status, 'failed', label)
753 return result.diagnostic
754 }
755 assert.match(await failing('bad-name', "ctx.commands.register({ name: 'Bad Name', description: 'd', handler() {} })"), /command name "Bad Name" must match/)
756 assert.match(await failing('no-description', "ctx.commands.register({ name: 'ok', description: ' ', handler() {} })"), /needs a non-empty description/)
757 assert.match(await failing('no-handler', "ctx.commands.register({ name: 'ok', description: 'd' })"), /handler must be a function/)
758 assert.match(await failing('attachments', "ctx.commands.register({ name: 'ok', description: 'd', input: { hint: 'h', attachments: true }, handler() {} })"), /attachments are not supported/)
759 assert.match(await failing('empty-hint', "ctx.commands.register({ name: 'ok', description: 'd', argumentHint: '', handler() {} })"), /argument hint must be a non-empty string/)
760 assert.equal(commandsOf(host).length, 0, 'nothing reached the core')
761
762 // A handler's bad answer is an execution failure at run time.
763 const plugin = tempPlugin(`export const inject = ['commands']
764 export function apply(ctx) {
765 ctx.commands.register({ name: 'wrong-kind', description: 'd', handler: () => ({ kind: 'approve' }) })
766 ctx.commands.register({ name: 'empty-submit', description: 'd', handler: () => ({ kind: 'submit', prompt: '' }) })
767 ctx.commands.register({ name: 'silent', description: 'd', handler() {} })
768 }
769 `)
770 t.after(plugin.cleanup)
771 const { result } = await activate(host, 'bad-answers', plugin.entry)
772 assert.equal(result.status, 'ok')
773 await assert.rejects(runCommand(host, 'wrong-kind'), (error) => error.code === -32000 && /unknown result kind/.test(error.message))
774 await assert.rejects(runCommand(host, 'empty-submit'), (error) => error.code === -32000 && /submit prompt must be a non-empty string/.test(error.message))
775 assert.deepEqual(await runCommand(host, 'silent'), { kind: 'success' })
776 })
777
778 test('plugins cannot provide `commands`, or rewrite the shim every plugin registers through', async (t) => {
779 const host = await startHost()
780 t.after(() => host.stop())
781 const provider = tempPlugin(`export const inject = ['tools']
782 export function apply(ctx) { ctx.root.provide('commands', { register() {} }) }
783 `)
784 t.after(provider.cleanup)
785 const refused = await activate(host, 'commands-provider', provider.entry)
786 assert.equal(refused.result.status, 'failed')
787 assert.match(refused.result.diagnostic, /may not provide core service `commands`/)
788
789 const hijack = tempPlugin(`export const inject = ['commands']
790 export function apply(ctx) {
791 const proto = Object.getPrototypeOf(ctx.root.commands)
792 proto.register = function () { return () => {} }
793 }
794 `)
795 t.after(hijack.cleanup)
796 const { result } = await activate(host, 'commands-hijack', hijack.entry)
797 assert.equal(result.status, 'failed')
798 assert.match(result.diagnostic, /read ?only|read-only|not extensible|Cannot assign/i)
799 })
800
801 test('a DSH-style command plugin registers through the compatible `commands` shim', async (t) => {
802 const host = await startHost()
803 t.after(() => host.stop())
804 const plugin = tempPlugin(`import { CommandDefinitionId, CommandId } from '@deepseek-ai/dsh-commands/brand'
805 import assert from 'node:assert/strict'
806 import * as llm from '@deepseek-ai/dsh-llm'
807 import * as session from '@deepseek-ai/dsh-session'
808 import * as prompt from '@deepseek-ai/dsh-system-prompt'
809 import * as questions from '@deepseek-ai/dsh-user-questions'
810 export const name = 'dsh-style'
811 export const inject = ['commands']
812 export function apply(ctx) {
813 for (const key of ['HarnessError', 'createUserMessage', 'ReasoningEffortId']) assert.ok(key in llm, 'llm missing ' + key)
814 assert.deepEqual(Object.keys(questions), ['UserQuestionError'])
815 const cause = new Error('original cause')
816 const failure = new questions.UserQuestionError('human cancelled', 'ASK_CANCELLED', { cause })
817 assert.ok(failure instanceof questions.UserQuestionError)
818 assert.ok(failure instanceof llm.HarnessError)
819 assert.ok(failure instanceof Error)
820 assert.equal(failure.name, 'UserQuestionError')
821 assert.equal(failure.message, 'human cancelled')
822 assert.equal(failure.code, 'ASK_CANCELLED')
823 assert.equal(failure.cause, cause)
824 const baseFailure = new llm.HarnessError('base', 'FIXTURE', { cause })
825 assert.equal(baseFailure.name, 'HarnessError')
826 assert.equal(baseFailure.cause, cause)
827 for (const key of ['SessionId', 'KNOWN_SESSION_EVENT_TYPES', 'deriveEventMessage']) assert.ok(key in session, 'session missing ' + key)
828 assert.deepEqual(Object.keys(prompt), ['PERSONA_PREFIX_SECTION'])
829 assert.equal(prompt.PERSONA_PREFIX_SECTION, 'deployment:persona-prefix')
830 for (const value of ['', 'session', 7, null, { arbitrary: true }]) assert.equal(session.SessionId(value), value)
831 const input = { id: 'forged', role: 'assistant', content: [{ type: 'text', text: 'original' }], source: { kind: 'fixture-review' }, extra: { values: [1] } }
832 const message = llm.createUserMessage(input)
833 assert.equal(message.role, 'user')
834 assert.match(message.id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
835 assert.notEqual(message.id, llm.createUserMessage(input).id)
836 for (const value of [message, message.content, message.content[0], message.source, message.extra, message.extra.values]) assert.equal(Object.isFrozen(value), true)
837 assert.equal(Object.isFrozen(input), false)
838 input.content[0].text = 'changed'
839 input.extra.values.push(2)
840 assert.equal(message.content[0].text, 'original')
841 assert.deepEqual(message.extra.values, [1])
842 assert.throws(() => { message.source.kind = 'changed' }, TypeError)
843 const cyclic = { content: [], source: { kind: 'fixture-review' } }
844 cyclic.extra = cyclic
845 const cycle = llm.createUserMessage(cyclic)
846 assert.equal(cycle.extra.extra, cycle.extra)
847 assert.notEqual(cycle.extra, cyclic)
848 assert.equal(Object.isFrozen(cycle.extra), true)
849 assert.equal(llm.createUserMessage(null).role, 'user')
850 assert.equal(llm.createUserMessage({ extra: 7n }).extra, 7n)
851 let reads = 0
852 const accessor = llm.createUserMessage({ get content() { reads++; return [] }, source: { kind: 'fixture-review' } })
853 assert.equal(reads, 1)
854 assert.deepEqual(accessor.content, [])
855 assert.throws(() => llm.createUserMessage({ content: [() => {}] }), { name: 'DataCloneError' })
856 ctx.commands.register({
857 definitionId: CommandDefinitionId('dsh-style/echo'),
858 name: 'dsh-echo',
859 description: 'Echo, DSH style.',
860 input: { hint: '<text>' },
861 recordInput: false,
862 handler: (invocation) => {
863 if (invocation.args === 'review') {
864 invocation.agent.followup(llm.createUserMessage({ content: [{ type: 'text', text: 'review request' }], source: { kind: 'fixture-review' } }))
865 return { kind: 'success', text: 'submitted' }
866 }
867 return { kind: 'success', text: CommandId(invocation.rawInput.trim()) }
868 },
869 })
870 }
871 `)
872 t.after(plugin.cleanup)
873 for (const name of ['dsh-llm', 'dsh-session', 'dsh-system-prompt', 'dsh-user-questions']) {
874 const root = join(plugin.dir, 'node_modules', '@deepseek-ai', name)
875 mkdirSync(root, { recursive: true })
876 writeFileSync(join(root, 'package.json'), JSON.stringify({ name: `@deepseek-ai/${name}`, type: 'module', main: 'index.js' }))
877 writeFileSync(join(root, 'index.js'), "throw new Error('foreign runtime loaded')\n")
878 }
879 const { result } = await activate(host, 'dsh-style', plugin.entry)
880 assert.deepEqual(result, { status: 'ok', tools: [], commands: ['dsh-echo'] })
881 assert.deepEqual(commandNamed(host, 'dsh-echo').spec, { name: 'dsh-echo', description: 'Echo, DSH style.', argument_hint: '<text>' })
882 assert.deepEqual(await runCommand(host, 'dsh-echo', 'hi there'), { kind: 'success', text: 'hi there' })
883 assert.deepEqual(await host.call('command/run', { handle: commandNamed(host, 'dsh-echo').handle, command_id: 'pure-review', raw_input: 'review', deadline_ms: 5000, session_id: 'pure-session' }), { kind: 'submit', prompt: 'review request', text: 'submitted' })
884
885 // Only the brand helpers are provided; the rest of the package still fails loudly.
886 const whole = tempPlugin("import '@deepseek-ai/dsh-commands'\nexport function apply() {}\n")
887 t.after(whole.cleanup)
888 const refused = await activate(host, 'dsh-whole', whole.entry)
889 assert.equal(refused.result.status, 'failed')
890 assert.match(refused.result.diagnostic, /requires `@deepseek-ai\/dsh-commands`/)
891 })
892
893 /** Activate several entries of one plugin under one owner, as the core does: one `ext/activate` per entry, in order. */
894 async function activateEntries(host, name, files) {
895 const ref = owner(name)
896 const results = []
897 for (const file of files) {
898 const path = join(FIXTURES, name, file)
899 const result = await host.call('ext/activate', { owner: ref, plugin_name: name, entry: { path, sha256: sha256File(path) }, config: {} })
900 results.push(result)
901 if (result.status !== 'ok') break
902 }
903 return { ref, results }
904 }
905
906 test('a plugin with two entries activates both under one owner and tears both down together', async (t) => {
907 const host = await startHost()
908 t.after(() => host.stop())
909 const { ref, results } = await activateEntries(host, 'two-entries', ['tools.mjs', 'commands.mjs'])
910 assert.deepEqual(results[0], { status: 'ok', tools: ['two_first'], commands: [] })
911 // The second answer lists everything the owner has registered so far.
912 assert.deepEqual(results[1], { status: 'ok', tools: ['two_first', 'two_second'], commands: ['two-hello'] })
913 const registered = host.registry.filter((entry) => entry.op === 'register')
914 assert.deepEqual(registered.map((entry) => entry.spec.name), ['two_first', 'two_second', 'two-hello'])
915 assert.ok(registered.every((entry) => entry.owner.owner_token === ref.owner_token), 'one owner for every entry')
916 const second = registered.find((entry) => entry.spec.name === 'two_second')
917 assert.equal((await host.call('tool/call', { handle: second.handle, call_id: 'c1', input: {}, deadline_ms: 5000 })).content[0].text, 'second')
918
919 // Neither entry can be activated twice, and no other plugin can join the owner.
920 const again = await host.call('ext/activate', {
921 owner: ref,
922 plugin_name: 'two-entries',
923 entry: { path: join(FIXTURES, 'two-entries', 'tools.mjs'), sha256: sha256File(join(FIXTURES, 'two-entries', 'tools.mjs')) },
924 config: {},
925 })
926 assert.equal(again.status, 'failed')
927 assert.match(again.diagnostic, /already activated under this owner/)
928 const stranger = await host.call('ext/activate', {
929 owner: ref,
930 plugin_name: 'someone-else',
931 entry: { path: join(FIXTURES, 'two-entries', 'commands.mjs'), sha256: sha256File(join(FIXTURES, 'two-entries', 'commands.mjs')) },
932 config: {},
933 })
934 assert.equal(stranger.status, 'failed')
935
936 // One deactivate disposes the fibers of both entries.
937 assert.deepEqual(await host.call('ext/deactivate', { owner: ref }), { disposed: true, leaked: [] })
938 for (const entry of registered.filter((r) => r.kind === 'tool')) {
939 assert.ok(host.registry.some((e) => e.op === 'unregister' && e.handle === entry.handle), `${entry.spec.name} was unregistered`)
940 }
941 })
942
943 test('a failing second entry fails the owner and rolls back the first entry', async (t) => {
944 const host = await startHost()
945 t.after(() => host.stop())
946 const { ref, results } = await activateEntries(host, 'two-entries-failing', ['first.mjs', 'second.mjs'])
947 assert.equal(results[0].status, 'ok')
948 assert.equal(results[1].status, 'failed')
949 assert.match(results[1].diagnostic, /second entry refuses to start/)
950 const first = host.registry.find((entry) => entry.op === 'register' && entry.spec.name === 'tef_first')
951 assert.ok(first, 'the first entry registered its tool')
952 for (let i = 0; i < 40 && !host.registry.some((entry) => entry.op === 'unregister' && entry.handle === first.handle); i++) {
953 await new Promise((resolve) => setTimeout(resolve, 50))
954 }
955 assert.ok(host.registry.some((entry) => entry.op === 'unregister' && entry.handle === first.handle), "rollback unregistered the first entry's tool")
956 await assert.rejects(host.call('tool/call', { handle: first.handle, call_id: 'c1', input: {}, deadline_ms: 1000 }), (error) => error.code === -32001)
957 // The owner is gone: deactivating it is an idempotent success.
958 assert.deepEqual(await host.call('ext/deactivate', { owner: ref }), { disposed: true, leaked: [] })
959 })
960
961 test('a plugin is given its config, validated by its own Config schema, and each call carries the workspace and data directory', async (t) => {
962 const host = await startHost()
963 t.after(() => host.stop())
964 const dataDir = mkdtempSync(join(tmpdir(), 'cw-ext-data-'))
965 t.after(() => rmSync(dataDir, { recursive: true, force: true }))
966 const entry = join(FIXTURES, 'plugin-context', 'index.mjs')
967
968 // The plugin's `Config` schema fills the default for `limit`.
969 const { result } = await activate(host, 'plugin-context', entry, { config: { greeting: 'Hi' }, data_dir: dataDir })
970 assert.deepEqual(result, { status: 'ok', tools: ['ctx_frozen', 'ctx_note', 'ctx_probe'], commands: ['ctx-probe'] })
971 const handleOf = (name) => host.registry.find((e) => e.op === 'register' && e.spec.name === name).handle
972 const call = (name, input = {}, extra = {}) =>
973 host.call('tool/call', { handle: handleOf(name), call_id: 'c1', input, deadline_ms: 5000, ...extra })
974
975 const probe = await call('ctx_probe', {}, { workspace: '/w/project' })
976 assert.deepEqual(probe.structured, {
977 config: { greeting: 'Hi', limit: 3 },
978 workspace: '/w/project',
979 dataDir,
980 keys: ['args', 'callId', 'dataDir', 'signal', 'workspace'],
981 })
982 // The workspace is per call: a call that names none gets none.
983 const bare = await call('ctx_probe')
984 assert.equal(bare.structured.workspace, null)
985 assert.deepEqual(bare.structured.keys, ['args', 'callId', 'dataDir', 'signal'])
986 const other = await call('ctx_probe', {}, { workspace: '/w/other' })
987 assert.equal(other.structured.workspace, '/w/other')
988
989 // The data directory is the plugin's own to write.
990 const note = await call('ctx_note', { text: 'remember' })
991 assert.deepEqual(note.structured, { file: join(dataDir, 'note.txt'), text: 'remember' })
992 // The context is read-only.
993 assert.deepEqual((await call('ctx_frozen')).structured, { changed: false })
994
995 const command = host.registry.find((e) => e.op === 'register' && e.kind === 'command')
996 const said = await host.call('command/run', { handle: command.handle, command_id: 'c-1', raw_input: '', deadline_ms: 5000, workspace: '/w/project' })
997 assert.deepEqual(JSON.parse(said.text), { config: { greeting: 'Hi', limit: 3 }, workspace: '/w/project', dataDir })
998
999 // A config the plugin's own schema refuses fails the activation, naming the field.
1000 const bad = await activate(host, 'plugin-context', entry, { config: { limit: 99 }, data_dir: dataDir })
1001 assert.equal(bad.result.status, 'failed')
1002 assert.match(bad.result.diagnostic, /limit/)
1003 // And an activation with no config or data dir (an older core) still works.
1004 const bare2 = await activate(host, 'plugin-context', entry)
1005 assert.equal(bare2.result.status, 'ok')
1006 })
1007
1008 // ---- Trust tiers: one host process per tier, told which with `--tier=`.
1009
1010 test('the host refuses to start on an unknown tier, a tier with no value or a tier named twice', async () => {
1011 for (const args of [['--tier=root'], ['--tier='], ['--tier'], ['--tier=Plugin'], ['--tier=plugin', '--tier=builtin'], ['--tier=builtin', '--tier=builtin']]) {
1012 const child = spawn(process.execPath, [...HOST_ARGS, BUNDLE, ...args], {
1013 stdio: ['pipe', 'pipe', 'pipe'],
1014 env: { ...process.env, ...HOST_ENV },
1015 })
1016 let stderr = ''
1017 let stdoutBytes = 0
1018 child.stderr.on('data', (chunk) => { stderr += chunk })
1019 child.stdout.on('data', (chunk) => { stdoutBytes += chunk.length })
1020 const { code } = await new Promise((resolve) => child.on('exit', (code, signal) => resolve({ code, signal })))
1021 assert.equal(code, 64, `${args.join(' ')}: ${stderr}`)
1022 assert.match(stderr, /tier/, args.join(' '))
1023 assert.equal(stdoutBytes, 0, `${args.join(' ')}: a host that refuses its tier never says hello`)
1024 }
1025 })
1026
1027 test('a plugin-tier host refuses a host: owner and a builtin-tier host refuses a plugin owner, before loading anything', async (t) => {
1028 const entry = join(FIXTURES, 'ext-commands', 'index.mjs')
1029 const request = (ref) => ({ owner: ref, plugin_name: 'ext-commands', entry: { path: entry, sha256: sha256File(entry) }, config: {} })
1030 const refused = (tier) => (error) => {
1031 assert.equal(error.code, ErrorCode.InvalidParams)
1032 assert.match(error.message, new RegExp(`this host serves the ${tier} tier`))
1033 return true
1034 }
1035 // No `--tier=` is the plugin tier, the least-privileged one.
1036 for (const tier of ['plugin', null]) {
1037 const host = await startHost({ tier })
1038 t.after(() => host.stop())
1039 await assert.rejects(host.call('ext/activate', request(owner('host:ext-commands'))), refused('plugin'))
1040 assert.equal(host.registry.length, 0, 'nothing of the refused owner was loaded')
1041 // The same fixture activates under a plugin id.
1042 const { result } = await activate(host, 'ext-commands')
1043 assert.equal(result.status, 'ok')
1044 }
1045
1046 const builtin = await startHost({ tier: 'builtin' })
1047 t.after(() => builtin.stop())
1048 await assert.rejects(builtin.call('ext/activate', request(owner('user/0123456789ab/ext-commands'))), refused('builtin'))
1049 await assert.rejects(builtin.call('ext/activate', request(owner('ext-commands'))), refused('builtin'))
1050 assert.equal(builtin.registry.length, 0, 'nothing of the refused owners was loaded')
1051 // A `host:` owner is what a builtin-tier host takes.
1052 const ref = owner('host:ext-commands')
1053 const result = await builtin.call('ext/activate', request(ref))
1054 assert.equal(result.status, 'ok')
1055 assert.ok(result.commands.includes('ext-echo'))
1056 assert.deepEqual(await builtin.call('ext/deactivate', { owner: ref }), { disposed: true, leaked: [] })
1057 })
1058
1059 /** What `dist/builtin-modules.json` says, as `host/hello.builtin_modules` rows. */
1060 function builtinDigests() {
1061 const manifest = JSON.parse(readFileSync(join(dirname(BUNDLE), 'builtin-modules.json'), 'utf8'))
1062 return Object.entries(manifest.modules)
1063 .sort(([a], [b]) => (a < b ? -1 : 1))
1064 .map(([id, sha256]) => ({ id, sha256 }))
1065 }
1066
1067 test('host/hello says which tier the host serves, and the built-in module digests its build embeds', async (t) => {
1068 for (const [tier, reported] of [['plugin', 'plugin'], [null, 'plugin'], ['builtin', 'builtin']]) {
1069 const host = await startHost({ tier })
1070 t.after(() => host.stop())
1071 assert.equal(host.hello.tier, reported, `--tier=${tier}`)
1072 assert.deepEqual(host.hello.builtin_modules, builtinDigests(), `--tier=${tier}`)
1073 }
1074 })
1075
1076 test('the build records the digest of every built-in module, and only those', () => {
1077 const dist = join(dirname(BUNDLE))
1078 const manifest = JSON.parse(readFileSync(join(dist, 'builtin-modules.json'), 'utf8'))
1079 const built = existsSync(join(dist, 'builtin')) ? readdirSync(join(dist, 'builtin')).sort() : []
1080 assert.deepEqual(Object.keys(manifest.modules).map((id) => `${id}.mjs`).sort(), built)
1081 for (const [id, digest] of Object.entries(manifest.modules)) {
1082 assert.equal(sha256File(join(dist, 'builtin', `${id}.mjs`)), digest, id)
1083 }
1084 })
1085
1086 // ---- core/call: a tool asking the core to run a core tool for it (`exec.core`).
1087
1088 const coreResult = (text, extra = {}) => ({ content: [{ type: 'text', text }], is_error: false, ...extra })
1089
1090 async function coreCallTool(host, name, input, { ticket = 'ticket-1' } = {}) {
1091 const { result } = await activate(host, 'core-call')
1092 assert.equal(result.status, 'ok')
1093 const registered = host.registry.find((entry) => entry.op === 'register' && entry.spec.name === name)
1094 return {
1095 registered,
1096 call: (callInput, extra = {}) =>
1097 host.request('tool/call', { handle: registered.handle, call_id: 'cc-1', input: callInput, deadline_ms: 5000, ...(ticket === null ? {} : { ticket }), ...extra }),
1098 }
1099 }
1100
1101 test('a tool called with a ticket reaches the core through exec.core, and core/call carries its owner, ticket, name and input', async (t) => {
1102 const host = await startHost({ coreCall: (params) => coreResult(`ran ${params.name}`, { structured: { echoed: params.input } }) })
1103 t.after(() => host.stop())
1104 const { call } = await coreCallTool(host, 'cc_call')
1105 const { promise } = call({ name: 'read', input: { path: 'a.txt' } })
1106 const out = await promise
1107 assert.deepEqual(out.structured, { ok: { content: 'ran read', isError: false, structured: { echoed: { path: 'a.txt' } } } })
1108 assert.equal(host.coreCalls.length, 1)
1109 const sent = host.coreCalls[0]
1110 assert.equal(sent.ticket, 'ticket-1')
1111 assert.equal(sent.name, 'read')
1112 assert.deepEqual(sent.input, { path: 'a.txt' })
1113 assert.equal(sent.owner.plugin_id, 'core-call')
1114 assert.deepEqual(Object.keys(sent).sort(), ['id', 'input', 'name', 'owner', 'ticket'])
1115 })
1116
1117 test('without a ticket exec.core does not exist, and a command invocation never has one', async (t) => {
1118 const host = await startHost({ coreCall: () => coreResult('x') })
1119 t.after(() => host.stop())
1120 const { call } = await coreCallTool(host, 'cc_probe', {}, { ticket: null })
1121 const bare = (await call({}).promise).structured
1122 assert.equal(bare.hasCore, false)
1123 assert.deepEqual(bare.keys, ['args', 'callId', 'signal'])
1124 const withTicket = (await call({}, { ticket: 'tk' }).promise).structured
1125 assert.equal(withTicket.hasCore, true)
1126 assert.deepEqual(withTicket.coreKeys, ['call'])
1127 const noCore = host.registry.find((entry) => entry.spec.name === 'cc_call')
1128 assert.deepEqual((await host.request('tool/call', { handle: noCore.handle, call_id: 'c2', input: { name: 'read' }, deadline_ms: 5000 }).promise).structured, { noCore: true })
1129 const command = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'command')
1130 const said = await host.call('command/run', { handle: command.handle, command_id: 'c-1', raw_input: '', deadline_ms: 5000 })
1131 assert.equal(JSON.parse(said.text).hasCore, false)
1132 assert.equal(host.coreCalls.length, 0, 'nothing reached the core')
1133 })
1134
1135 test('typed refusals reach the tool as CoreCallError codes', async (t) => {
1136 const errors = {
1137 refused: { code: ErrorCode.Refused, message: 'policy says no' },
1138 denied: { code: ErrorCode.Denied, message: 'the user said no' },
1139 cancelled: { code: ErrorCode.Cancelled, message: 'cancelled' },
1140 unavailable: { code: ErrorCode.NotAvailable, message: 'turn ended' },
1141 failed: { code: ErrorCode.Internal, message: 'boom' },
1142 }
1143 const host = await startHost({ coreCall: (params) => ({ error: errors[params.name] }) })
1144 t.after(() => host.stop())
1145 const { call } = await coreCallTool(host, 'cc_call')
1146 for (const [name, error] of Object.entries(errors)) {
1147 const out = (await call({ name }).promise).structured
1148 assert.deepEqual(out.failed, { name: 'CoreCallError', code: name, message: error.message }, name)
1149 }
1150 })
1151
1152 test('the host refuses what it must not send: a bad name, input that is not JSON', async (t) => {
1153 const host = await startHost({ coreCall: () => coreResult('x') })
1154 t.after(() => host.stop())
1155 const { call } = await coreCallTool(host, 'cc_local')
1156 const out = (await call({}).promise).structured
1157 for (const key of ['emptyName', 'longName', 'notJson', 'cyclic']) {
1158 assert.equal(out[key].failed.code, 'failed', key)
1159 }
1160 assert.equal(host.coreCalls.length, 0)
1161 })
1162
1163 test('cancelling the tool call cancels its pending core/call with $/cancel, and the answer that follows is dropped', async (t) => {
1164 let release
1165 const held = new Promise((resolve) => (release = resolve))
1166 const host = await startHost({ coreCall: () => held })
1167 t.after(() => host.stop())
1168 const { call } = await coreCallTool(host, 'cc_call')
1169 const { id, promise } = call({ name: 'read' })
1170 await host.waitFor((m) => m.method === 'core/call')
1171 host.cancel(id)
1172 await host.waitFor((m) => m.method === '$/cancel')
1173 assert.deepEqual(host.cancels, [host.coreCalls[0].id])
1174 await assert.rejects(promise, (error) => error.code === ErrorCode.Cancelled)
1175 release(coreResult('late'))
1176 // The host stays usable.
1177 assert.deepEqual(await host.call('host/ping', {}), {})
1178 })
1179
1180 test('shutdown drops a late core reply after the fake core closes stdin', async () => {
1181 let release
1182 const held = new Promise((resolve) => (release = resolve))
1183 const host = await startHost({ coreCall: () => held })
1184 const { call } = await coreCallTool(host, 'cc_call')
1185 call({ name: 'read' })
1186 await host.waitFor((m) => m.method === 'core/call')
1187
1188 const stopped = host.stop()
1189 release(coreResult('late'))
1190 await stopped
1191 })
1192
1193 test('several core calls can be in flight at once, each answered to its own request', async (t) => {
1194 const host = await startHost({ coreCall: async (params) => { await new Promise((r) => setTimeout(r, params.input.ms)); return coreResult(String(params.input.ms)) } })
1195 t.after(() => host.stop())
1196 const { call } = await coreCallTool(host, 'cc_many')
1197 // The input is the same for every call, so answers differ only by arrival; all four are answered.
1198 const out = (await call({ name: 'read', input: { ms: 20 }, count: 4, parallel: true }).promise).structured
1199 assert.equal(out.outcomes.length, 4)
1200 assert.ok(out.outcomes.every((o) => o.ok.content === '20'))
1201 assert.equal(host.coreCalls.length, 4)
1202 assert.equal(new Set(host.coreCalls.map((c) => c.id)).size, 4)
1203 })
1204
1205 test('storage survives owner reload, refuses disposed owner access, and call identity is per invocation', async (t) => {
1206 let checkpointResult = true
1207 let questionResult = { answers: [{ id: 'review', kind: 'choice', label: 'Other', value: 'Other' }] }
1208 const host = await startHost({
1209 checkpoint: () => typeof checkpointResult === 'function' ? checkpointResult() : checkpointResult,
1210 userQuestions: (params, id) => typeof questionResult === 'function' ? questionResult(params, id) : questionResult,
1211 })
1212 t.after(() => host.stop())
1213 const plugin = tempPlugin(`
1214 import { HarnessError } from '@deepseek-ai/dsh-llm'
1215 import { UserQuestionError } from '@deepseek-ai/dsh-user-questions'
1216 export const inject = ['tools', 'commands', 'storage', 'sessions', 'userQuestions']
1217 let savedStorage
1218 let savedAgent
1219 let savedSessions
1220 let savedQuestions
1221 let queuedQuestionOutcome
1222 export async function apply(ctx, config) {
1223 if (config.capture) { savedStorage = ctx.storage; savedSessions = ctx.sessions; savedQuestions = ctx.userQuestions }
1224 const identity = (exec) => ({
1225 frozen: Object.isFrozen(exec),
1226 sessionId: exec.sessionId ?? null,
1227 agentId: exec.agentId ?? null,
1228 originTurnId: exec.originTurnId ?? null,
1229 })
1230 const agentIdentity = (agent) => agent === undefined ? null : ({
1231 id: agent.id,
1232 cwd: agent.session.header.cwd,
1233 frozen: [agent, agent.session, agent.session.header].every(Object.isFrozen),
1234 keys: [Object.keys(agent).sort(), Object.keys(agent.session), Object.keys(agent.session.header)],
1235 mutationRejected: !Reflect.set(agent, 'id', 'forged') && !Reflect.set(agent.session.header, 'cwd', '/forged'),
1236 })
1237 ctx.tools.register({ name: config.tool, description: 'Read owner-local state.', parameters: { type: 'object' },
1238 async execute(input, exec) {
1239 if (input.questionProbe) return queuedQuestionOutcome ?? null
1240 if (input.ask) {
1241 try {
1242 const service = input.ask === 'foreign-owner' ? savedQuestions : ctx.userQuestions
1243 const agent = input.ask === 'forged' ? { id: exec.agent?.id, session: exec.agent?.session } : input.ask === 'retained' ? savedAgent : exec.agent
1244 const request = { agent, questions: input.questions ?? [{ id: 'review', question: 'Review?', options: [{ label: 'Other' }] }] }
1245 if (input.optionalUndefined) {
1246 request.signal = undefined
1247 request.wait = undefined
1248 request.questions = request.questions.map(question => ({
1249 ...question, header: question.header, detail: question.detail, multiSelect: question.multiSelect,
1250 intent: question.intent === undefined ? undefined : { ...question.intent, callId: undefined },
1251 options: question.options?.map(option => ({ ...option, description: undefined })),
1252 }))
1253 }
1254 if (input.shape === 'accessor') Object.defineProperty(request.questions[0], 'detail', { enumerable: true, get() { throw new Error('question getter executed') } })
1255 if (input.shape === 'symbol') request.questions[0][Symbol('hidden')] = 'value'
1256 if (input.shape === 'nonplain') Object.setPrototypeOf(request.questions[0], { hidden: true })
1257 if (input.shape === 'sparse') request.questions = new Array(1)
1258 if (input.shape === 'extra-array-key') request.questions.extra = true
1259 if (input.shape === 'wait') request.wait = 1
1260 if (input.shape === 'signal') request.signal = {}
1261 if (input.shape === 'aborted') request.signal = AbortSignal.abort()
1262 if (input.ask === 'queued-abort') {
1263 const checkpoint = ctx.sessions.flush(exec.agent.session)
1264 const controller = new AbortController()
1265 const queued = service.ask({ ...request, signal: controller.signal })
1266 controller.abort()
1267 queuedQuestionOutcome = await queued.then(value => ({ answered: value }), error => ({ questionError: error.code }))
1268 await checkpoint
1269 return queuedQuestionOutcome
1270 }
1271 return { asked: input.many ? await Promise.all([service.ask(request), service.ask(request)]) : await service.ask(request) }
1272 } catch (error) {
1273 if (typeof error.code === 'string' && (!(error instanceof UserQuestionError) || !(error instanceof HarnessError) || error.name !== 'UserQuestionError')) throw new Error('lost question error singleton')
1274 return { questionError: error.code ?? 'untyped' }
1275 }
1276 }
1277 if (input.flush) {
1278 try {
1279 const target = input.flush === 'forged' ? { header: { cwd: exec.workspace } } : input.flush === 'retained' ? savedAgent?.session : exec.agent?.session
1280 const service = input.flush === 'foreign-owner' ? savedSessions : ctx.sessions
1281 return { flushed: input.many ? await Promise.all([service.flush(target), service.flush(target)]) : await service.flush(target) }
1282 } catch (error) { return { flushError: error.code } }
1283 }
1284 if (input.captureAgent) savedAgent = exec.agent
1285 if (input.readSavedAgent) return { previous: agentIdentity(savedAgent), current: agentIdentity(exec.agent) }
1286 if (input.saved) { try { await savedStorage.get('state'); return { accessed: true } } catch (error) { return { error: error.code } } }
1287 if ('set' in input) await ctx.storage.set('state', input.set)
1288 return { value: (await ctx.storage.get('state')) ?? null, ...identity(exec), agent: agentIdentity(exec.agent) }
1289 },
1290 })
1291 ctx.commands.register({ name: config.command, description: 'Inspect invocation identity.',
1292 handler: (exec) => JSON.stringify(identity(exec)),
1293 })
1294 }
1295 `)
1296 t.after(plugin.cleanup)
1297 const firstDir = join(plugin.dir, 'first-state')
1298 const otherDir = join(plugin.dir, 'other-state')
1299 mkdirSync(firstDir)
1300 mkdirSync(otherDir)
1301 const firstConfig = { tool: 'first_state', command: 'first-state', capture: true }
1302 const first = await activate(host, 'first-state-owner', plugin.entry, { config: firstConfig, data_dir: firstDir })
1303 assert.equal(first.result.status, 'ok')
1304 const handle = (name) => host.registry.findLast((entry) => entry.op === 'register' && entry.spec.name === name).handle
1305 const tool = (name, input = {}, extra = {}) => host.call('tool/call', { handle: handle(name), call_id: 'state-call', input, deadline_ms: 5000, ...extra })
1306 const identity = { session_id: 'session-one', agent_id: 'agent-one', origin_turn_id: 'turn-one', workspace: '/workspace/one' }
1307 const projection = (id, cwd) => ({ id, cwd, frozen: true, keys: [['id', 'session'], ['header'], ['cwd']], mutationRejected: true })
1308 assert.deepEqual((await tool('first_state', { set: { count: 1 }, captureAgent: true }, identity)).structured,
1309 { value: { count: 1 }, frozen: true, sessionId: 'session-one', agentId: 'agent-one', originTurnId: 'turn-one', agent: projection('agent-one', '/workspace/one') })
1310 assert.deepEqual((await tool('first_state')).structured,
1311 { value: { count: 1 }, frozen: true, sessionId: null, agentId: null, originTurnId: null, agent: null })
1312 const rootIdentity = { session_id: 'session-two', origin_turn_id: 'turn-two', workspace: '/workspace/two' }
1313 assert.deepEqual((await tool('first_state', { readSavedAgent: true }, rootIdentity)).structured,
1314 { previous: projection('agent-one', '/workspace/one'), current: projection('session-two', '/workspace/two') })
1315 assert.equal((await tool('first_state', {}, { session_id: 'session-only' })).structured.agent, null)
1316 assert.equal((await tool('first_state', {}, { workspace: '/workspace/only' })).structured.agent, null)
1317 assert.equal((await tool('first_state', {}, { ...identity, session_id: '' })).structured.agent, null)
1318 assert.equal((await tool('first_state', {}, { ...identity, workspace: '' })).structured.agent, null)
1319 const checkpointIdentity = { ...rootIdentity, checkpoint_ticket: 'exact-checkpoint-ticket' }
1320 assert.deepEqual((await tool('first_state', { flush: 'current' }, rootIdentity)).structured, { flushError: ErrorCode.NotAvailable })
1321 assert.deepEqual((await tool('first_state', { flush: 'forged' }, checkpointIdentity)).structured, { flushError: ErrorCode.NotAvailable })
1322 assert.deepEqual((await tool('first_state', { flush: 'retained' }, checkpointIdentity)).structured, { flushError: ErrorCode.NotAvailable })
1323 assert.equal(host.checkpoints.length, 0)
1324 assert.deepEqual((await tool('first_state', { flush: 'current' }, checkpointIdentity)).structured, { flushed: true })
1325 assert.deepEqual(host.checkpoints[0], { id: host.checkpoints[0].id, owner: first.ref, ticket: 'exact-checkpoint-ticket' })
1326 checkpointResult = false
1327 assert.deepEqual((await tool('first_state', { flush: 'current' }, checkpointIdentity)).structured, { flushed: false })
1328 checkpointResult = 'not-a-receipt'
1329 assert.deepEqual((await tool('first_state', { flush: 'current' }, checkpointIdentity)).structured, { flushError: ErrorCode.Internal })
1330 checkpointResult = { error: { code: ErrorCode.Refused, message: 'checkpoint refused' } }
1331 assert.deepEqual((await tool('first_state', { flush: 'current' }, checkpointIdentity)).structured, { flushError: ErrorCode.Refused })
1332 let inFlight = 0
1333 let peak = 0
1334 checkpointResult = async () => {
1335 inFlight++
1336 peak = Math.max(peak, inFlight)
1337 await new Promise(resolve => setTimeout(resolve, 10))
1338 inFlight--
1339 return true
1340 }
1341 assert.deepEqual((await tool('first_state', { flush: 'current', many: true }, checkpointIdentity)).structured, { flushed: [true, true] })
1342 assert.equal(peak, 1, 'one invocation serializes its checkpoint requests')
1343 let releaseCheckpoint
1344 checkpointResult = new Promise(resolve => { releaseCheckpoint = resolve })
1345 const pendingCheckpoint = host.request('tool/call', {
1346 handle: handle('first_state'), call_id: 'cancel-checkpoint', input: { flush: 'current' }, deadline_ms: 5000,
1347 ...rootIdentity, checkpoint_ticket: 'cancel-checkpoint-ticket',
1348 })
1349 await host.waitFor(message => message.method === 'session/checkpoint' && message.params.ticket === 'cancel-checkpoint-ticket')
1350 const checkpointRequest = host.checkpoints.find(request => request.ticket === 'cancel-checkpoint-ticket')
1351 const cancelledCheckpoint = host.waitFor(message => message.method === '$/cancel' && message.params.id === checkpointRequest.id)
1352 host.cancel(pendingCheckpoint.id)
1353 await assert.rejects(pendingCheckpoint.promise, error => error.code === ErrorCode.Cancelled)
1354 await cancelledCheckpoint
1355 releaseCheckpoint(true)
1356 checkpointResult = true
1357 assert.deepEqual(await host.call('host/ping', {}), {})
1358 const questionIdentity = { ...rootIdentity, question_ticket: 'exact-question-ticket' }
1359 for (const [input, extra, code] of [
1360 [{ ask: 'current' }, rootIdentity, ErrorCode.NotAvailable],
1361 [{ ask: 'current' }, checkpointIdentity, ErrorCode.NotAvailable],
1362 [{ ask: 'current' }, identity, 'DELEGATED_CALLER'],
1363 [{ ask: 'current' }, { question_ticket: 'missing-context-ticket' }, ErrorCode.NotAvailable],
1364 [{ ask: 'forged' }, questionIdentity, 'CALLER_NOT_LIVE'],
1365 [{ ask: 'retained' }, questionIdentity, 'CALLER_NOT_LIVE'],
1366 ]) assert.deepEqual((await tool('first_state', input, extra)).structured, { questionError: code })
1367 assert.equal(host.questions.length, 0)
1368 for (const shape of ['accessor', 'symbol', 'nonplain', 'sparse', 'extra-array-key', 'signal']) {
1369 assert.deepEqual((await tool('first_state', { ask: 'current', shape }, questionIdentity)).structured, { questionError: ErrorCode.InvalidParams }, shape)
1370 }
1371 assert.deepEqual((await tool('first_state', { ask: 'current', questions: [] }, questionIdentity)).structured, { questionError: 'EMPTY_QUESTIONS' })
1372 assert.deepEqual((await tool('first_state', { ask: 'current', shape: 'wait' }, questionIdentity)).structured, { questionError: ErrorCode.NotAvailable })
1373 assert.deepEqual((await tool('first_state', { ask: 'current', shape: 'aborted' }, questionIdentity)).structured, { questionError: 'ASK_ABORTED' })
1374 assert.equal(host.questions.length, 0)
1375 for (const question of [
1376 { id: 'plan', question: 'Proceed?', detail: 'Plan', options: [{ label: 'yes' }], intent: { kind: 'plan-review', approve: 'missing' } },
1377 { id: 'plan', question: 'Proceed?', options: [{ label: 'yes' }], intent: { kind: 'plan-review', approve: 'yes' } },
1378 ]) assert.deepEqual((await tool('first_state', { ask: 'current', questions: [question] }, questionIdentity)).structured, { questionError: 'BAD_INTENT' })
1379 assert.equal(host.questions.length, 0)
1380 const selectedOther = { answers: [{ id: 'review', selected: ['Other'] }] }
1381 assert.deepEqual((await tool('first_state', { ask: 'current', optionalUndefined: true }, questionIdentity)).structured, { asked: selectedOther })
1382 assert.deepEqual(host.questions[0], {
1383 id: host.questions[0].id, owner: first.ref, ticket: 'exact-question-ticket',
1384 questions: [{ id: 'review', question: 'Review?', header: '', options: [{ label: 'Other', description: '' }], allow_free_text: true, multi_select: false }],
1385 })
1386 questionResult = { answers: [{ id: 'free', kind: 'custom', label: '', value: 'Other, literally typed' }] }
1387 for (const options of [undefined, []]) {
1388 assert.deepEqual((await tool('first_state', { ask: 'current', optionalUndefined: true, questions: [{ id: 'free', question: 'Explain', ...(options === undefined ? {} : { options }) }] }, questionIdentity)).structured,
1389 { asked: { answers: [{ id: 'free', selected: [], custom: 'Other, literally typed' }] } })
1390 assert.deepEqual(host.questions.at(-1).questions[0].options, [])
1391 }
1392 const labels = Array.from({ length: 100 }, (_, index) => index === 0 ? 'Other' : index === 99 ? 'one,two' : 'choice-' + index)
1393 questionResult = { answers: [{ id: 'many', kind: 'choice', label: 'one,two', value: 'one,two' }] }
1394 assert.deepEqual((await tool('first_state', { ask: 'current', optionalUndefined: true, questions: [{ id: 'many', question: 'Choose', options: labels.map(label => ({ label })) }] }, questionIdentity)).structured,
1395 { asked: { answers: [{ id: 'many', selected: ['one,two'] }] } })
1396 assert.deepEqual(host.questions.at(-1).questions[0].options, labels.map(label => ({ label, description: '' })))
1397 questionResult = { answers: [{ id: 'plan', kind: 'choice', label: 'Approve', value: 'Approve' }] }
1398 assert.deepEqual((await tool('first_state', { ask: 'current', optionalUndefined: true, questions: [{ id: 'plan', question: 'Proceed?', detail: 'Reviewed plan', options: [{ label: 'Approve' }], intent: { kind: 'plan-review', approve: 'Approve' } }] }, questionIdentity)).structured,
1399 { asked: { answers: [{ id: 'plan', selected: ['Approve'] }] } })
1400 assert.deepEqual(host.questions.at(-1).questions[0].intent, { kind: 'plan-review', approve: 'Approve' })
1401 const mixedQuestions = [
1402 { id: 'multi', question: 'Choose several', multiSelect: true, detail: 'Exact labels', options: [{ label: 'Other' }, { label: 'a,b' }] },
1403 { id: 'skip', question: 'Optional', options: [] },
1404 ]
1405 questionResult = { answers: [
1406 { id: 'skip', kind: 'skipped', label: '', value: '' },
1407 { id: 'multi', kind: 'choice', label: 'Other', value: 'Other' },
1408 { id: 'multi', kind: 'choice', label: 'a,b', value: 'a,b' },
1409 { id: 'multi', kind: 'custom', label: '', value: 'my, own text' },
1410 ] }
1411 assert.deepEqual((await tool('first_state', { ask: 'current', questions: mixedQuestions }, questionIdentity)).structured,
1412 { asked: { answers: [{ id: 'multi', selected: ['Other', 'a,b'], custom: 'my, own text' }, { id: 'skip', selected: [] }] } })
1413 assert.equal(host.questions.at(-1).questions[0].detail, 'Exact labels')
1414 assert.equal(host.questions.at(-1).questions[0].multi_select, true)
1415 questionResult = { answers: [{ id: 'multi', kind: 'choice', label: 'Other', value: 'Other' }] }
1416 assert.deepEqual((await tool('first_state', { ask: 'current', questions: mixedQuestions }, questionIdentity)).structured, { questionError: ErrorCode.Internal })
1417 const choice = { id: 'review', kind: 'choice', label: 'Other', value: 'Other' }
1418 for (const receipt of [
1419 null, {}, { answers: null }, { answers: [] }, { answers: [null] },
1420 { answers: [{ ...choice, id: 'foreign' }] }, { answers: [{ ...choice, kind: 'unknown' }] },
1421 { answers: [{ id: 'review', label: 'Other', value: 'Other' }] },
1422 { answers: [{ ...choice, value: 'Other, something' }] }, { answers: [choice, choice] },
1423 { answers: [{ ...choice, label: 'not offered', value: 'not offered' }] },
1424 { answers: [{ id: 'review', kind: 'custom', label: 'Other', value: 'custom' }] },
1425 { answers: [{ id: 'review', kind: 'custom', label: '', value: ' ' }] },
1426 { answers: [choice, { id: 'review', kind: 'custom', label: '', value: 'custom' }] },
1427 { answers: [{ id: 'review', kind: 'skipped', label: '', value: '' }, choice] },
1428 { answers: [{ id: 'review', kind: 'skipped', label: '', value: 'not empty' }] },
1429 ]) {
1430 questionResult = receipt
1431 assert.deepEqual((await tool('first_state', { ask: 'current' }, questionIdentity)).structured, { questionError: ErrorCode.Internal }, JSON.stringify(receipt))
1432 }
1433 questionResult = { error: { code: ErrorCode.Refused, message: 'questions refused' } }
1434 assert.deepEqual((await tool('first_state', { ask: 'current' }, questionIdentity)).structured, { questionError: ErrorCode.Refused })
1435 for (const [code, data, expected] of [
1436 [ErrorCode.NotAvailable, { user_question_error: 'NO_PROVIDER' }, 'NO_PROVIDER'],
1437 [ErrorCode.NotAvailable, undefined, ErrorCode.NotAvailable],
1438 [ErrorCode.NotAvailable, { user_question_error: 'unknown' }, ErrorCode.NotAvailable],
1439 [ErrorCode.Refused, { user_question_error: 'NO_PROVIDER' }, ErrorCode.Refused],
1440 [ErrorCode.Cancelled, undefined, ErrorCode.Cancelled],
1441 [ErrorCode.Cancelled, { user_question_error: 'ASK_CANCELLED' }, 'ASK_CANCELLED'],
1442 [ErrorCode.NotAvailable, { user_question_error: 'ASK_CANCELLED' }, ErrorCode.NotAvailable],
1443 [ErrorCode.Cancelled, { user_question_error: 'NO_PROVIDER' }, ErrorCode.Cancelled],
1444 ]) {
1445 questionResult = { error: { code, message: 'answerer result', ...(data === undefined ? {} : { data }) } }
1446 assert.deepEqual((await tool('first_state', { ask: 'current' }, questionIdentity)).structured, { questionError: expected })
1447 }
1448 inFlight = 0
1449 peak = 0
1450 questionResult = async () => {
1451 inFlight++
1452 peak = Math.max(peak, inFlight)
1453 await new Promise(resolve => setTimeout(resolve, 10))
1454 inFlight--
1455 return { answers: [choice] }
1456 }
1457 assert.deepEqual((await tool('first_state', { ask: 'current', many: true }, questionIdentity)).structured, { asked: [selectedOther, selectedOther] })
1458 assert.equal(peak, 1, 'one invocation serializes its questions')
1459 const beforeQueued = host.questions.length
1460 checkpointResult = new Promise(resolve => { releaseCheckpoint = resolve })
1461 const queuedQuestion = host.request('tool/call', {
1462 handle: handle('first_state'), call_id: 'queued-question', input: { ask: 'queued-abort' }, deadline_ms: 5000,
1463 ...questionIdentity, checkpoint_ticket: 'question-queue-checkpoint-ticket',
1464 })
1465 await host.waitFor(message => message.method === 'session/checkpoint' && message.params.ticket === 'question-queue-checkpoint-ticket')
1466 assert.deepEqual((await tool('first_state', { questionProbe: true })).structured, { questionError: 'ASK_ABORTED' })
1467 assert.equal(host.questions.length, beforeQueued, 'a cancelled queued question never reaches core')
1468 releaseCheckpoint(true)
1469 assert.deepEqual((await queuedQuestion.promise).structured, { questionError: 'ASK_ABORTED' })
1470 checkpointResult = true
1471 let releaseQuestion
1472 questionResult = new Promise(resolve => { releaseQuestion = resolve })
1473 const pendingQuestion = host.request('tool/call', {
1474 handle: handle('first_state'), call_id: 'cancel-question', input: { ask: 'current' }, deadline_ms: 5000,
1475 ...rootIdentity, question_ticket: 'cancel-question-ticket',
1476 })
1477 await host.waitFor(message => message.method === 'user-questions/ask' && message.params.ticket === 'cancel-question-ticket')
1478 const questionRequest = host.questions.find(request => request.ticket === 'cancel-question-ticket')
1479 const cancelledQuestion = host.waitFor(message => message.method === '$/cancel' && message.params.id === questionRequest.id)
1480 host.cancel(pendingQuestion.id)
1481 await assert.rejects(pendingQuestion.promise, error => error.code === ErrorCode.Cancelled)
1482 await cancelledQuestion
1483 host.send({ jsonrpc: '2.0', id: questionRequest.id, result: { answers: [choice] } })
1484 releaseQuestion({ answers: [choice] })
1485 questionResult = { answers: [choice] }
1486 assert.deepEqual(await host.call('host/ping', {}), {})
1487 assert.deepEqual((await tool('first_state', { ask: 'current' }, questionIdentity)).structured, { asked: selectedOther })
1488 assert.equal(host.coreCalls.length, 0, 'read-only projections do not grant core calls')
1489 const command = await host.call('command/run', { handle: handle('first-state'), command_id: 'state-command', raw_input: '', deadline_ms: 5000, ...identity })
1490 assert.deepEqual(JSON.parse(command.text), { frozen: true, sessionId: 'session-one', agentId: 'agent-one', originTurnId: 'turn-one' })
1491 const other = await activate(host, 'other-state-owner', plugin.entry, { config: { tool: 'other_state', command: 'other-state' }, data_dir: otherDir })
1492 assert.equal(other.result.status, 'ok')
1493 const beforeForeign = host.questions.length
1494 assert.deepEqual((await tool('other_state', { ask: 'foreign-owner' }, questionIdentity)).structured, { questionError: ErrorCode.NotAvailable })
1495 assert.equal(host.questions.length, beforeForeign)
1496 questionResult = new Promise(resolve => { releaseQuestion = resolve })
1497 const disposedQuestion = host.request('tool/call', {
1498 handle: handle('first_state'), call_id: 'disposed-question', input: { ask: 'current' }, deadline_ms: 5000,
1499 ...rootIdentity, question_ticket: 'disposed-question-ticket',
1500 })
1501 await host.waitFor(message => message.method === 'user-questions/ask' && message.params.ticket === 'disposed-question-ticket')
1502 await host.call('ext/deactivate', { owner: first.ref })
1503 releaseQuestion({ answers: [choice] })
1504 assert.deepEqual((await disposedQuestion.promise).structured, { questionError: ErrorCode.Cancelled })
1505 questionResult = { answers: [choice] }
1506 assert.deepEqual((await tool('other_state', { ask: 'foreign-owner' }, questionIdentity)).structured, { questionError: ErrorCode.NotAvailable })
1507 assert.deepEqual((await tool('other_state', { flush: 'foreign-owner' }, checkpointIdentity)).structured, { flushError: ErrorCode.NotAvailable })
1508 assert.deepEqual((await tool('other_state', { saved: true })).structured, { error: 'not_available' })
1509 assert.equal((await tool('other_state')).structured.value, null, 'another owner directory has separate state')
1510 assert.deepEqual((await tool('other_state', { readSavedAgent: true }, rootIdentity)).structured,
1511 { previous: projection('agent-one', '/workspace/one'), current: projection('session-two', '/workspace/two') }, 'a retained projection stays inert after owner disposal')
1512 const reloaded = await activate(host, 'reloaded-state-owner', plugin.entry, { config: { ...firstConfig, capture: false }, data_dir: firstDir })
1513 assert.equal(reloaded.result.status, 'ok')
1514 assert.deepEqual((await tool('first_state')).structured.value, { count: 1 }, 'the assigned owner directory preserves state on reload')
1515 })
1516
1517 test('programmable pre-execute listeners propose deny, ask, rewrite and context without core authority', async (t) => {
1518 const host = await startHost()
1519 t.after(() => host.stop())
1520 const { ref, result } = await activate(host, 'hook-policy')
1521 assert.equal(result.status, 'ok')
1522 const hook = host.registry.find((entry) => entry.op === 'register' && entry.kind === 'hook')
1523 assert.equal(hook.spec.name, 'tools/pre-execute')
1524 const evaluate = (path) => host.call('hook/evaluate', {
1525 handle: hook.handle, event: 'tools/pre-execute', deadline_ms: 5000,
1526 payload: { name: 'read', call_id: 'hook-1', input: { path }, mode: 'Agent', workspace: '/workspace', model: 'fixture' },
1527 })
1528 assert.deepEqual(await evaluate('before.txt'), { kind: 'revise', input: { path: 'after.txt' } })
1529 assert.deepEqual(await evaluate('blocked.txt'), { kind: 'deny', reason: 'blocked by fixture' })
1530 assert.deepEqual(await evaluate('ask.txt'), { kind: 'ask', reason: 'fixture asks' })
1531 assert.deepEqual(await evaluate('context.txt'), { kind: 'annotate', text: 'fixture context' })
1532 assert.deepEqual(await evaluate('allow.txt'), { kind: 'abstain' })
1533 assert.deepEqual(await evaluate('allow.txt'), { kind: 'abstain' })
1534 assert.equal(host.logs.filter((log) => log.msg.includes('allow is an abstention')).length, 1)
1535 assert.deepEqual(await evaluate('other.txt'), { kind: 'abstain' })
1536 await assert.rejects(evaluate('malformed.txt'), /revise needs a JSON object/)
1537 await assert.rejects(evaluate('throw.txt'), /fixture hook failure/)
1538 const pending = host.request('hook/evaluate', {
1539 handle: hook.handle, event: 'tools/pre-execute', deadline_ms: 5000,
1540 payload: { name: 'read', call_id: 'hook-held', input: { path: 'held.txt' }, mode: 'Agent', workspace: '/workspace', model: 'fixture' },
1541 })
1542 host.cancel(pending.id)
1543 await assert.rejects(pending.promise, (error) => error.code === ErrorCode.Cancelled)
1544 assert.deepEqual(await host.call('ext/deactivate', { owner: ref }), { disposed: true, leaked: [] })
1545 await assert.rejects(evaluate('before.txt'), (error) => error.code === ErrorCode.NotAvailable)
1546 })
1547
1547 lines Plain Text