返回 CodeWhale
catalog.test.mjs
根目录 / crates / engine / extension-host / test / catalog.test.mjs
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 catalog
10
11 before(async () => {
12 const dir = mkdtempSync(join(here, '..', 'node_modules', '.cw-catalog-'))
13 const outfile = join(dir, 'catalog.mjs')
14 await build({ entryPoints: [join(here, '../src/dsh/catalog.ts')], outfile, bundle: true, platform: 'node', format: 'esm', packages: 'external', absWorkingDir: join(here, '..'), logLevel: 'silent' })
15 catalog = await import(pathToFileURL(outfile).href)
16 process.on('exit', () => rmSync(dir, { recursive: true, force: true }))
17 })
18
19 function brokerHost(answers) {
20 const calls = []
21 return {
22 calls,
23 host: {
24 tier: 'plugin',
25 broker: async (ctx, service, method, input) => {
26 calls.push({ service, method, input })
27 const answer = typeof answers[method] === 'function' ? answers[method](input) : answers[method]
28 if (answer instanceof Error) throw answer
29 return answer
30 },
31 },
32 }
33 }
34
35 function serviceOf(adapter, host) {
36 const service = Object.create(adapter.define(host).prototype)
37 service.ctx = {}
38 return service
39 }
40
41 const brokerRefusal = (code, refusal, message) => Object.assign(new Error(message), { code, data: { dsh_refusal: refusal, service: 'catalog' } })
42
43 test('a balance widget reads an absent account, an unknown balance and a known balance, and never a key', async () => {
44 const answers = { balance: { status: 'absent' } }
45 const { host, calls } = brokerHost(answers)
46 const account = serviceOf(catalog.deepseekAccountAdapter, host)
47 const client = { version: '0.4.2', locale: 'zh_CN', timezoneOffsetSeconds: 28800 }
48
49 assert.equal(await account.getBalance(client), null)
50 answers.balance = { status: 'unknown' }
51 assert.deepEqual(await account.getBalance(client), { status: 'failed' })
52 answers.balance = { status: 'known', currency: 'CNY', total: '123.45', topped_up: '100.00', granted: '23.45' }
53 const ready = await account.getBalance(client)
54 assert.deepEqual(ready, { status: 'ready', value: [{ currency: 'CNY', balance: '100.00' }], bonusWallets: [{ currency: 'CNY', balance: '23.45' }] })
55 const shown = [...ready.value, ...ready.bonusWallets].reduce((sum, wallet) => sum + Number(wallet.balance), 0)
56 assert.equal(shown.toFixed(2), '123.45')
57 answers.balance = { status: 'known', currency: 'USD', total: '12.50', topped_up: '', granted: '' }
58 assert.deepEqual(await account.getBalance(client), { status: 'ready', value: [{ currency: 'USD', balance: '12.50' }], bonusWallets: [] })
59
60 assert.deepEqual(calls.map((call) => [call.service, call.method, call.input]), Array(4).fill(['catalog', 'balance', {}]))
61 for (const method of ['resolveToken', 'getPlatformSession', 'getState', 'startSignIn', 'signOut', 'rejectToken']) {
62 assert.throws(() => account[method]('https://api.deepseek.com'), (error) => error.code === -32001 && error.message.includes(`deepseekAccount.${method} is not provided`))
63 }
64 assert.equal(calls.length, 4)
65
66 answers.balance = { status: 'known', currency: 'CNY', total: '1', topped_up: '1', granted: '0', api_key: 'sk-raw' }
67 assert.deepEqual(Object.keys(await catalog.accountBalance(host, {})).sort(), ['currency', 'granted', 'status', 'topped_up', 'total'])
68 answers.balance = { status: 'ready', value: [] }
69 await assert.rejects(account.getBalance(client), /invalid catalog broker balance/)
70 answers.balance = brokerRefusal(-32001, 'not_available', 'the catalog broker is not available yet')
71 await assert.rejects(account.getBalance(client), /not available yet/)
72 })
73
74 test('a market plugin asking to install gets the reviewed-install answer, and nothing installs or removes', async () => {
75 const review = {
76 status: 'review_required', package: '@acme/review', version: '1.10.0', plugin: 'review', spec: 'npm:@acme/review@1.10.0',
77 command: '/plugin install npm:@acme/review@1.10.0',
78 message: 'Codewhale installs a plugin only through its reviewed install flow; nothing was installed. Review and install @acme/review@1.10.0 with `/plugin install npm:@acme/review@1.10.0`.',
79 }
80 const answers = { 'install.plan': review }
81 const { host, calls } = brokerHost(answers)
82 const manager = serviceOf(catalog.pluginManagerAdapter, host)
83
84 const requested = await manager.installBundle('@acme/review@1.10.0', { requestId: 'r1', registry: 'https://registry.example.com' })
85 assert.deepEqual(requested, {
86 changed: false, application: 'failed', stage: 'install', target: '@acme/review@1.10.0',
87 error: { code: 'management-required', diagnostic: review.message, message: review.message },
88 })
89 assert.deepEqual(calls[0], { service: 'catalog', method: 'install.plan', input: { package: '@acme/review', version: '1.10.0', registry: 'https://registry.example.com' } })
90 await manager.installBundle('dsh-demo@1.2.3')
91 assert.deepEqual(calls[1].input, { package: 'dsh-demo', version: '1.2.3' })
92
93 answers['install.plan'] = { status: 'already_present', package: 'dsh-demo', version: '1.2.3', plugin: 'dsh-demo', command: '/plugin trust dsh-demo', message: 'A plugin named `dsh-demo` is already present; nothing was installed.' }
94 assert.equal((await manager.installBundle('dsh-demo@1.2.3')).error.code, 'already-installed')
95
96 answers['install.plan'] = brokerRefusal(-32002, 'refused', '`dsh-demo@^1.2.3` is not an exact npm package version Codewhale can fetch')
97 const range = await manager.installBundle('dsh-demo@^1.2.3')
98 assert.equal(range.error.code, 'invalid-spec')
99 assert.match(range.error.diagnostic, /not an exact npm package version/)
100
101 const sent = calls.length
102 for (const spec of ['dsh-demo', '@acme/review', 'git+https://github.com/acme/review.git#0123456789abcdef0123456789abcdef01234567', 'dsh-demo@', 7]) {
103 const refused = await manager.installBundle(spec)
104 assert.equal(refused.error.code, 'invalid-spec', String(spec))
105 assert.equal(refused.application, 'failed')
106 }
107 assert.equal((await manager.installBundle('dsh-demo@1.2.3', { registry: 7 })).error.code, 'invalid-spec')
108 assert.deepEqual(await manager.removeBundle('dsh-demo'), {
109 changed: false, application: 'failed', stage: 'remove', target: 'dsh-demo',
110 error: { code: 'management-required', diagnostic: 'Codewhale removes a plugin only from its own plugin manager, after you disable it: /plugin uninstall', message: 'Codewhale removes a plugin only from its own plugin manager, after you disable it: /plugin uninstall' },
111 })
112 assert.deepEqual(await manager.cancelInstall('r1'), { status: 'not-running' })
113 assert.equal(calls.length, sent, 'a spec that is not name@exact-version, a removal and a cancel never reach the broker')
114
115 answers['install.plan'] = brokerRefusal(-32002, 'ticket_refused', 'the invocation this dsh/broker:catalog belongs to has ended')
116 await assert.rejects(manager.installBundle('dsh-demo@1.2.3'), /has ended/)
117 answers['install.plan'] = { status: 'installed', package: 'dsh-demo', version: '1.2.3', plugin: 'dsh-demo', command: 'x', message: 'x' }
118 await assert.rejects(manager.installBundle('dsh-demo@1.2.3'), /invalid catalog broker install plan/)
119 })
120
121 test('a model-proxy directory is built from approved provider routes, and an unapproved route is the refusal', async () => {
122 const gateway = { provider: 'gateway', base_url: 'https://gateway.example/api', default_model: 'tiny-model', models: ['tiny-model', 'large-model'] }
123 const answers = {
124 'routes.list': { routes: [gateway] },
125 'routes.resolve': (input) => input.provider === 'gateway'
126 ? { route: gateway, model: input.model ?? gateway.default_model }
127 : brokerRefusal(-32002, 'refused', `\`${input.provider}\` is not a provider route approved for this plugin`),
128 }
129 const { host, calls } = brokerHost(answers)
130
131 const routes = await catalog.approvedRoutes(host, {})
132 const directory = {
133 providers: routes.map((route) => ({ provider: route.provider, active: true })),
134 models: routes.map((route) => ({ provider: route.provider, models: route.models.map((id) => ({ id })) })),
135 }
136 assert.deepEqual(directory, {
137 providers: [{ provider: 'gateway', active: true }],
138 models: [{ provider: 'gateway', models: [{ id: 'tiny-model' }, { id: 'large-model' }] }],
139 })
140
141 assert.deepEqual(await catalog.resolveRoute(host, {}, 'gateway', 'large-model'), { ...gateway, model: 'large-model' })
142 assert.deepEqual(await catalog.resolveRoute(host, {}, 'gateway'), { ...gateway, model: 'tiny-model' })
143 await assert.rejects(catalog.resolveRoute(host, {}, 'openai', 'gpt-x'), /not a provider route approved for this plugin/)
144 assert.deepEqual(calls.map((call) => [call.service, call.method, call.input]), [
145 ['catalog', 'routes.list', {}],
146 ['catalog', 'routes.resolve', { provider: 'gateway', model: 'large-model' }],
147 ['catalog', 'routes.resolve', { provider: 'gateway' }],
148 ['catalog', 'routes.resolve', { provider: 'openai', model: 'gpt-x' }],
149 ])
150
151 await assert.rejects(catalog.resolveRoute(host, {}, '', 'x'), (error) => error.code === -32602)
152 await assert.rejects(catalog.resolveRoute(host, {}, 'gateway', 7), (error) => error.code === -32602)
153 assert.equal(calls.length, 4)
154 answers['routes.list'] = { routes: [{ provider: 'gateway', base_url: 'https://gateway.example/api', default_model: null, models: [7] }] }
155 await assert.rejects(catalog.approvedRoutes(host, {}), /invalid catalog broker route/)
156 answers['routes.list'] = [gateway]
157 await assert.rejects(catalog.approvedRoutes(host, {}), /invalid catalog broker routes/)
158 })
159
159 lines Plain Text