dsh-codearts-dock 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +172 -2
  4. package/SECURITY.md +47 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3519 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +25 -0
  9. package/docs/DETAIL.zh.md +25 -0
  10. package/docs/PUBLISHING.md +43 -0
  11. package/docs/preview.svg +78 -0
  12. package/icons/dsh-connect-codearts-128.png +0 -0
  13. package/icons/dsh-connect-codearts-256.png +0 -0
  14. package/locale/en.json +7 -0
  15. package/locale/zh.json +7 -0
  16. package/package.json +88 -4
  17. package/scripts/build-market-index.mjs +24 -0
  18. package/scripts/check-legal.sh +33 -0
  19. package/scripts/check-release.mjs +29 -0
  20. package/scripts/test.mjs +11 -0
  21. package/src/account.js +217 -0
  22. package/src/accounts.js +481 -0
  23. package/src/adapter.js +742 -0
  24. package/src/backup.js +89 -0
  25. package/src/catalog.js +269 -0
  26. package/src/checkin.js +271 -0
  27. package/src/credentials.js +435 -0
  28. package/src/features.js +79 -0
  29. package/src/gateway.js +521 -0
  30. package/src/health.js +18 -0
  31. package/src/index.js +1108 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +90 -0
  35. package/src/protocol/crypto.js +160 -0
  36. package/src/protocol/sign.js +176 -0
  37. package/src/protocol/sm4.js +264 -0
  38. package/src/protocol/sse.js +134 -0
  39. package/src/sts.js +118 -0
  40. package/src/usage.js +55 -0
  41. package/test/accounts.test.mjs +322 -0
  42. package/test/adapter.test.mjs +234 -0
  43. package/test/assembler.test.mjs +86 -0
  44. package/test/features.test.mjs +257 -0
  45. package/test/live-probe.mjs +55 -0
  46. package/test/protocol.test.mjs +167 -0
  47. package/test/registration.test.mjs +301 -0
  48. package/test/sm4.test.mjs +64 -0
  49. package/test/ui.test.mjs +370 -0
  50. package/test/visual.test.mjs +438 -0
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Offline tests for the account store and the daily check-in guard.
3
+ *
4
+ * Both are file-backed, so every case runs against a scratch directory: these
5
+ * must never touch the real account file.
6
+ */
7
+
8
+ import assert from 'node:assert/strict'
9
+ import { mkdtempSync, rmSync, existsSync, readFileSync, statSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+
13
+ const results = []
14
+ const check = async (name, fn) => {
15
+ try {
16
+ await fn()
17
+ results.push(`✓ ${name}`)
18
+ } catch (error) {
19
+ results.push(`✗ ${name}\n ${error.message}`)
20
+ process.exitCode = 1
21
+ }
22
+ }
23
+
24
+ // Each module reads its directory at import time, so point it at a scratch home
25
+ // before importing.
26
+ const scratch = mkdtempSync(join(tmpdir(), 'dca-accounts-'))
27
+ process.env.APPDATA = scratch
28
+ process.env.XDG_CONFIG_HOME = scratch
29
+ // The store falls back to the legacy single-pair file when the configured one
30
+ // is absent. Without redirecting it too, these tests would read the developer's
31
+ // real credential and every isolation assertion would be meaningless.
32
+ process.env.DSH_CONNECT_CODEARTS_LEGACY_CREDENTIAL = join(scratch, 'legacy-credentials.json')
33
+
34
+ // Import paths FIRST so its module-level constants are evaluated against the
35
+ // scratch home. Importing it through another module would evaluate it before
36
+ // the environment was redirected, and the tests would then run against the real
37
+ // config directory.
38
+ const { CONFIG_DIR } = await import('../src/paths.js')
39
+ const accounts = await import('../src/accounts.js')
40
+ const checkin = await import('../src/checkin.js')
41
+
42
+ assert.ok(CONFIG_DIR.startsWith(scratch), `config dir escaped the scratch home: ${CONFIG_DIR}`)
43
+
44
+ await check('an empty store has no accounts and no active id', () => {
45
+ const store = accounts.readStore()
46
+ assert.equal(store.accounts.length, 0)
47
+ assert.equal(store.activeId, null)
48
+ })
49
+
50
+ await check('a v1 bare pair is migrated into one account', () => {
51
+ const store = accounts.normaliseStore({ ak: 'AKV1PAIR0000000001', sk: 'skv1' })
52
+ assert.equal(store.version, 2)
53
+ assert.equal(store.accounts.length, 1)
54
+ assert.equal(store.accounts[0].ak, 'AKV1PAIR0000000001')
55
+ assert.equal(store.activeId, store.accounts[0].id)
56
+ })
57
+
58
+ await check('the first account added becomes active, later ones do not steal it', async () => {
59
+ const first = await accounts.addAccount({ ak: 'AKONE0000000000001', sk: 'sk1', label: 'one' })
60
+ assert.equal(first.added, true)
61
+ assert.equal(accounts.readStore().activeId, first.account.id)
62
+
63
+ await accounts.addAccount({ ak: 'AKTWO0000000000002', sk: 'sk2', label: 'two' })
64
+ assert.equal(accounts.readStore().activeId, first.account.id, 'adding must not switch')
65
+ assert.equal(accounts.readStore().accounts.length, 2)
66
+ })
67
+
68
+ await check('re-adding the same AK updates in place instead of duplicating', async () => {
69
+ const before = accounts.readStore().accounts.length
70
+ const result = await accounts.addAccount({ ak: 'AKONE0000000000001', sk: 'sk1-rotated' })
71
+ assert.equal(result.added, false)
72
+ assert.equal(accounts.readStore().accounts.length, before)
73
+ const updated = accounts.readStore().accounts.find((a) => a.ak === 'AKONE0000000000001')
74
+ assert.equal(updated.sk, 'sk1-rotated')
75
+ })
76
+
77
+ await check('switching the active account persists', async () => {
78
+ const second = accounts.readStore().accounts.find((a) => a.ak === 'AKTWO0000000000002')
79
+ await accounts.setActiveAccount(second.id)
80
+ assert.equal(accounts.activeAccount()?.id, second.id)
81
+ })
82
+
83
+ await check('removing the active account promotes what is left', async () => {
84
+ const active = accounts.activeAccount()
85
+ await accounts.removeAccount(active.id)
86
+ const store = accounts.readStore()
87
+ assert.equal(store.accounts.some((a) => a.id === active.id), false)
88
+ assert.notEqual(store.activeId, null)
89
+ assert.ok(store.accounts.some((a) => a.id === store.activeId))
90
+ })
91
+
92
+ await check('the public view carries no secret', async () => {
93
+ const store = accounts.readStore()
94
+ const views = store.accounts.map((a) => accounts.publicAccount(a, store))
95
+ const text = JSON.stringify(views)
96
+ for (const account of store.accounts) {
97
+ assert.equal(text.includes(account.sk), false, 'a secret leaked into the public view')
98
+ }
99
+ assert.ok(views[0].akMasked.includes('…'))
100
+ })
101
+
102
+ await check('the store file is written owner-only', () => {
103
+ const mode = statSync(join(CONFIG_DIR, 'credentials.json')).mode & 0o777
104
+ assert.equal(mode, 0o600, `expected 0600, got ${mode.toString(8)}`)
105
+ })
106
+
107
+ // ── import parsing ─────────────────────────────────────────────────────────
108
+
109
+ await check('a Huawei credentials.csv is parsed by header name', () => {
110
+ const text = 'User Name,Access Key Id,Secret Access Key\nhw001,AKCSV1,skCSV1\nhw002,AKCSV2,skCSV2'
111
+ const { accounts: parsed } = accounts.parseImport(text)
112
+ assert.equal(parsed.length, 2)
113
+ assert.equal(parsed[0].ak, 'AKCSV1')
114
+ assert.equal(parsed[0].sk, 'skCSV1')
115
+ // The user-name column becomes the label, which is friendlier than an AK.
116
+ assert.equal(parsed[0].label, 'hw001')
117
+ })
118
+
119
+ await check('AK,SK lines parse, including a trailing label', () => {
120
+ const { accounts: parsed } = accounts.parseImport('AKLINE1,skLine1\nAKLINE2,skLine2,工作')
121
+ assert.equal(parsed.length, 2)
122
+ assert.equal(parsed[1].label, '工作')
123
+ })
124
+
125
+ await check('tab-separated and JSON payloads parse', () => {
126
+ assert.equal(accounts.parseImport('AKTAB\tskTab').accounts.length, 1)
127
+ const doc = JSON.stringify({ version: 2, activeId: null, accounts: [{ ak: 'AKJSON', sk: 'skJson' }] })
128
+ assert.equal(accounts.parseImport(doc).accounts.length, 1)
129
+ })
130
+
131
+ await check('unusable lines are counted, not silently dropped', () => {
132
+ const { accounts: parsed, skipped } = accounts.parseImport('AKOK,skOk\nnot-a-pair\n\n')
133
+ assert.equal(parsed.length, 1)
134
+ assert.equal(skipped, 1)
135
+ })
136
+
137
+ await check('an export round-trips back through the importer', async () => {
138
+ const text = accounts.exportStore(accounts.readStore())
139
+ const parsed = accounts.parseImport(text)
140
+ assert.equal(parsed.accounts.length, accounts.readStore().accounts.length)
141
+ })
142
+
143
+ // ── check-in ───────────────────────────────────────────────────────────────
144
+
145
+ /** A gateway stub whose daily campaign flips to claimed after the first claim. */
146
+ function fakeGateway() {
147
+ const state = { claimable: true, claims: 0, items: null }
148
+ const client = {
149
+ getJson: async () => ({
150
+ data: {
151
+ items: [
152
+ // A second login campaign runs at the same time: the daily one must
153
+ // still be the one chosen.
154
+ { campaignId: 40, title: 'Skill创新赛每日签到礼', claimable: true, pendingTotalAmount: 1000, benefitUnit: 'CREDIT', status: 'ELIGIBLE' },
155
+ {
156
+ campaignId: 34,
157
+ title: '每日签到领100积分',
158
+ claimable: state.claimable,
159
+ pendingTotalAmount: state.claimable ? 100 : 0,
160
+ benefitUnit: 'CREDIT',
161
+ status: state.claimable ? 'ELIGIBLE' : 'CONSUMED',
162
+ },
163
+ ],
164
+ },
165
+ }),
166
+ postJson: async () => {
167
+ state.claims += 1
168
+ state.claimable = false
169
+ return { ok: true }
170
+ },
171
+ }
172
+ return { client, state }
173
+ }
174
+
175
+ await check('the daily campaign is picked out of a list with other campaigns', () => {
176
+ const items = [{ campaignId: 40, title: 'other' }, { campaignId: 34, title: '每日签到领100积分' }]
177
+ assert.equal(checkin.dailyCampaignOf(items).campaignId, 34)
178
+ // With no id 34, the title hint still finds it.
179
+ assert.equal(checkin.dailyCampaignOf([{ campaignId: 99, title: '每日签到礼' }]).campaignId, 99)
180
+ })
181
+
182
+ await check('a claim is made once and never repeated the same day', async () => {
183
+ const { client, state } = fakeGateway()
184
+ const day = new Date('2026-11-18T10:00:00+08:00')
185
+ const id = 'acct-daily'
186
+
187
+ const first = await checkin.claimDaily(client, { accountId: id, now: day })
188
+ assert.equal(first.claimed, true)
189
+ assert.equal(first.amount, 100)
190
+ assert.equal(state.claims, 1, 'must claim exactly once')
191
+
192
+ const second = await checkin.claimDaily(client, { accountId: id, now: day })
193
+ assert.equal(second.claimed, false)
194
+ assert.equal(state.claims, 1, 'a same-day retry must not reach upstream')
195
+ })
196
+
197
+ await check('the day record is per account, not global', async () => {
198
+ const { client, state } = fakeGateway()
199
+ const day = new Date('2026-11-18T10:00:00+08:00')
200
+ const a = await checkin.claimDaily(client, { accountId: 'acct-a', now: day })
201
+ assert.equal(a.claimed, true)
202
+ // A different account on the same day is a different entitlement.
203
+ state.claimable = true
204
+ const b = await checkin.claimDaily(client, { accountId: 'acct-b', now: day })
205
+ assert.equal(b.claimed, true)
206
+ assert.equal(state.claims, 2)
207
+ })
208
+
209
+ await check('a new day allows a new claim', async () => {
210
+ const { client, state } = fakeGateway()
211
+ const first = await checkin.claimDaily(client, { accountId: 'acct-day', now: new Date('2026-11-18T10:00:00+08:00') })
212
+ assert.equal(first.claimed, true)
213
+ state.claimable = true
214
+ const next = await checkin.claimDaily(client, { accountId: 'acct-day', now: new Date('2026-11-19T10:00:00+08:00') })
215
+ assert.equal(next.claimed, true)
216
+ })
217
+
218
+ await check('an already-claimed campaign is not sent to the write endpoint', async () => {
219
+ const { client, state } = fakeGateway()
220
+ state.claimable = false
221
+ const result = await checkin.claimDaily(client, { accountId: 'acct-consumed', now: new Date('2026-11-18T10:00:00+08:00') })
222
+ assert.equal(result.claimed, false)
223
+ assert.equal(state.claims, 0, 'the write endpoint must not be called')
224
+ })
225
+
226
+ await check('a missing campaign is reported, not claimed blindly', async () => {
227
+ const client = { getJson: async () => ({ data: { items: [] } }), postJson: async () => { throw new Error('must not be called') } }
228
+ const result = await checkin.claimDaily(client, { accountId: 'acct-none', now: new Date('2026-11-18T10:00:00+08:00') })
229
+ assert.equal(result.claimed, false)
230
+ assert.match(result.reason, /没有每日签到活动/)
231
+ })
232
+
233
+ await check('the today summary counts only claimed accounts', async () => {
234
+ // `acct-daily` was claimed above on this FIXED day. Asking about the real
235
+ // "today" made this pass on 2026-11-18 and fail on 2026-11-19 — a test that
236
+ // only holds on the day it was written. Pin the day instead.
237
+ const day = new Date('2026-11-18T10:00:00+08:00')
238
+ const summary = checkin.todaySummary([
239
+ { id: 'acct-daily', label: 'a' },
240
+ { id: 'acct-never', label: 'b' },
241
+ ], day)
242
+ assert.equal(summary.total, 2)
243
+ assert.equal(summary.done, 1)
244
+ assert.equal(summary.pending, 1)
245
+ })
246
+
247
+ await check('the day key follows the local calendar, not UTC', () => {
248
+ // 23:30 in +08:00 is still the 18th locally even though UTC has rolled over.
249
+ assert.equal(checkin.todayKey(new Date('2026-11-18T23:30:00+08:00')), '2026-11-18')
250
+ assert.equal(checkin.todayKey(new Date('2026-11-19T00:30:00+08:00')), '2026-11-19')
251
+ })
252
+
253
+ // Clean up the scratch home.
254
+ rmSync(scratch, { recursive: true, force: true })
255
+ assert.equal(existsSync(scratch), false)
256
+
257
+ // ── borrowing the CodeArts client's sign-in ───────────────────────────────
258
+ {
259
+ const { mkdtempSync, mkdirSync, writeFileSync } = await import('node:fs')
260
+ const { tmpdir } = await import('node:os')
261
+ const { join } = await import('node:path')
262
+
263
+ /**
264
+ * Build a stand-in state.vscdb: SQLite noise with the sign-in blob embedded,
265
+ * which is what the real file looks like to a string reader.
266
+ */
267
+ const writeStateDb = (home, blob) => {
268
+ const dir = join(home, '.config', 'codearts-agent', 'User', 'globalStorage')
269
+ mkdirSync(dir, { recursive: true })
270
+ writeFileSync(join(dir, 'state.vscdb'), blob)
271
+ }
272
+
273
+ const blobWith = (expiresAt) =>
274
+ 'SQLite format 3\u0000' +
275
+ 'x'.repeat(300) +
276
+ '{"id":"huawei-cloud-authentication","originData":{"accessKey":"AKBORROW1",' +
277
+ '"secretKey":"skBorrow","securityToken":"tokBorrow","expiresAt":"' +
278
+ expiresAt +
279
+ '","account":{"label":"borrowed"}}}' +
280
+ '\u0000'.repeat(200) +
281
+ 'junk { not json }'
282
+
283
+ // `readCodeArtsSignIn` resolves candidates through `homedir()`, which caches
284
+ // the first HOME it sees, so point HOME at a scratch dir before importing.
285
+ const scratchHome = mkdtempSync(join(tmpdir(), 'dca-vscdb-'))
286
+ const savedHome = process.env.HOME
287
+ process.env.HOME = scratchHome
288
+
289
+ writeStateDb(scratchHome, blobWith(new Date(Date.now() + 6 * 60 * 60 * 1000).toISOString()))
290
+ const { readCodeArtsSignIn } = await import('../src/credentials.js')
291
+ const borrowed = readCodeArtsSignIn()
292
+
293
+ await check('a live sign-in blob is borrowed from the client state database', () => {
294
+ assert.ok(borrowed !== null, 'the credential should be found')
295
+ assert.equal(borrowed.key.ak, 'AKBORROW1')
296
+ assert.equal(borrowed.key.sk, 'skBorrow')
297
+ assert.equal(borrowed.key.securityToken, 'tokBorrow')
298
+ assert.equal(borrowed.key.account, 'borrowed')
299
+ assert.ok(borrowed.where.endsWith('state.vscdb'), 'reports the file it came from')
300
+ })
301
+
302
+ // A token about to die must NOT be adopted: it would fail the first request,
303
+ // and the next source down might still work.
304
+ await check('a nearly expired sign-in blob is skipped, not adopted', () => {
305
+ writeStateDb(scratchHome, blobWith(new Date(Date.now() + 60 * 1000).toISOString()))
306
+ assert.equal(readCodeArtsSignIn(), null)
307
+ })
308
+
309
+ // The anchor is what makes reading a binary file safe: without it there is no
310
+ // credential, even when the field names appear elsewhere in the file.
311
+ await check('a database without the sign-in anchor yields nothing', () => {
312
+ writeStateDb(scratchHome, 'SQLite\u0000{"accessKey":"x","secretKey":"y","securityToken":"z"}')
313
+ assert.equal(readCodeArtsSignIn(), null)
314
+ })
315
+
316
+ if (savedHome === undefined) delete process.env.HOME
317
+ else process.env.HOME = savedHome
318
+ }
319
+
320
+ console.log(results.join('\n'))
321
+ if (process.exitCode) console.log('\naccounts: some checks failed')
322
+ else console.log('\naccounts: all checks passed')
@@ -0,0 +1,234 @@
1
+ // Adapter-level checks against a fake gateway client: no network involved.
2
+ import assert from 'node:assert/strict';
3
+ import { createCodeArtsAdapter, PROVIDER_ID } from '../src/adapter.js';
4
+ import { Catalog } from '../src/catalog.js';
5
+
6
+ function fakeCatalog(models) {
7
+ const c = new Catalog();
8
+ c.current = models; c.source = 'gateway';
9
+ return c;
10
+ }
11
+
12
+ const models = [
13
+ { id:'m1', name:'Model One', context:100000, maxOutput:8192, ratio:'0.1x', supportsImages:true, strengths:[] },
14
+ { id:'m2', name:'Model Two', context:200000, maxOutput:8192, ratio:'0.2x', supportsImages:false, strengths:['high','max'], defaultStrength:'high' },
15
+ ];
16
+
17
+ // Build an adapter whose gateway client is a stub, so no request leaves the
18
+ // process while the real stream() logic runs.
19
+ function adapterWith(chunks, credential = { key:{ ak:'AK', sk:'SK', securityToken:'TOKEN' } }) {
20
+ const sent = [];
21
+ const adapter = createCodeArtsAdapter({
22
+ credentials: { resolve: async () => credential },
23
+ catalog: fakeCatalog(models),
24
+ createClient: () => ({
25
+ heartbeat: async () => true,
26
+ streamChat: async function* (req) { sent.push(req); yield* chunks; },
27
+ }),
28
+ });
29
+ return { adapter, sent };
30
+ }
31
+
32
+ // The adapter caches clients behind #client; drive stream with a stubbed one.
33
+ async function collect(adapter, options) {
34
+ const out = [];
35
+ for await (const chunk of adapter.stream(options)) out.push(chunk);
36
+ return out;
37
+ }
38
+
39
+ const results = [];
40
+ const check = async (name, fn) => {
41
+ try { await fn(); results.push(`✓ ${name}`); }
42
+ catch (e) { results.push(`✗ ${name}\n ${e.message}`); process.exitCode=1; }
43
+ };
44
+
45
+ await check('providerInfo names the route', async () => {
46
+ const { adapter } = adapterWith([]);
47
+ const info = adapter.providerInfo(PROVIDER_ID);
48
+ assert.equal(info.id, PROVIDER_ID);
49
+ assert.ok(info.name.length > 0);
50
+ });
51
+
52
+ await check('listModels renders the credit ratio into the name', async () => {
53
+ const { adapter } = adapterWith([]);
54
+ const list = await adapter.listModels(PROVIDER_ID);
55
+ assert.equal(list.length, 2);
56
+ assert.equal(list[0].name, 'Model One · 0.1x');
57
+ assert.deepEqual(list[0].inputModalities, ['text','image']);
58
+ assert.deepEqual(list[1].inputModalities, ['text']);
59
+ });
60
+
61
+ await check('resolveModel declares context, output cap, and reasoning', async () => {
62
+ const { adapter } = adapterWith([]);
63
+ const model = await adapter.resolveModel(PROVIDER_ID, 'm2');
64
+ assert.equal(model.context.contextWindow, 200000);
65
+ assert.equal(model.defaultMaxTokens, 8192);
66
+ assert.ok(model.reasoning, 'm2 declares thinking levels');
67
+ assert.equal(model.reasoning.defaultEffort, 'high');
68
+ const ids = model.reasoning.efforts.map(e => e.id);
69
+ assert.deepEqual(ids, ['off','high','max']);
70
+ });
71
+
72
+ await check('a model with no levels declares no reasoning', async () => {
73
+ const { adapter } = adapterWith([]);
74
+ const model = await adapter.resolveModel(PROVIDER_ID, 'm1');
75
+ assert.equal(model.reasoning, undefined);
76
+ });
77
+
78
+ await check('text and reasoning deltas emit block lifecycle and a stop finish', async () => {
79
+ const { adapter } = adapterWith([
80
+ { reasoning:'think' },
81
+ { text:'Hello' },
82
+ { text:' world' },
83
+ { usage:{ inputTokens:10, outputTokens:2, totalTokens:12 } },
84
+ { finish:'stop' },
85
+ ]);
86
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[{role:'user',content:[{type:'text',text:'hi'}]}] });
87
+ const kinds = out.filter(c => c.type!=='block-end').map(c => c.type);
88
+ assert.deepEqual(kinds, ['block-start','reasoning-delta','block-start','text-delta','text-delta','usage','finish']);
89
+ const text = out.filter(c=>c.type==='text-delta').map(c=>c.text).join('');
90
+ assert.equal(text, 'Hello world');
91
+ const finish = out.at(-1);
92
+ assert.equal(finish.reason.kind, 'stop');
93
+ });
94
+
95
+ await check('tool-call deltas accumulate into one block and finish as tool-calls', async () => {
96
+ const { adapter } = adapterWith([
97
+ { toolCalls:[{ index:0, id:'call_1', function:{ name:'get_weather', arguments:'' } }] },
98
+ { toolCalls:[{ index:0, function:{ arguments:'{"city":"BJ"}' } }] },
99
+ { finish:'tool_calls' },
100
+ ]);
101
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[{role:'user',content:[{type:'text',text:'weather'}]}] });
102
+ const starts = out.filter(c=>c.type==='block-start');
103
+ assert.equal(starts.length, 1);
104
+ assert.equal(starts[0].blockType, 'tool-call');
105
+ const deltas = out.filter(c=>c.type==='tool-call-delta');
106
+ assert.equal(deltas.length, 2);
107
+ assert.equal(deltas[0].id, 'call_1');
108
+ assert.equal(deltas[0].name, 'get_weather');
109
+ assert.equal(deltas[1].argumentsDelta, '{"city":"BJ"}');
110
+ assert.equal(out.at(-1).reason.kind, 'tool-calls');
111
+ });
112
+
113
+ await check('developer messages become system, and tool results become tool messages', async () => {
114
+ const { adapter, sent } = adapterWith([{ text:'ok' }, { finish:'stop' }]);
115
+ await collect(adapter, {
116
+ provider: PROVIDER_ID, model:'m1',
117
+ messages: [
118
+ { role:'developer', content:[{type:'text',text:'be brief'}] },
119
+ { role:'user', content:[{type:'text',text:'hi'}] },
120
+ { role:'assistant', content:[
121
+ {type:'text',text:'calling'},
122
+ {type:'tool-call', id:'c1', name:'f', arguments:'{}'} ] },
123
+ { role:'tool', toolCallId:'c1', content:[{type:'text',text:'result'}] },
124
+ ],
125
+ });
126
+ const msgs = sent[0].messages;
127
+ assert.equal(msgs[0].role, 'system');
128
+ assert.equal(msgs[0].content, 'be brief');
129
+ assert.equal(msgs[1].role, 'user');
130
+ assert.equal(msgs[2].role, 'assistant');
131
+ assert.equal(msgs[2].tool_calls[0].id, 'c1');
132
+ assert.equal(msgs[3].role, 'tool');
133
+ assert.equal(msgs[3].tool_call_id, 'c1');
134
+ assert.equal(msgs[3].content, 'result');
135
+ });
136
+
137
+ await check('system prompt is sent as the leading system message', async () => {
138
+ const { adapter, sent } = adapterWith([{ finish:'stop' }]);
139
+ await collect(adapter, { provider: PROVIDER_ID, model:'m1', system:'SYS', messages:[] });
140
+ assert.equal(sent[0].messages[0].role, 'system');
141
+ assert.equal(sent[0].messages[0].content, 'SYS');
142
+ });
143
+
144
+ await check('a gateway failure becomes an error finish, not a throw', async () => {
145
+ const a = createCodeArtsAdapter({
146
+ credentials: { resolve: async () => ({ key:{ ak:'A', sk:'S', securityToken:'T' } }) },
147
+ catalog: fakeCatalog(models),
148
+ createClient: () => ({
149
+ heartbeat: async () => true,
150
+ streamChat: async function* () { throw new Error('upstream exploded'); },
151
+ }),
152
+ });
153
+ const out = await collect(a, { provider: PROVIDER_ID, model:'m1', messages:[] });
154
+ const finish = out.at(-1);
155
+ assert.equal(finish.reason.kind, 'error');
156
+ assert.match(finish.reason.failure.message, /exploded/);
157
+ });
158
+
159
+ await check('max-tokens maps through', async () => {
160
+ const { adapter } = adapterWith([{ finish:'length' }]);
161
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[] });
162
+ assert.equal(out.at(-1).reason.kind, 'max-tokens');
163
+ });
164
+
165
+ await check('usage arriving after finish is still reported, in stream order', async () => {
166
+ // The gateway sends finish BEFORE usage and then [DONE]. Returning on
167
+ // finish would silently drop the token counts.
168
+ const { adapter } = adapterWith([
169
+ { text:'hi' },
170
+ { finish:'length' },
171
+ { usage:{ inputTokens:17, outputTokens:600, totalTokens:617 } },
172
+ { done:true },
173
+ ]);
174
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[] });
175
+ const types = out.map(c=>c.type);
176
+ assert.ok(types.indexOf('usage') >= 0, 'usage must be emitted');
177
+ assert.equal(types.at(-1), 'finish', 'finish is last');
178
+ const usage = out.find(c=>c.type==='usage');
179
+ assert.equal(usage.usage.inputTokens, 17);
180
+ assert.equal(usage.usage.outputTokens, 600);
181
+ assert.equal(out.at(-1).reason.kind, 'max-tokens');
182
+ });
183
+
184
+ await check('exactly one finish chunk is emitted', async () => {
185
+ const { adapter } = adapterWith([{ text:'x' }, { finish:'stop' }, { done:true }]);
186
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[] });
187
+ assert.equal(out.filter(c=>c.type==='finish').length, 1);
188
+ });
189
+
190
+ await check('a done frame without a finish reason still settles as stop', async () => {
191
+ const { adapter } = adapterWith([{ text:'x' }, { done:true }]);
192
+ const out = await collect(adapter, { provider: PROVIDER_ID, model:'m1', messages:[] });
193
+ assert.equal(out.at(-1).type, 'finish');
194
+ assert.equal(out.at(-1).reason.kind, 'stop');
195
+ });
196
+
197
+ await check('a display name is resolved to the gateway model id', async () => {
198
+ // The gateway answers `GLM-5.2 · 0.7x` with HTTP 200 and an empty body, so a
199
+ // display string must never reach the wire.
200
+ const { catalogModels } = globalThis.__dcaTest ?? {};
201
+ const cat = new Catalog();
202
+ cat.current = [{ id:'GLM-5.2', name:'GLM-5.2', context:1, maxOutput:1, ratio:'0.7x', supportsImages:false, strengths:[] }];
203
+ cat.source = 'gateway';
204
+ assert.equal(cat.resolveId('GLM-5.2'), 'GLM-5.2');
205
+ assert.equal(cat.resolveId('GLM-5.2 · 0.7x'), 'GLM-5.2');
206
+ assert.equal(cat.resolveId('glm-5.2'), 'GLM-5.2');
207
+ assert.equal(cat.resolveId(' GLM-5.2 '), 'GLM-5.2');
208
+ // An unknown value passes through unchanged rather than vanishing.
209
+ assert.equal(cat.resolveId('not-a-model'), 'not-a-model');
210
+ });
211
+
212
+ await check('a reasoning-only reply explains itself instead of coming back empty', async () => {
213
+ const { adapter } = adapterWith([
214
+ { reasoning: '想了很久但没有正文' },
215
+ { finish: 'stop' },
216
+ { done: true },
217
+ ]);
218
+ const out = await collect(adapter, { provider: PROVIDER_ID, model: 'm1', messages: [], maxTokens: 60 });
219
+ const text = out.filter((c) => c.type === 'text-delta').map((c) => c.text).join('');
220
+ assert.ok(text.length > 0, 'a note must be emitted');
221
+ assert.match(text, /max_tokens/);
222
+ assert.equal(out.at(-1).reason.kind, 'stop');
223
+ });
224
+
225
+ await check('a normal reply is left alone by the reasoning-only guard', async () => {
226
+ const { adapter } = adapterWith([{ text: '正常回复' }, { finish: 'stop' }, { done: true }]);
227
+ const out = await collect(adapter, { provider: PROVIDER_ID, model: 'm1', messages: [] });
228
+ const text = out.filter((c) => c.type === 'text-delta').map((c) => c.text).join('');
229
+ assert.equal(text, '正常回复');
230
+ });
231
+
232
+ console.log(results.join('\n'));
233
+ if (process.exitCode) console.log('\nadapter: some checks failed');
234
+ else console.log('\nadapter: all checks passed');
@@ -0,0 +1,86 @@
1
+ // Feed the adapter's chunks through the Host's REAL BlockAssembler to prove
2
+ // the emitted block content survives.
3
+ // Needs the Host's own package, so it only runs inside a DSH shell.
4
+ const base = process.env.DSH_INSTALL_DIR;
5
+ if (!base) { console.log('DSH_INSTALL_DIR unset; skipping assembler integration test'); process.exit(0); }
6
+ const { createRequire } = await import('node:module');
7
+ const req = createRequire(base + '/package.json');
8
+ let mod;
9
+ try { mod = await import(req.resolve('@deepseek-ai/dsh-llm')); }
10
+ catch (e) {
11
+ // Outside a DSH shell this integration check cannot resolve the Host
12
+ // package; skip rather than fail, and say so once.
13
+ console.log(`assembler: skipped (${e.code}) — run inside a DSH shell`);
14
+ process.exit(0);
15
+ }
16
+ const { BlockAssembler } = mod;
17
+ if (!BlockAssembler) { console.log('BlockAssembler not exported; exports:', Object.keys(mod).slice(0,40).join(',')); process.exit(0); }
18
+
19
+ // Relative to this file, so the test runs from any checkout location.
20
+ const { createCodeArtsAdapter } = await import(new URL('../src/adapter.js', import.meta.url).href);
21
+ const chunks = [
22
+ { reasoning:'让我想想' },
23
+ { text:'你好' },
24
+ { text:',世界' },
25
+ { toolCalls:[{index:0, id:'call_1', function:{name:'get_weather', arguments:''}}] },
26
+ { toolCalls:[{index:0, function:{arguments:'{"city":"BJ"}'}}] },
27
+ { finish:'tool_calls' },
28
+ { usage:{inputTokens:5,outputTokens:9,totalTokens:14} },
29
+ { done:true },
30
+ ];
31
+ const adapter = createCodeArtsAdapter({
32
+ credentials:{ resolve: async()=>({ key:{ak:'A',sk:'S',securityToken:'T'} }) },
33
+ catalog:{ models:()=>[], find:()=>undefined },
34
+ createClient: ()=>({ heartbeat: async()=>true, streamChat: async function*(req){ yield* chunks } }),
35
+ });
36
+ const asm = new BlockAssembler();
37
+ for await (const c of adapter.stream({ provider:'codearts', model:'m', messages:[] })) asm.push(c);
38
+ const blocks = asm.blocks();
39
+ console.log('blocks:', JSON.stringify(blocks, null, 1));
40
+ const text = blocks.filter(b=>b.type==='text').map(b=>b.text).join('');
41
+ const reasoning = blocks.filter(b=>b.type==='reasoning').map(b=>b.text).join('');
42
+ const call = blocks.find(b=>b.type==='tool-call');
43
+ console.log('---');
44
+ console.log('text preserved :', JSON.stringify(text), text==='你好,世界' ? 'OK':'MISMATCH');
45
+ console.log('reasoning kept :', JSON.stringify(reasoning), reasoning==='让我想想' ? 'OK':'MISMATCH');
46
+ console.log('tool name/args :', call ? `${call.name} ${call.arguments}` : 'MISSING',
47
+ call && call.name==='get_weather' && call.arguments==='{"city":"BJ"}' ? 'OK':'MISMATCH');
48
+ console.log('usage:', JSON.stringify(asm.usage));
49
+ console.log('finish:', JSON.stringify(asm.finish));
50
+
51
+ // Fail the run when any assertion above regressed, so `npm test` catches it.
52
+ const failures = [];
53
+ if (text !== '你好,世界') failures.push('text');
54
+ if (reasoning !== '让我想想') failures.push('reasoning');
55
+ if (!call || call.name !== 'get_weather') failures.push('tool-call');
56
+ if (asm.finish?.kind !== 'tool-calls') failures.push('finish');
57
+ if (failures.length) { console.log('assembler: FAILED —', failures.join(', ')); process.exit(1); }
58
+ // A stream with NO tool call closes its text block through the settle path,
59
+ // which is a different code path from the tool-call one above. Both must echo
60
+ // their content: the assembler replaces the block with whatever `block-end`
61
+ // carries.
62
+ {
63
+ const plainChunks = [
64
+ { reasoning: '先想' },
65
+ { text: '只有文字' },
66
+ { text: ',没有工具调用' },
67
+ { finish: 'stop' },
68
+ { usage: { inputTokens: 3, outputTokens: 7, totalTokens: 10 } },
69
+ { done: true },
70
+ ];
71
+ const plainAdapter = createCodeArtsAdapter({
72
+ credentials: { resolve: async () => ({ key: { ak: 'A', sk: 'S', securityToken: 'T' } }) },
73
+ catalog: { models: () => [], find: () => undefined, resolveId: (id) => id },
74
+ createClient: () => ({ heartbeat: async () => true, streamChat: async function* () { yield* plainChunks } }),
75
+ });
76
+ const plainAsm = new BlockAssembler();
77
+ for await (const c of plainAdapter.stream({ provider: 'codearts', model: 'm', messages: [] })) plainAsm.push(c);
78
+ const plainText = plainAsm.blocks().filter((b) => b.type === 'text').map((b) => b.text).join('');
79
+ const plainReasoning = plainAsm.blocks().filter((b) => b.type === 'reasoning').map((b) => b.text).join('');
80
+ console.log('settle path text :', JSON.stringify(plainText));
81
+ console.log('settle path think:', JSON.stringify(plainReasoning));
82
+ if (plainText !== '只有文字,没有工具调用') { console.log('assembler: FAILED — settle-path text'); process.exit(1); }
83
+ if (plainReasoning !== '先想') { console.log('assembler: FAILED — settle-path reasoning'); process.exit(1); }
84
+ }
85
+
86
+ console.log('assembler: all checks passed');