返回 CodeWhale
creator-host.test.mjs
根目录 / crates / engine / extension-host / test / creator-host.test.mjs
1 import { test, before } from 'node:test'
2 import assert from 'node:assert/strict'
3 import { createHash } from 'node:crypto'
4 import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
5 import { tmpdir } from 'node:os'
6 import { join, dirname } from 'node:path'
7 import { fileURLToPath, pathToFileURL } from 'node:url'
8 import { build } from 'esbuild'
9 import { startHost, activate, owner as makeOwner, sha256File } from './harness.mjs'
10
11 const here = dirname(fileURLToPath(import.meta.url))
12 const creatorBundle = join(here, '..', 'dist', 'builtin', 'creator.mjs')
13 const upstreamToolsPath = join(here, '..', 'src', 'dsh', 'upstream', 'creator', 'plugin-manager', 'tools.js')
14 const upstreamEscalationPath = join(here, '..', 'src', 'dsh', 'upstream', 'creator', 'sandbox', 'escalation.js')
15 const licensesPath = join(here, '..', 'dist', 'LICENSES.txt')
16 let HostRoot
17
18 before(async () => {
19 const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-creator-test-'))
20 const rootOut = join(dir, 'root.mjs')
21 await build({
22 entryPoints: [join(here, '../src/root.ts')],
23 outfile: rootOut,
24 bundle: true,
25 platform: 'node',
26 format: 'esm',
27 packages: 'external',
28 absWorkingDir: join(here, '..'),
29 logLevel: 'silent',
30 })
31 ;({ HostRoot } = await import(pathToFileURL(rootOut).href))
32 process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
33 })
34
35 function sha256Text(text) {
36 return createHash('sha256').update(text, 'utf8').digest('hex')
37 }
38
39 function fakeRpc(brokerFn) {
40 let seq = 1
41 return {
42 notify: () => {},
43 request: async (method, params) => {
44 if (method === 'registry/register') return { handle: seq++ }
45 if (method === 'registry/unregister') return {}
46 if (method === 'dsh/broker') return brokerFn(params)
47 return {}
48 },
49 }
50 }
51
52 function makeTempPlugin(t, code) {
53 const dir = mkdtempSync(join(tmpdir(), 'cw-creator-unit-'))
54 t.after(() => rmSync(dir, { recursive: true, force: true }))
55 const path = join(dir, 'index.mjs')
56 writeFileSync(path, code)
57 return { path, sha256: sha256File(path) }
58 }
59
60 function makeCallParams(handle, id, input, extra = {}) {
61 return {
62 handle,
63 call_id: id,
64 input,
65 deadline_ms: 5000,
66 workspace: '/tmp/ws',
67 caller_tools: [],
68 broker_tickets: [{ service: 'plugins', ticket: 't1' }],
69 ...extra,
70 }
71 }
72
73 test('the creator module registers plugin_manager with DSH\'s own description and parameters', async (t) => {
74 const host = await startHost({ tier: 'builtin' })
75 t.after(() => host.stop())
76
77 const { result } = await activate(host, 'host:creator', creatorBundle)
78 assert.equal(result.status, 'ok')
79 const registered = host.registry.find((r) => r.op === 'register' && r.kind === 'tool' && r.spec.name === 'plugin_manager')
80 assert.ok(registered)
81
82 const upstreamSource = readFileSync(upstreamToolsPath, 'utf8')
83 const match = upstreamSource.match(/name:\s*'plugin_manager',\s*\n\s*description:\s*'([^']+)'/)
84 assert.ok(match, 'expected pinned plugin_manager description in upstream tools.js')
85 assert.equal(sha256Text(registered.spec.description), sha256Text(match[1]))
86
87 assert.deepEqual(registered.spec.input_schema.required, ['action'])
88 assert.deepEqual(Object.keys(registered.spec.input_schema.properties), [
89 'action',
90 'target',
91 'enabled',
92 'runtimeVersion',
93 'acceptRisk',
94 'approvedBuilds',
95 'registry',
96 'offset',
97 'limit',
98 ])
99 assert.deepEqual(registered.spec.input_schema.properties.action.enum, [
100 'list_plugins',
101 'list_bundles',
102 'set_plugin',
103 'set_bundle',
104 'install_bundle',
105 'remove_bundle',
106 'list_version_exemptions',
107 'set_version_exemption',
108 ])
109 })
110
111 test('list_bundles sends exactly one dsh/broker frame for service plugins, method list', async (t) => {
112 const host = await startHost({
113 tier: 'builtin',
114 dshBroker: (params) => {
115 assert.equal(params.service, 'plugins')
116 if (params.method === 'posture') return { mode: 'workspace-write' }
117 if (params.method === 'list') return { entries: [{ name: 'demo-bundle', rows: [{ id: 'demo-row', enabled: true }], updatable: true, meta: {} }] }
118 throw new Error(`unexpected method ${params.method}`)
119 },
120 })
121 t.after(() => host.stop())
122
123 await activate(host, 'host:creator', creatorBundle)
124 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
125 const res = await host.call('tool/call', makeCallParams(registered.handle, 'pm-list-1', { action: 'list_bundles' }, { session_id: 's1' }))
126 assert.deepEqual(JSON.parse(res.content[0].text), {
127 entries: [{ name: 'demo-bundle', rows: [{ id: 'demo-row', enabled: true }] }],
128 total: 1,
129 nextOffset: null,
130 })
131 const listCalls = host.brokerCalls.filter((c) => c.service === 'plugins' && c.method === 'list')
132 assert.equal(listCalls.length, 1)
133 assert.deepEqual(listCalls[0].input, {})
134 })
135
136 test('the approval step makes one posture read, asks nobody, and runs before the manager call', async (t) => {
137 const order = []
138 const asks = []
139 const host = await startHost({
140 tier: 'builtin',
141 userQuestionsAsk: (params) => {
142 asks.push(params)
143 return { answers: {} }
144 },
145 dshBroker: (params) => {
146 order.push(`${params.service}:${params.method}`)
147 if (params.method === 'posture') return { mode: 'workspace-write' }
148 if (params.method === 'enable') return { changed: true, application: 'applied' }
149 throw new Error(`unexpected method ${params.method}`)
150 },
151 })
152 t.after(() => host.stop())
153
154 await activate(host, 'host:creator', creatorBundle)
155 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
156 const res = await host.call('tool/call', makeCallParams(registered.handle, 'pm-order-1', { action: 'set_bundle', target: 'b1', enabled: true }, { session_id: 's1' }))
157 assert.equal(JSON.parse(res.content[0].text).changed, true)
158 assert.deepEqual(order, ['plugins:posture', 'plugins:enable'])
159 assert.equal(asks.length, 0)
160 })
161
162 test('a read-only posture surfaces DSH\'s own rejected sentence and the manager is never called', async (t) => {
163 const upstreamEscalation = readFileSync(upstreamEscalationPath, 'utf8')
164 const rejectedMatch = upstreamEscalation.includes('the user rejected escalating this ${subject} to "${mode}"; it stays denied, so stop and explain instead of working around it')
165 assert.ok(rejectedMatch)
166
167 const host = await startHost({
168 tier: 'builtin',
169 dshBroker: (params) => {
170 if (params.method === 'posture') return { mode: 'read-only' }
171 throw new Error(`manager method ${params.method} should never be called`)
172 },
173 })
174 t.after(() => host.stop())
175
176 await activate(host, 'host:creator', creatorBundle)
177 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
178 await assert.rejects(
179 host.call('tool/call', makeCallParams(registered.handle, 'pm-ro-1', { action: 'list_bundles' }, { session_id: 's1' })),
180 (err) => err.message.includes('the user rejected escalating this plugin management operation to "danger-full-access"; it stays denied, so stop and explain instead of working around it'),
181 )
182 assert.deepEqual(host.brokerCalls.map((c) => c.method), ['posture'])
183 })
184
185 test('a broker refusal or error answers unavailable and the manager is never called', async (t) => {
186 let behavior = 'refusal'
187 const host = await startHost({
188 tier: 'builtin',
189 dshBroker: (params) => {
190 if (params.method === 'posture') {
191 if (behavior === 'refusal') return { error: { code: -32002, message: 'ticket refused', data: { dsh_refusal: 'ticket_refused' } } }
192 return { error: { code: -32603, message: 'internal failure' } }
193 }
194 throw new Error(`manager method ${params.method} should never be called`)
195 },
196 })
197 t.after(() => host.stop())
198
199 await activate(host, 'host:creator', creatorBundle)
200 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
201 await assert.rejects(
202 host.call('tool/call', makeCallParams(registered.handle, 'pm-unavail-1', { action: 'list_bundles' }, { session_id: 's1' })),
203 /sandbox escalation to "danger-full-access" requires approval, but no approval channel is available/,
204 )
205 behavior = 'internal'
206 await assert.rejects(
207 host.call('tool/call', makeCallParams(registered.handle, 'pm-unavail-2', { action: 'list_plugins' }, { session_id: 's1' })),
208 /sandbox escalation to "danger-full-access" requires approval, but no approval channel is available/,
209 )
210 assert.deepEqual(host.brokerCalls.map((c) => c.method), ['posture', 'posture'])
211
212 const unitRoot = new HostRoot(fakeRpc(async () => { throw new Error('boom') }), 'builtin')
213 const unitFile = makeTempPlugin(t, `
214 export const inject = ['tools']
215 export function apply(ctx) {
216 ctx.tools.register({
217 name: 'probe_unavail',
218 parameters: { type: 'object', properties: {} },
219 async execute(_args, exec) { return await ctx.get('approval').request({ agent: exec.agent, callId: exec.callId }) },
220 })
221 }
222 `)
223 const ownerRef = makeOwner('host:creator')
224 await unitRoot.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })
225 const handle = unitRoot.owners.get(ownerRef.owner_token).tools.values().next().value.handle
226 const res = await unitRoot.callTool(handle, {}, 'c1', new AbortController().signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [] })
227 assert.equal(res.structured, 'unavailable')
228 })
229
230 test('sandboxPolicy never reports danger-full-access', async (t) => {
231 const root = new HostRoot(fakeRpc(async (params) => {
232 if (params.method === 'posture') return { mode: 'danger-full-access' }
233 return {}
234 }), 'builtin')
235 const unitFile = makeTempPlugin(t, `
236 export const inject = ['tools', 'sandboxPolicy']
237 export function apply(ctx) {
238 ctx.tools.register({
239 name: 'probe_policy',
240 parameters: { type: 'object', properties: {} },
241 async execute(_args, exec) {
242 return {
243 plain: ctx.sandboxPolicy.resolve({}),
244 session: ctx.sandboxPolicy.resolve({ session: exec.agent.session }),
245 spoofed: ctx.sandboxPolicy.resolve({ mode: 'danger-full-access' }),
246 approval: await ctx.get('approval').request({ agent: exec.agent, callId: exec.callId }),
247 }
248 },
249 })
250 }
251 `)
252 const ownerRef = makeOwner('host:creator')
253 assert.equal((await root.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })).status, 'ok')
254 const handle = root.owners.get(ownerRef.owner_token).tools.values().next().value.handle
255 const res = await root.callTool(handle, {}, 'c-pol', new AbortController().signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [{ service: 'plugins', ticket: 't1' }] })
256 assert.deepEqual(res.structured.plain, { mode: 'read-only' })
257 assert.deepEqual(res.structured.session, { mode: 'read-only' })
258 assert.deepEqual(res.structured.spoofed, { mode: 'read-only' })
259 assert.notEqual(res.structured.plain.mode, 'danger-full-access')
260 assert.equal(res.structured.approval, 'allowed-once')
261 })
262
263 test('list_version_exemptions answers the target version with no broker call', async (t) => {
264 const host = await startHost({
265 tier: 'builtin',
266 dshBroker: (params) => {
267 if (params.method === 'posture') return { mode: 'workspace-write' }
268 throw new Error(`unexpected manager broker call ${params.method}`)
269 },
270 })
271 t.after(() => host.stop())
272
273 await activate(host, 'host:creator', creatorBundle)
274 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
275 const exRes = await host.call('tool/call', makeCallParams(registered.handle, 'pm-ex-1', { action: 'list_version_exemptions' }, { session_id: 's1' }))
276 assert.deepEqual(JSON.parse(exRes.content[0].text), {
277 runtimeVersion: '0.2.2-rc.1',
278 exemptions: [],
279 warnings: ['Codewhale does not exempt plugins from the host compatibility contract.'],
280 })
281 assert.deepEqual(host.brokerCalls.map((c) => c.method), ['posture'])
282
283 let brokerCalls = 0
284 const root = new HostRoot(fakeRpc(async () => { brokerCalls++; return {} }), 'builtin')
285 const unitFile = makeTempPlugin(t, `
286 export const inject = ['tools', 'pluginManager']
287 export function apply(ctx) {
288 ctx.tools.register({
289 name: 'probe_ex',
290 parameters: { type: 'object', properties: {} },
291 async execute() { return ctx.pluginManager.listVersionExemptions() },
292 })
293 }
294 `)
295 const ownerRef = makeOwner('host:creator')
296 await root.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })
297 const handle = root.owners.get(ownerRef.owner_token).tools.values().next().value.handle
298 const res = await root.callTool(handle, {}, 'c-ex', new AbortController().signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [] })
299 assert.deepEqual(res.structured, {
300 exemptions: [],
301 warnings: ['Codewhale does not exempt plugins from the host compatibility contract.'],
302 })
303 assert.equal(brokerCalls, 0)
304 })
305
306 test('outside a live invocation every adapter method refuses', async (t) => {
307 const calls = []
308 const root = new HostRoot(fakeRpc(async (params) => { calls.push(params); return { mode: 'workspace-write' } }), 'builtin')
309 let captured
310 const unitFile = makeTempPlugin(t, `
311 export const inject = ['tools', 'pluginManager', 'sandboxPolicy']
312 export function apply(ctx) {
313 globalThis.__cwCreatorCap = ctx
314 ctx.tools.register({
315 name: 'probe_spoof',
316 parameters: { type: 'object', properties: { mode: { type: 'string' } } },
317 async execute(args, exec) {
318 if (args.mode === 'spoof-call') return await ctx.get('approval').request({ agent: exec.agent, callId: 'wrong-call' })
319 if (args.mode === 'spoof-agent') return await ctx.get('approval').request({ agent: { ...exec.agent }, callId: exec.callId })
320 return null
321 },
322 })
323 }
324 `)
325 const ownerRef = makeOwner('host:creator')
326 await root.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })
327 captured = globalThis.__cwCreatorCap
328 delete globalThis.__cwCreatorCap
329
330 const pm = captured.pluginManager
331 const sp = captured.sandboxPolicy
332 const ap = captured.get('approval')
333
334 assert.throws(() => sp.resolve({}), /requires a live tool invocation/)
335 assert.throws(() => pm.listVersionExemptions(), /requires a live tool invocation/)
336 for (const invoke of [
337 () => pm.listBundles(),
338 () => pm.listPlugins(),
339 () => pm.setPluginEnabled('p1', true),
340 () => pm.setBundleEnabled('b1', true),
341 () => pm.installBundle('pkg@1.0.0'),
342 () => pm.removeBundle('pkg'),
343 () => pm.setVersionExemption('pkg@1.0.0', '0.2.2-rc.1', true, true),
344 () => pm.cancelInstall('req-1'),
345 ]) {
346 await assert.rejects(invoke, /requires a live tool invocation/)
347 }
348 assert.equal(await ap.request({ agent: { id: 's1' }, callId: 'c1' }), 'unavailable')
349 assert.equal(calls.length, 0)
350
351 const handle = root.owners.get(ownerRef.owner_token).tools.values().next().value.handle
352 const identity = { session_id: 's1', broker_tickets: [{ service: 'plugins', ticket: 't1' }] }
353 const spoofCall = await root.callTool(handle, { mode: 'spoof-call' }, 'c-s1', new AbortController().signal, '/tmp/ws', undefined, identity)
354 assert.equal(spoofCall.structured, 'unavailable')
355 const spoofAgent = await root.callTool(handle, { mode: 'spoof-agent' }, 'c-s2', new AbortController().signal, '/tmp/ws', undefined, identity)
356 assert.equal(spoofAgent.structured, 'unavailable')
357 assert.equal(calls.length, 0)
358
359 const otherFile = makeTempPlugin(t, `
360 export const inject = ['tools']
361 export function apply(ctx) {
362 ctx.tools.register({
363 name: 'other_probe',
364 parameters: { type: 'object', properties: {} },
365 async execute() {
366 const errors = []
367 for (const fn of [
368 () => ctx.get('sandboxPolicy').resolve({}),
369 () => ctx.get('pluginManager').listVersionExemptions(),
370 ]) {
371 try { fn(); errors.push('unexpected-ok') } catch (err) { errors.push(err.message) }
372 }
373 for (const fn of [
374 () => ctx.get('pluginManager').listBundles(),
375 () => ctx.get('pluginManager').listPlugins(),
376 () => ctx.get('pluginManager').setPluginEnabled('p1', false),
377 () => ctx.get('pluginManager').setBundleEnabled('b1', true),
378 () => ctx.get('pluginManager').installBundle('pkg@1.0.0'),
379 () => ctx.get('pluginManager').removeBundle('pkg'),
380 () => ctx.get('pluginManager').setVersionExemption('pkg@1.0.0', '0.2.2-rc.1', true, true),
381 () => ctx.get('pluginManager').cancelInstall('req-1'),
382 ]) {
383 try { await fn(); errors.push('unexpected-ok') } catch (err) { errors.push(err.message) }
384 }
385 return { errors, approval: await ctx.get('approval').request({}) }
386 },
387 })
388 }
389 `)
390 const otherRef = makeOwner('host:other')
391 await root.activate({ owner: otherRef, plugin_name: 'other', entry: otherFile, config: {} })
392 const otherHandle = root.owners.get(otherRef.owner_token).tools.values().next().value.handle
393 const otherRes = await root.callTool(otherHandle, {}, 'c-other', new AbortController().signal, '/tmp/ws', undefined, identity)
394 assert.equal(otherRes.structured.approval, 'unavailable')
395 assert.equal(otherRes.structured.errors.length, 10)
396 for (const msg of otherRes.structured.errors) assert.match(msg, /creator/i)
397 assert.equal(calls.length, 0)
398 })
399
400 test('an invocation with no agent fails with DSH\'s own sentence and asks and calls nothing', async (t) => {
401 const upstreamEscalation = readFileSync(upstreamEscalationPath, 'utf8')
402 assert.ok(upstreamEscalation.includes('sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through'))
403
404 const asks = []
405 const host = await startHost({
406 tier: 'builtin',
407 userQuestionsAsk: (params) => { asks.push(params); return { answers: {} } },
408 dshBroker: () => { throw new Error('broker should not be called without an agent') },
409 })
410 t.after(() => host.stop())
411
412 await activate(host, 'host:creator', creatorBundle)
413 const registered = host.registry.find((r) => r.op === 'register' && r.spec.name === 'plugin_manager')
414 await assert.rejects(
415 host.call('tool/call', makeCallParams(registered.handle, 'pm-no-agent', { action: 'list_bundles' })),
416 (err) => err.message.includes('sandbox escalation to "danger-full-access" requires approval, but the call has no agent to route it through'),
417 )
418 assert.equal(host.brokerCalls.length, 0)
419 assert.equal(asks.length, 0)
420 })
421
422 test('an aborted call answers cancelled and the manager is never called', async (t) => {
423 const calls = []
424 const root = new HostRoot(fakeRpc(async (params) => { calls.push(params); return { mode: 'workspace-write' } }), 'builtin')
425 let managerCalls = 0
426 const unitFile = makeTempPlugin(t, `
427 export const inject = ['tools', 'pluginManager']
428 export function apply(ctx) {
429 ctx.tools.register({
430 name: 'probe_abort',
431 parameters: { type: 'object', properties: { nonAborted: { type: 'boolean' } } },
432 async execute(args, exec) {
433 const controller = new AbortController()
434 if (!args?.nonAborted) controller.abort()
435 const decision = await ctx.get('approval').request({ agent: exec.agent, callId: exec.callId, signal: controller.signal })
436 if (decision === 'allowed-once') {
437 globalThis.__cwManagerCalled++
438 await ctx.pluginManager.listBundles()
439 }
440 return decision
441 },
442 })
443 }
444 `)
445 globalThis.__cwManagerCalled = 0
446 const ownerRef = makeOwner('host:creator')
447 await root.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })
448 const handle = root.owners.get(ownerRef.owner_token).tools.values().next().value.handle
449 const res = await root.callTool(handle, {}, 'c-abort', new AbortController().signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [{ service: 'plugins', ticket: 't1' }] })
450 assert.equal(res.structured, 'cancelled')
451 assert.equal(globalThis.__cwManagerCalled, 0)
452 assert.equal(calls.length, 0)
453
454 const midFlightAbort = new AbortController()
455 const cancelCalls = []
456 const cancelRoot = new HostRoot(fakeRpc(async (params) => {
457 cancelCalls.push(params.method)
458 midFlightAbort.abort()
459 throw new Error('aborted mid-flight')
460 }), 'builtin')
461 await cancelRoot.activate({ owner: ownerRef, plugin_name: 'creator', entry: unitFile, config: {} })
462 const cancelHandle = cancelRoot.owners.get(ownerRef.owner_token).tools.values().next().value.handle
463 const rpcCancelRes = await cancelRoot.callTool(cancelHandle, { nonAborted: true }, 'c-abort-rpc', midFlightAbort.signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [{ service: 'plugins', ticket: 't1' }] }).catch((err) => ({ aborted: err.message }))
464 if (!rpcCancelRes.aborted) assert.equal(rpcCancelRes.structured, 'cancelled')
465 assert.equal(globalThis.__cwManagerCalled, 0)
466 assert.deepEqual(cancelCalls, ['posture'])
467 delete globalThis.__cwManagerCalled
468
469 const creatorRoot = new HostRoot(fakeRpc(async () => { throw new Error('broker must not be called when already aborted') }), 'builtin')
470 const creatorRef = makeOwner('host:creator')
471 const creatorAct = await creatorRoot.activate({ owner: creatorRef, plugin_name: 'creator', entry: { path: creatorBundle, sha256: sha256File(creatorBundle) }, config: {} })
472 assert.equal(creatorAct.status, 'ok')
473 const pmHandle = creatorRoot.owners.get(creatorRef.owner_token).tools.values().next().value.handle
474 const alreadyAborted = new AbortController()
475 alreadyAborted.abort()
476 await assert.rejects(
477 creatorRoot.callTool(pmHandle, { action: 'list_bundles' }, 'pm-abort-unit', alreadyAborted.signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [{ service: 'plugins', ticket: 't1' }] }),
478 /cancelled/,
479 )
480 assert.equal(calls.length, 0)
481 })
482
483 test('a plugin-tier host refuses a plugin that injects pluginManager, sandboxPolicy or approval, or provides sandboxPolicy or approval', async (t) => {
484 const calls = []
485 const pluginRoot = new HostRoot(fakeRpc(async (params) => { calls.push(params); return {} }), 'plugin')
486
487 for (const service of ['sandboxPolicy', 'approval']) {
488 const file = makeTempPlugin(t, `export const inject = ['${service}']; export function apply() {}`)
489 const res = await pluginRoot.activate({ owner: makeOwner(`bad-inject-${service}`), plugin_name: `bad-${service}`, entry: file, config: {} })
490 assert.equal(res.status, 'failed', service)
491 assert.match(res.diagnostic, new RegExp(`${service}.*belongs to the Codewhale core`))
492 }
493
494 for (const service of ['sandboxPolicy', 'approval', 'pluginManager']) {
495 const file = makeTempPlugin(t, `export function apply(ctx) { ctx.root.provide('${service}', {}) }`)
496 const res = await pluginRoot.activate({ owner: makeOwner(`bad-provide-${service}`), plugin_name: `bad-p-${service}`, entry: file, config: {} })
497 assert.equal(res.status, 'failed', service)
498 assert.match(res.diagnostic, new RegExp(`plugin may not provide core service \`${service}\``))
499 }
500
501 const catalogPlugin = makeTempPlugin(t, `
502 export const inject = ['tools', 'pluginManager']
503 export function apply(ctx) {
504 ctx.tools.register({
505 name: 'catalog_probe',
506 parameters: { type: 'object', properties: {} },
507 async execute() { return await ctx.pluginManager.removeBundle('demo') },
508 })
509 }
510 `)
511 const okOwner = makeOwner('catalog-plugin')
512 const okRes = await pluginRoot.activate({ owner: okOwner, plugin_name: 'catalog-probe', entry: catalogPlugin, config: {} })
513 assert.equal(okRes.status, 'ok')
514 const handle = pluginRoot.owners.get(okOwner.owner_token).tools.values().next().value.handle
515 const out = await pluginRoot.callTool(handle, {}, 'c-cat', new AbortController().signal, '/tmp/ws', undefined, { session_id: 's1', broker_tickets: [] })
516 assert.equal(out.structured.error.code, 'management-required')
517 assert.equal(calls.length, 0)
518 })
519
520 test('a built-in module other than creator that injects pluginManager, sandboxPolicy or approval fails activation', async (t) => {
521 const builtinRoot = new HostRoot(fakeRpc(async () => ({})), 'builtin')
522 for (const service of ['pluginManager', 'sandboxPolicy', 'approval']) {
523 const file = makeTempPlugin(t, `export const inject = ['${service}']; export function apply() {}`)
524 const res = await builtinRoot.activate({ owner: makeOwner(`host:other-${service}`), plugin_name: `other-${service}`, entry: file, config: {} })
525 assert.equal(res.status, 'failed', service)
526 assert.match(res.diagnostic, new RegExp(`${service}.*belongs to the Codewhale core`))
527 }
528 })
529
530 test('the built-in module registers plugin_manager and the cordis inspection tools', async (t) => {
531 const host = await startHost({ tier: 'builtin' })
532 t.after(() => host.stop())
533
534 const { result } = await activate(host, 'host:creator', creatorBundle)
535 assert.equal(result.status, 'ok')
536 assert.deepEqual(result.tools, ['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])
537 assert.deepEqual(result.commands, [])
538 const registrations = host.registry.filter((entry) => entry.op === 'register')
539 assert.equal(registrations.length, 3)
540 assert.deepEqual(registrations.map((r) => r.spec.name).sort(), ['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])
541 })
542
543 test('LICENSES.txt credits dsh-plugin-manager and dsh-sandbox', () => {
544 const notices = readFileSync(licensesPath, 'utf8')
545 assert.match(notices, /@deepseek-ai\/dsh-plugin-manager@0\.2\.2-rc\.1 \(MIT\)/)
546 assert.match(notices, /@deepseek-ai\/dsh-sandbox@0\.2\.2-rc\.1 \(MIT\)/)
547 assert.match(notices, /@deepseek-ai\/dsh-tool-cordis@0\.2\.2-rc\.1 \(MIT\)/)
548 })
549
550 test('cordis tools are DSH\'s own definitions', async (t) => {
551 const host = await startHost({ tier: 'builtin' })
552 t.after(() => host.stop())
553
554 await activate(host, 'host:creator', creatorBundle)
555 const listTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_list')
556 const queryTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_query')
557 assert.ok(listTool)
558 assert.ok(queryTool)
559
560 const toolCordisSource = readFileSync(join(here, '..', 'src', 'dsh', 'upstream', 'creator', 'tool-cordis', 'index.js'), 'utf8')
561 const listMatch = toolCordisSource.match(/name:\s*"cordis_inspect_list",\s*\n\s*description:\s*"([^"]+)"/)
562 assert.ok(listMatch)
563 assert.equal(sha256Text(listTool.spec.description), sha256Text(listMatch[1]))
564
565 const queryMatch = toolCordisSource.match(/name:\s*"cordis_inspect_query",\s*\n\s*description:\s*"([^"]+)"/)
566 assert.ok(queryMatch)
567 assert.equal(sha256Text(queryTool.spec.description), sha256Text(queryMatch[1]))
568
569 assert.deepEqual(listTool.spec.input_schema, { type: 'object', properties: {} })
570 assert.deepEqual(queryTool.spec.input_schema.required, ['platform', 'provider', 'method'])
571 assert.deepEqual(Object.keys(queryTool.spec.input_schema.properties).sort(), ['input', 'method', 'platform', 'provider'])
572 assert.deepEqual(queryTool.spec.input_schema.properties.platform.enum, ['host', 'client'])
573 })
574
575 test('an unknown provider or method fails with DSH\'s wording', async (t) => {
576 const host = await startHost({ tier: 'builtin' })
577 t.after(() => host.stop())
578
579 await activate(host, 'host:creator', creatorBundle)
580 const queryTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_query')
581 assert.ok(queryTool)
582
583 await assert.rejects(
584 host.call('tool/call', makeCallParams(queryTool.handle, 'q-fail-1', { platform: 'host', provider: 'UnknownProvider', method: 'foo' }, { session_id: 's1' })),
585 /Host Cordis inspect provider "UnknownProvider" is not registered/,
586 )
587
588 await assert.rejects(
589 host.call('tool/call', makeCallParams(queryTool.handle, 'q-fail-2', { platform: 'host', provider: 'Service', method: 'unknownMethod' }, { session_id: 's1' })),
590 /Cordis inspect provider "Service" has no method "unknownMethod"/,
591 )
592 })
593
594 test('Config.listConfigs reflects a row added after the first query and drops extra fields', async (t) => {
595 let callCount = 0
596 const host = await startHost({
597 tier: 'builtin',
598 dshBroker: (params) => {
599 if (params.service === 'plugins' && params.method === 'status') {
600 callCount++
601 if (callCount === 1) {
602 return { entries: [] }
603 }
604 return {
605 entries: [
606 {
607 entryId: 'first-entry',
608 moduleName: 'first-plugin',
609 enabled: true,
610 fiberPhase: 'active',
611 diagnostic: 'leaky diagnostic',
612 patchId: 'leaky patch',
613 readOnlyReason: 'leaky reason',
614 },
615 ],
616 }
617 }
618 throw new Error(`unexpected method ${params.method}`)
619 },
620 })
621 t.after(() => host.stop())
622
623 await activate(host, 'host:creator', creatorBundle)
624 const queryTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_query')
625
626 const res1 = await host.call('tool/call', makeCallParams(queryTool.handle, 'q-cfg-1', { platform: 'host', provider: 'Config', method: 'listConfigs', input: { name: 'first-plugin' } }, { session_id: 's1' }))
627 const data1 = JSON.parse(res1.content[0].text)
628 assert.deepEqual(data1.data.entries, [])
629
630 const res2 = await host.call('tool/call', makeCallParams(queryTool.handle, 'q-cfg-2', { platform: 'host', provider: 'Config', method: 'listConfigs', input: { name: 'first-plugin' } }, { session_id: 's1' }))
631 const data2 = JSON.parse(res2.content[0].text)
632 assert.equal(data2.data.entries.length, 1)
633 assert.deepEqual(data2.data.entries[0], {
634 id: 'plugin:first-entry',
635 name: 'first-plugin',
636 kind: 'installed-plugin',
637 status: 'active',
638 })
639 })
640
641 test('Tool provider answers exactly the Rust-supplied caller tools as { name } entries', async (t) => {
642 const host = await startHost({
643 tier: 'builtin',
644 dshBroker: (params) => {
645 if (params.service === 'plugins' && params.method === 'tools') {
646 return { names: ['read_file', 'write_file'] }
647 }
648 throw new Error(`unexpected method ${params.method}`)
649 },
650 })
651 t.after(() => host.stop())
652
653 await activate(host, 'host:creator', creatorBundle)
654 const queryTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_query')
655
656 const res = await host.call('tool/call', makeCallParams(queryTool.handle, 'q-tool-1', { platform: 'host', provider: 'Tool', method: 'listTools' }, { session_id: 's1' }))
657 const data = JSON.parse(res.content[0].text)
658 assert.deepEqual(data.data, {
659 tools: [{ name: 'read_file' }, { name: 'write_file' }],
660 })
661
662 await assert.rejects(
663 host.call('tool/call', makeCallParams(queryTool.handle, 'q-tool-bad', { platform: 'host', provider: 'Tool', method: 'listTools', input: { extra: 'rogue' } }, { session_id: 's1' })),
664 /rejected input/,
665 )
666 })
667
668 test('cordis_inspect_query without an agent gets DSH\'s agent-backed error', async (t) => {
669 const host = await startHost({ tier: 'builtin' })
670 t.after(() => host.stop())
671
672 await activate(host, 'host:creator', creatorBundle)
673 const queryTool = host.registry.find((r) => r.op === 'register' && r.spec.name === 'cordis_inspect_query')
674
675 await assert.rejects(
676 host.call('tool/call', makeCallParams(queryTool.handle, 'q-no-agent', { platform: 'host', provider: 'Service', method: 'listService' }, { session_id: '' })),
677 /Cordis inspection requires an Agent-backed session/,
678 )
679 })
680
680 lines Plain Text