| 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 { Context } from '@deepseek-ai/cordis' |
| 10 | import { activate, FIXTURES, startHost } from './harness.mjs' |
| 11 | |
| 12 | const here = dirname(fileURLToPath(import.meta.url)) |
| 13 | const PNG_1X1_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' |
| 14 | const PNG_1X1 = Buffer.from(PNG_1X1_B64, 'base64') |
| 15 | const PNG_ID = `sha256:${createHash('sha256').update(PNG_1X1).digest('hex')}` |
| 16 | |
| 17 | let attachmentsAdapter |
| 18 | let AttachmentError |
| 19 | let isAttachmentError |
| 20 | let IMAGE_LIMITS |
| 21 | let ErrorCode |
| 22 | let RpcError |
| 23 | let RpcPeer |
| 24 | let HostRoot |
| 25 | let DSH_ADAPTERS |
| 26 | let dshAttachmentsPlugin |
| 27 | |
| 28 | before(async () => { |
| 29 | const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-attachments-')) |
| 30 | await build({ |
| 31 | entryPoints: { |
| 32 | attachments: join(here, '../src/dsh/attachments.ts'), |
| 33 | protocol: join(here, '../src/protocol.generated.ts'), |
| 34 | rpc: join(here, '../src/rpc.ts'), |
| 35 | root: join(here, '../src/root.ts'), |
| 36 | adapters: join(here, '../src/dsh/adapters.ts'), |
| 37 | }, |
| 38 | outdir: dir, |
| 39 | outExtension: { '.js': '.mjs' }, |
| 40 | splitting: true, |
| 41 | bundle: true, |
| 42 | platform: 'node', |
| 43 | format: 'esm', |
| 44 | packages: 'external', |
| 45 | absWorkingDir: join(here, '..'), |
| 46 | logLevel: 'silent', |
| 47 | }) |
| 48 | ;({ attachmentsAdapter, AttachmentError, isAttachmentError } = await import(pathToFileURL(join(dir, 'attachments.mjs')).href)) |
| 49 | ;({ IMAGE_LIMITS, ErrorCode } = await import(pathToFileURL(join(dir, 'protocol.mjs')).href)) |
| 50 | ;({ RpcError, RpcPeer } = await import(pathToFileURL(join(dir, 'rpc.mjs')).href)) |
| 51 | ;({ HostRoot } = await import(pathToFileURL(join(dir, 'root.mjs')).href)) |
| 52 | ;({ DSH_ADAPTERS } = await import(pathToFileURL(join(dir, 'adapters.mjs')).href)) |
| 53 | dshAttachmentsPlugin = await import(pathToFileURL(join(FIXTURES, 'dsh-attachments', 'index.mjs')).href) |
| 54 | process.on('exit', () => rmSync(dir, { recursive: true, force: true })) |
| 55 | }) |
| 56 | |
| 57 | function brokerHost(answers = {}) { |
| 58 | const calls = [] |
| 59 | return { |
| 60 | calls, |
| 61 | host: { |
| 62 | tier: 'plugin', |
| 63 | broker: async (_ctx, service, method, input, signal) => { |
| 64 | calls.push({ service, method, input, signal }) |
| 65 | const answer = answers[method] |
| 66 | if (answer instanceof Error) throw answer |
| 67 | return typeof answer === 'function' ? answer(input) : answer |
| 68 | }, |
| 69 | }, |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | function makeService(answers) { |
| 74 | const { host, calls } = brokerHost(answers) |
| 75 | const Attachments = attachmentsAdapter.define(host) |
| 76 | const service = Object.create(Attachments.prototype) |
| 77 | service.ctx = {} |
| 78 | return { service, calls, host } |
| 79 | } |
| 80 | |
| 81 | test('imageLimits mirrors generated IMAGE_LIMITS and is frozen', () => { |
| 82 | const { service } = makeService() |
| 83 | assert.deepEqual(service.imageLimits, IMAGE_LIMITS) |
| 84 | assert.equal(Object.isFrozen(service.imageLimits), true) |
| 85 | assert.equal(Object.isFrozen(service.imageLimits.mediaTypes), true) |
| 86 | assert.equal(service.imageHostPath({ attachmentId: PNG_ID }), undefined) |
| 87 | }) |
| 88 | |
| 89 | test('validateImage, saveImage, readImage, and readImageRequest match the broker contract', async () => { |
| 90 | const variantId = `sha256:${'b'.repeat(64)}` |
| 91 | const savedRef = { |
| 92 | attachment_id: PNG_ID, |
| 93 | media_type: 'image/png', |
| 94 | bytes: PNG_1X1.byteLength, |
| 95 | width: 1, |
| 96 | height: 1, |
| 97 | } |
| 98 | const { service, calls } = makeService({ |
| 99 | validate: { ok: true, media_type: 'image/png', bytes: PNG_1X1.byteLength, width: 1, height: 1 }, |
| 100 | save: { attachment: savedRef }, |
| 101 | read: { data_base64: PNG_1X1_B64, attachment: savedRef }, |
| 102 | read_request: { variant_id: variantId, data_base64: PNG_1X1_B64, media_type: 'image/png' }, |
| 103 | }) |
| 104 | |
| 105 | const validated = await service.validateImage({ data: PNG_1X1, mediaType: 'image/png', name: 'sample.png' }) |
| 106 | assert.deepEqual(validated, { ok: true, mediaType: 'image/png', bytes: PNG_1X1.byteLength, width: 1, height: 1 }) |
| 107 | await service.validateImage({ data: PNG_1X1, mediaType: 'image/png' }) |
| 108 | assert.equal('name' in calls[1].input, false) |
| 109 | |
| 110 | const saved = await service.saveImage({ data: PNG_1X1, mediaType: 'image/png', name: 'studio.png' }) |
| 111 | assert.deepEqual(saved, { |
| 112 | attachmentId: PNG_ID, |
| 113 | mediaType: 'image/png', |
| 114 | bytes: PNG_1X1.byteLength, |
| 115 | width: 1, |
| 116 | height: 1, |
| 117 | }) |
| 118 | |
| 119 | const read = await service.readImage({ attachmentId: PNG_ID, mediaType: 'image/png' }) |
| 120 | assert.equal(read.data instanceof Uint8Array, true) |
| 121 | assert.deepEqual(Buffer.from(read.data), PNG_1X1) |
| 122 | assert.deepEqual(read.ref, saved) |
| 123 | |
| 124 | const variant = await service.readImageRequest(saved, { width: 320, height: 320, maxBytes: 98304 }) |
| 125 | assert.equal(variant.variantId, variantId) |
| 126 | assert.equal(variant.mediaType, 'image/png') |
| 127 | assert.deepEqual(Buffer.from(variant.data), PNG_1X1) |
| 128 | |
| 129 | assert.deepEqual(calls.map((c) => [c.service, c.method]), [ |
| 130 | ['attachments', 'validate'], |
| 131 | ['attachments', 'validate'], |
| 132 | ['attachments', 'save'], |
| 133 | ['attachments', 'read'], |
| 134 | ['attachments', 'read_request'], |
| 135 | ]) |
| 136 | assert.equal(calls[0].input.data_base64, PNG_1X1_B64) |
| 137 | assert.deepEqual(calls[4].input, { |
| 138 | attachment: savedRef, |
| 139 | width: 320, |
| 140 | height: 320, |
| 141 | max_bytes: 98304, |
| 142 | }) |
| 143 | }) |
| 144 | |
| 145 | test('AttachmentError preserves upstream codes and local validation rejects bad inputs before RPC', async () => { |
| 146 | const { service, calls } = makeService({ |
| 147 | save: () => { throw new RpcError(ErrorCode.Refused, '[TOO_MANY_IMAGES] this Codewhale keeps one image per tool result') }, |
| 148 | read: () => { throw new RpcError(ErrorCode.Refused, '[ATTACHMENT_NOT_FOUND] attachment not found') }, |
| 149 | validate: () => { throw new RpcError(ErrorCode.Denied, 'attachments access denied') }, |
| 150 | }) |
| 151 | |
| 152 | await assert.rejects( |
| 153 | service.saveImage({ data: PNG_1X1, mediaType: 'image/png' }), |
| 154 | (err) => isAttachmentError(err) && err instanceof AttachmentError && err.code === 'TOO_MANY_IMAGES', |
| 155 | ) |
| 156 | await assert.rejects( |
| 157 | service.readImage({ attachmentId: PNG_ID }), |
| 158 | (err) => isAttachmentError(err) && err.code === 'ATTACHMENT_NOT_FOUND', |
| 159 | ) |
| 160 | await assert.rejects( |
| 161 | service.validateImage({ data: PNG_1X1, mediaType: 'image/png' }), |
| 162 | (err) => err instanceof RpcError && err.code === ErrorCode.Denied && !isAttachmentError(err), |
| 163 | ) |
| 164 | |
| 165 | const beforeLocal = calls.length |
| 166 | await assert.rejects( |
| 167 | service.validateImage({ data: PNG_1X1, mediaType: 'image/svg+xml' }), |
| 168 | (err) => isAttachmentError(err) && err.code === 'UNSUPPORTED_IMAGE_TYPE', |
| 169 | ) |
| 170 | await assert.rejects( |
| 171 | service.saveImage({ data: new Uint8Array(0), mediaType: 'image/png' }), |
| 172 | (err) => isAttachmentError(err) && err.code === 'INVALID_IMAGE', |
| 173 | ) |
| 174 | await assert.rejects( |
| 175 | service.saveImage({ data: new Uint8Array(IMAGE_LIMITS.maxImageBytes + 1), mediaType: 'image/png' }), |
| 176 | (err) => isAttachmentError(err) && err.code === 'IMAGE_TOO_LARGE', |
| 177 | ) |
| 178 | await assert.rejects( |
| 179 | service.readImage({ attachmentId: 'bad-id' }), |
| 180 | (err) => isAttachmentError(err) && err.code === 'INVALID_ATTACHMENT_REF', |
| 181 | ) |
| 182 | await assert.rejects( |
| 183 | service.saveImage({ data: PNG_1X1, mediaType: 'image/png', name: '../escape.png' }), |
| 184 | (err) => err instanceof RpcError && err.code === ErrorCode.InvalidParams, |
| 185 | ) |
| 186 | await assert.rejects( |
| 187 | service.readImage({ attachmentId: PNG_ID, hostPath: '/etc/passwd' }), |
| 188 | (err) => err instanceof RpcError && err.code === ErrorCode.InvalidParams, |
| 189 | ) |
| 190 | await assert.rejects( |
| 191 | service.readImageRequest({ attachmentId: PNG_ID }, { width: IMAGE_LIMITS.maxImageDimension + 1 }), |
| 192 | (err) => isAttachmentError(err) && err.code === 'IMAGE_DIMENSION_TOO_LARGE', |
| 193 | ) |
| 194 | await assert.rejects( |
| 195 | service.readImageRequest({ attachmentId: PNG_ID }, { maxBytes: IMAGE_LIMITS.maxImageBytes + 1 }), |
| 196 | (err) => isAttachmentError(err) && err.code === 'IMAGE_TOO_LARGE', |
| 197 | ) |
| 198 | assert.equal(calls.length, beforeLocal, 'locally invalid requests must never call the broker') |
| 199 | }) |
| 200 | |
| 201 | test('AbortSignal aborts before or during a broker call and generic file methods fail NotAvailable', async () => { |
| 202 | let releasePending |
| 203 | const { service, calls } = makeService({ |
| 204 | read: () => new Promise((resolve) => { releasePending = resolve }), |
| 205 | }) |
| 206 | |
| 207 | const alreadyAborted = new AbortController() |
| 208 | alreadyAborted.abort() |
| 209 | await assert.rejects( |
| 210 | service.readImage({ attachmentId: PNG_ID }, alreadyAborted.signal), |
| 211 | (err) => isAttachmentError(err) && err.code === 'CANCELLED', |
| 212 | ) |
| 213 | assert.throws( |
| 214 | () => service.imageHostPath({ attachmentId: PNG_ID }, alreadyAborted.signal), |
| 215 | (err) => isAttachmentError(err) && err.code === 'CANCELLED', |
| 216 | ) |
| 217 | assert.equal(calls.length, 0) |
| 218 | |
| 219 | const inFlight = new AbortController() |
| 220 | const pending = service.readImage({ attachmentId: PNG_ID }, inFlight.signal) |
| 221 | assert.equal(calls.length, 1) |
| 222 | assert.equal(calls[0].signal, inFlight.signal) |
| 223 | assert.equal(calls[0].signal.aborted, false) |
| 224 | inFlight.abort() |
| 225 | assert.equal(calls[0].signal.aborted, true) |
| 226 | await assert.rejects(pending, (err) => isAttachmentError(err) && err.code === 'CANCELLED') |
| 227 | releasePending?.({ data_base64: PNG_1X1_B64, attachment: { attachment_id: PNG_ID, media_type: 'image/png', bytes: PNG_1X1.byteLength, width: 1, height: 1 } }) |
| 228 | |
| 229 | for (const method of ['saveFile', 'admitEncodedFile', 'saveFileStream', 'readFileStream', 'readFile', 'fileHostPath']) { |
| 230 | assert.throws(() => service[method](), (err) => err instanceof RpcError && err.code === ErrorCode.NotAvailable, method) |
| 231 | } |
| 232 | }) |
| 233 | |
| 234 | test('consumer-shaped fixture executes against attachmentsAdapter inside Cordis and renders image attachment blocks', async (t) => { |
| 235 | const savedRef = { |
| 236 | attachment_id: PNG_ID, |
| 237 | media_type: 'image/png', |
| 238 | bytes: PNG_1X1.byteLength, |
| 239 | width: 1, |
| 240 | height: 1, |
| 241 | } |
| 242 | const variantId = `sha256:${'c'.repeat(64)}` |
| 243 | const { host, calls } = brokerHost({ |
| 244 | read: { data_base64: PNG_1X1_B64, attachment: savedRef }, |
| 245 | validate: { ok: true, media_type: 'image/png', bytes: PNG_1X1.byteLength, width: 1, height: 1 }, |
| 246 | save: { attachment: savedRef }, |
| 247 | read_request: { variant_id: variantId, data_base64: PNG_1X1_B64, media_type: 'image/png' }, |
| 248 | }) |
| 249 | |
| 250 | const ctx = new Context() |
| 251 | const tools = new Map() |
| 252 | ctx.provide('tools', { register(spec) { tools.set(spec.name, spec) } }) |
| 253 | const adapterFiber = ctx.plugin(attachmentsAdapter.define(host)) |
| 254 | await adapterFiber.await() |
| 255 | const pluginFiber = ctx.plugin(dshAttachmentsPlugin) |
| 256 | await pluginFiber.await() |
| 257 | t.after(async () => { |
| 258 | await pluginFiber.dispose() |
| 259 | await adapterFiber.dispose() |
| 260 | }) |
| 261 | |
| 262 | const tool = tools.get('attachments_roundtrip') |
| 263 | assert.ok(tool) |
| 264 | const controller = new AbortController() |
| 265 | const input = { |
| 266 | sourceRef: { attachmentId: PNG_ID, mediaType: 'image/png' }, |
| 267 | saveBase64: PNG_1X1_B64, |
| 268 | mediaType: 'image/png', |
| 269 | imageName: 'studio.png', |
| 270 | } |
| 271 | const value = await tool.execute(input, { signal: controller.signal }) |
| 272 | const rendered = tool.output.render(input, value) |
| 273 | assert.deepEqual(rendered, [ |
| 274 | { type: 'text', text: `read=${PNG_1X1.byteLength} saved=${PNG_ID} thumb=${PNG_1X1.byteLength}` }, |
| 275 | { type: 'image', attachment: value.attachment }, |
| 276 | ]) |
| 277 | assert.deepEqual(calls.map((c) => c.method), ['read', 'validate', 'save', 'read_request']) |
| 278 | }) |
| 279 | |
| 280 | test('real host activates dsh-attachments and projects renderResult image blocks', async (t) => { |
| 281 | const host = await startHost() |
| 282 | t.after(() => host.stop()) |
| 283 | |
| 284 | const activated = await activate(host, 'dsh-attachments') |
| 285 | assert.equal(activated.result.status, 'ok', activated.result.diagnostic) |
| 286 | |
| 287 | const renderActivated = await activate(host, 'dsh-attachments-render') |
| 288 | assert.equal(renderActivated.result.status, 'ok', renderActivated.result.diagnostic) |
| 289 | const reg = host.registry.find((entry) => entry.op === 'register' && entry.spec.name === 'render_attachment_result') |
| 290 | assert.ok(reg) |
| 291 | |
| 292 | const out = await host.call('tool/call', { |
| 293 | handle: reg.handle, |
| 294 | call_id: 'render-1', |
| 295 | input: { attachmentId: PNG_ID }, |
| 296 | deadline_ms: 5000, |
| 297 | }) |
| 298 | assert.equal(out.is_error, false) |
| 299 | assert.deepEqual(out.structured, { attachmentId: PNG_ID }) |
| 300 | assert.deepEqual(out.content, [ |
| 301 | { type: 'text', text: `image ${PNG_ID}` }, |
| 302 | { type: 'image_ref', attachment_id: PNG_ID }, |
| 303 | ]) |
| 304 | }) |
| 305 | |
| 306 | test('HostRoot adapterHost.broker forwards per-call AbortSignal into rpc.request and sends $/cancel', async (t) => { |
| 307 | const sent = [] |
| 308 | let peer |
| 309 | let handleSeq = 1 |
| 310 | const brokerSeen = new Promise((resolve) => { |
| 311 | peer = new RpcPeer((message) => { |
| 312 | sent.push(message) |
| 313 | if (message.method === 'registry/register') { |
| 314 | const handle = handleSeq++ |
| 315 | queueMicrotask(() => peer.handle({ jsonrpc: '2.0', id: message.id, result: { handle } })) |
| 316 | } else if (message.method === 'registry/unregister') { |
| 317 | queueMicrotask(() => peer.handle({ jsonrpc: '2.0', id: message.id, result: {} })) |
| 318 | } else if (message.method === 'dsh/broker') { |
| 319 | resolve(message) |
| 320 | } |
| 321 | }, 'plugin') |
| 322 | }) |
| 323 | |
| 324 | const callAbort = new AbortController() |
| 325 | const baseRemote = DSH_ADAPTERS.find((adapter) => adapter.service === 'remote') |
| 326 | let capturedHost |
| 327 | const cancelProbeRemote = { |
| 328 | service: 'remote', |
| 329 | define(adapterHost) { |
| 330 | capturedHost = adapterHost |
| 331 | const BaseRemote = baseRemote.define(adapterHost) |
| 332 | return class extends BaseRemote { |
| 333 | statusWithSignal(signal) { |
| 334 | return adapterHost.broker(this.ctx, 'remote', 'status', {}, signal) |
| 335 | } |
| 336 | } |
| 337 | }, |
| 338 | } |
| 339 | const root = new HostRoot( |
| 340 | peer, |
| 341 | 'plugin', |
| 342 | [...DSH_ADAPTERS.filter((adapter) => adapter.service !== 'remote'), cancelProbeRemote], |
| 343 | ) |
| 344 | |
| 345 | const dir = mkdtempSync(join(tmpdir(), 'cw-broker-abort-')) |
| 346 | t.after(() => rmSync(dir, { recursive: true, force: true })) |
| 347 | const entry = join(dir, 'index.mjs') |
| 348 | writeFileSync( |
| 349 | entry, |
| 350 | [ |
| 351 | "export const name = 'abort-probe'", |
| 352 | "export const inject = ['tools', 'remote']", |
| 353 | 'export function apply(ctx) {', |
| 354 | ' ctx.tools.register({', |
| 355 | " name: 'probe_broker_abort',", |
| 356 | " parameters: { type: 'object' },", |
| 357 | ' async execute(_input) {', |
| 358 | ' await ctx.remote.statusWithSignal(globalThis.__cwTestPerCallAbort.signal)', |
| 359 | " return 'done'", |
| 360 | ' },', |
| 361 | ' })', |
| 362 | '}', |
| 363 | ].join('\n'), |
| 364 | ) |
| 365 | globalThis.__cwTestPerCallAbort = callAbort |
| 366 | t.after(() => { delete globalThis.__cwTestPerCallAbort }) |
| 367 | |
| 368 | const owner = { plugin_id: 'abort-probe', generation: 1, owner_token: 'tok-abort-probe' } |
| 369 | const activated = await root.activate({ |
| 370 | owner, |
| 371 | plugin_name: 'abort-probe', |
| 372 | entry: { kind: 'native', path: entry, sha256: createHash('sha256').update(readFileSync(entry)).digest('hex') }, |
| 373 | config: {}, |
| 374 | }) |
| 375 | assert.equal(activated.status, 'ok', activated.diagnostic) |
| 376 | const regMsg = sent.find((m) => m.method === 'registry/register') |
| 377 | assert.ok(regMsg) |
| 378 | const registeredHandle = 1 |
| 379 | |
| 380 | const invocationAbort = new AbortController() |
| 381 | const toolPromise = root.callTool( |
| 382 | registeredHandle, |
| 383 | {}, |
| 384 | 'call-abort-1', |
| 385 | invocationAbort.signal, |
| 386 | dir, |
| 387 | 'core-tkt', |
| 388 | { session_id: 'sess-abort', broker_tickets: [{ service: 'remote', ticket: 'remote-tkt' }] }, |
| 389 | ) |
| 390 | const brokerReq = await brokerSeen |
| 391 | assert.equal(brokerReq.params.service, 'remote') |
| 392 | assert.equal(brokerReq.params.method, 'status') |
| 393 | |
| 394 | callAbort.abort() |
| 395 | await assert.rejects(toolPromise, (err) => err instanceof RpcError && err.code === ErrorCode.Cancelled) |
| 396 | const cancelMsg = sent.find((m) => m.method === '$/cancel') |
| 397 | assert.deepEqual(cancelMsg, { jsonrpc: '2.0', method: '$/cancel', params: { id: brokerReq.id } }) |
| 398 | assert.equal(invocationAbort.signal.aborted, false) |
| 399 | |
| 400 | await assert.rejects( |
| 401 | capturedHost.broker({}, 'remote', 'status', {}, 'not-a-signal'), |
| 402 | (err) => err instanceof RpcError && err.code === ErrorCode.InvalidParams, |
| 403 | ) |
| 404 | await root.deactivateAll(1000) |
| 405 | }) |
| 406 |