| 1 | import { test, before } from 'node:test' |
| 2 | import assert from 'node:assert/strict' |
| 3 | import { mkdtempSync, rmSync } from 'node:fs' |
| 4 | import { join, dirname } from 'node:path' |
| 5 | import { fileURLToPath, pathToFileURL } from 'node:url' |
| 6 | import { build } from 'esbuild' |
| 7 | |
| 8 | const here = dirname(fileURLToPath(import.meta.url)) |
| 9 | let llmAdapter |
| 10 | let promptOf |
| 11 | |
| 12 | before(async () => { |
| 13 | const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-llm-')) |
| 14 | const outfile = join(dir, 'llm.mjs') |
| 15 | await build({ entryPoints: [join(here, '../src/dsh/llm.ts')], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' }) |
| 16 | ;({ llmAdapter, promptOf } = await import(pathToFileURL(outfile).href)) |
| 17 | process.on('exit', () => rmSync(dir, { recursive: true, force: true })) |
| 18 | }) |
| 19 | |
| 20 | const catalog = { |
| 21 | providers: [{ id: 'session', name: 'Codewhale session route' }], |
| 22 | models: [{ provider: 'session', id: 'm-1', name: 'm-1', context_window: 1000, default_max_output_tokens: 4096, max_output_tokens: 16384 }], |
| 23 | limits: {}, |
| 24 | } |
| 25 | const reported = { coverage: 'reported', input_tokens: 5, output_tokens: 3, cache_read_tokens: null, cache_write_tokens: null, reasoning_tokens: null } |
| 26 | const completion = (usage) => ({ text: 'hello', finish: 'stop', route: { provider: 'p', model: 'm-1' }, usage, receipt: { requests: 1, duration_ms: 2 } }) |
| 27 | |
| 28 | function service(answers) { |
| 29 | const calls = [] |
| 30 | const host = { |
| 31 | tier: 'plugin', |
| 32 | broker: async (ctx, name, method, input) => { |
| 33 | calls.push({ name, method, input }) |
| 34 | const answer = answers[method] |
| 35 | if (answer instanceof Error) throw answer |
| 36 | return answer |
| 37 | }, |
| 38 | } |
| 39 | const instance = Object.create(llmAdapter.define(host).prototype) |
| 40 | instance.ctx = {} |
| 41 | return { llm: instance, calls } |
| 42 | } |
| 43 | |
| 44 | async function drain(stream) { |
| 45 | const chunks = [] |
| 46 | for await (const chunk of stream) chunks.push(chunk) |
| 47 | return chunks |
| 48 | } |
| 49 | |
| 50 | test('a consumer-shaped stream is one typed complete call and ends with usage and a finish', async () => { |
| 51 | const { llm, calls } = service({ complete: completion(reported) }) |
| 52 | const chunks = await drain(llm.stream({ |
| 53 | provider: 'session', model: 'm-1', system: 'be brief', maxTokens: 64, |
| 54 | messages: [{ role: 'user', content: [{ type: 'text', text: 'say ' }, { type: 'text', text: 'hello' }] }], |
| 55 | })) |
| 56 | assert.deepEqual(calls, [{ name: 'llm', method: 'complete', input: { prompt: 'say hello', system: 'be brief', provider: 'session', model: 'm-1', max_output_tokens: 64 } }]) |
| 57 | assert.deepEqual(chunks.map((chunk) => chunk.type), ['block-start', 'text-delta', 'block-end', 'usage', 'finish']) |
| 58 | assert.equal(chunks[1].text, 'hello') |
| 59 | assert.deepEqual(chunks[3].usage, { inputTokens: 5, outputTokens: 3, totalTokens: 8 }) |
| 60 | assert.deepEqual(chunks[4].reason, { kind: 'stop' }) |
| 61 | }) |
| 62 | |
| 63 | test('unreported usage yields no usage chunk, and a refusal or abort is a terminal finish', async () => { |
| 64 | const missing = { ...reported, coverage: 'missing', input_tokens: null, output_tokens: null } |
| 65 | const quiet = await drain(service({ complete: completion(missing) }).llm.stream({ messages: [{ role: 'user', content: 'hi' }] })) |
| 66 | assert.deepEqual(quiet.map((chunk) => chunk.type), ['block-start', 'text-delta', 'block-end', 'finish']) |
| 67 | const refused = await drain(service({ complete: new Error('the model call ran out of time') }).llm.stream({ messages: [{ role: 'user', content: 'hi' }] })) |
| 68 | assert.deepEqual(refused, [{ type: 'finish', reason: { kind: 'error', failure: { message: 'the model call ran out of time', code: 'BROKER_REFUSED' } } }]) |
| 69 | const { llm, calls } = service({ complete: completion(reported) }) |
| 70 | const aborted = await drain(llm.stream({ messages: [{ role: 'user', content: 'hi' }], signal: AbortSignal.abort() })) |
| 71 | assert.equal(aborted[0].reason.kind, 'aborted') |
| 72 | assert.deepEqual(calls, []) |
| 73 | const controller = new AbortController() |
| 74 | const host = { |
| 75 | tier: 'plugin', |
| 76 | broker: async () => { |
| 77 | controller.abort() |
| 78 | throw new Error('withdrawn') |
| 79 | }, |
| 80 | } |
| 81 | const aborting = Object.create(llmAdapter.define(host).prototype) |
| 82 | aborting.ctx = {} |
| 83 | const midFlightAbort = await drain(aborting.stream({ messages: [{ role: 'user', content: 'hi' }], signal: controller.signal })) |
| 84 | assert.deepEqual(midFlightAbort, [{ type: 'finish', reason: { kind: 'aborted', failure: { message: 'the model call was aborted', code: 'ABORTED' } } }]) |
| 85 | }) |
| 86 | |
| 87 | test('tools, non-text content and tool results are refused locally, and a transcript keeps its roles', async () => { |
| 88 | const { llm, calls } = service({ complete: completion(reported) }) |
| 89 | await assert.rejects(drain(llm.stream({ messages: [{ role: 'user', content: 'x' }], tools: [{ name: 't' }] })), /without tools/) |
| 90 | await assert.rejects(drain(llm.stream({ messages: [{ role: 'user', content: 'x' }], tools: { read: {} } })), /without tools/) |
| 91 | await assert.rejects(drain(llm.stream({ messages: [{ role: 'user', content: [{ type: 'image', attachment: {} }] }] })), /text blocks only/) |
| 92 | await assert.rejects(drain(llm.stream({ messages: [{ role: 'tool', content: [] }] })), /tool results/) |
| 93 | await assert.rejects(drain(llm.stream({ messages: [] })), /at least one message/) |
| 94 | await assert.rejects(llm.complete({}), /prompt/) |
| 95 | await assert.rejects(llm.complete({ prompt: 'x', maxTokens: Number.NaN }), /maxTokens/) |
| 96 | await assert.rejects(llm.complete({ prompt: 'x', maxTokens: -1 }), /maxTokens/) |
| 97 | await assert.rejects(llm.complete({ prompt: 'x', timeoutMs: 0 }), /timeoutMs/) |
| 98 | await assert.rejects(llm.complete({ prompt: 'x', timeoutMs: Number.POSITIVE_INFINITY }), /timeoutMs/) |
| 99 | await assert.rejects(llm.complete({ prompt: 'x', provider: 42 }), /provider/) |
| 100 | assert.deepEqual(calls, []) |
| 101 | assert.equal(promptOf([{ role: 'user', content: 'a' }, { role: 'assistant', content: [{ type: 'text', text: 'b' }] }]), 'user: a\n\nassistant: b') |
| 102 | }) |
| 103 | |
| 104 | test('the catalog is read-only and adapter, provider and key registration are named refusals', async () => { |
| 105 | const { llm, calls } = service({ catalog }) |
| 106 | assert.deepEqual(await llm.listModels('session'), [{ provider: 'session', id: 'm-1', name: 'm-1', inputModalities: ['text'], context: { contextWindow: 1000 }, defaultMaxTokens: 4096 }]) |
| 107 | assert.deepEqual(await llm.listModels('openai'), []) |
| 108 | assert.equal((await llm.resolveModelInfo('session', 'm-1')).id, 'm-1') |
| 109 | await assert.rejects(llm.resolveModelInfo('session', 'other'), /only the models in its catalog/) |
| 110 | assert.equal(llm.usage, undefined) |
| 111 | assert.ok(calls.every((call) => call.name === 'llm' && call.method === 'catalog')) |
| 112 | for (const method of ['listProviders', 'registerAdapter', 'registerConfigurableProviders', 'registerModelDiscovery', 'discoverModels', 'prepareCall', 'resolveCallConfig']) { |
| 113 | assert.throws(() => llm[method](), (error) => error.code === -32001 && error.message.includes(`llm.${method} is not available`)) |
| 114 | } |
| 115 | await assert.rejects(service({ catalog: { providers: [] } }).llm.catalog(), /invalid llm broker catalog/) |
| 116 | await assert.rejects(service({ complete: { ...completion(reported), finish: '' } }).llm.complete({ prompt: 'hi' }), /invalid llm broker completion/) |
| 117 | }) |
| 118 |