dsh-codearts-dock 0.0.0-stage → 1.0.1

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 (49) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/SECURITY.md +45 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3491 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +24 -0
  9. package/docs/DETAIL.zh.md +24 -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 +715 -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 +15 -0
  31. package/src/index.js +1029 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +87 -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/test/accounts.test.mjs +344 -0
  41. package/test/adapter.test.mjs +234 -0
  42. package/test/assembler.test.mjs +86 -0
  43. package/test/features.test.mjs +240 -0
  44. package/test/live-probe.mjs +55 -0
  45. package/test/protocol.test.mjs +167 -0
  46. package/test/registration.test.mjs +303 -0
  47. package/test/sm4.test.mjs +64 -0
  48. package/test/ui.test.mjs +732 -0
  49. package/test/visual.test.mjs +420 -0
package/src/adapter.js ADDED
@@ -0,0 +1,715 @@
1
+ /**
2
+ * The 码道 LLM adapter.
3
+ *
4
+ * This is a native `LlmAdapter`, not a local HTTP bridge. The Host registers
5
+ * it against a provider route and calls `stream()` directly, which removes a
6
+ * whole process, a port, a restart, and a rewrite of the model list on disk
7
+ * from the design — the catalog is whatever the gateway said at the last
8
+ * refresh.
9
+ *
10
+ * The adapter converts between two vocabularies:
11
+ *
12
+ * Host messages (durable, role-tagged, block-structured)
13
+ * -> OpenAI chat-completions messages (what the gateway accepts)
14
+ *
15
+ * gateway SSE events (text / reasoning / tool-call deltas)
16
+ * -> Host `StreamChunk`s (block-start, delta, block-end, usage, finish)
17
+ */
18
+
19
+ import { GatewayError, MadaoClient } from './gateway.js'
20
+ import { parseIdentity } from './account.js'
21
+
22
+ /**
23
+ * @typedef {object} AdapterDeps
24
+ * @property {import('./credentials.js').CredentialProvider} credentials resolves a signed triple.
25
+ * @property {import('./catalog.js').Catalog} catalog the live model catalog.
26
+ * @property {() => string|undefined} [gateway] gateway root override.
27
+ * @property {() => any} [attachments] the Host attachment service, for image bytes.
28
+ * @property {(key: any) => MadaoClient} [createClient] client factory, injected by tests.
29
+ * @property {(line: string) => void} [log] diagnostic sink.
30
+ */
31
+
32
+ /**
33
+ * The Host's `LlmAdapter` base class, or a local stand-in with the same defaults.
34
+ *
35
+ * The Host provides `@deepseek-ai/dsh-llm` at runtime and resolves it for loaded
36
+ * plugins; a checkout run on its own (tests, a probe script) has no such package.
37
+ * Extending the base MATTERS — it carries `imageRequestPricing` and
38
+ * `imageRequestTarget`, which the Host calls unconditionally. A plain class that
39
+ * merely looks like an adapter registers and streams fine, then dies mid-session
40
+ * the first time some other code path asks for one of them:
41
+ *
42
+ * this.adapters.get(...)?.adapter.imageRequestPricing is not a function
43
+ *
44
+ * Hence: use the real base when it resolves, and fall back to an equivalent one
45
+ * so the plugin still runs outside the Host. The two are interchangeable because
46
+ * every method the fallback defines is the same default the Host's base defines.
47
+ */
48
+ let LlmAdapter
49
+ try {
50
+ ;({ LlmAdapter } = await import('@deepseek-ai/dsh-llm'))
51
+ } catch {
52
+ /**
53
+ * The Host base class's defaults, restated.
54
+ *
55
+ * A provider that prices no images and has no per-image target reports exactly
56
+ * that, and a provider with no retry opinion defers to the Host's default.
57
+ */
58
+ LlmAdapter = class {
59
+ providerInfo(provider) {
60
+ return { id: provider, name: provider }
61
+ }
62
+ providerRetryPolicy() {
63
+ return undefined
64
+ }
65
+ imageRequestPricing() {
66
+ return undefined
67
+ }
68
+ imageRequestTarget() {
69
+ return { width: 0, height: 0, maxBytes: 0 }
70
+ }
71
+ listModels() {
72
+ return []
73
+ }
74
+ resolveModel(provider, model) {
75
+ return { provider, id: model, name: model }
76
+ }
77
+ prepareCall() {
78
+ throw new Error('prepareCall must be implemented by the adapter')
79
+ }
80
+ }
81
+ }
82
+
83
+ /** Provider route this adapter owns. */
84
+ export const PROVIDER_ID = 'codearts'
85
+
86
+ /** The name the model selector shows for this route. */
87
+ export const PROVIDER_NAME = '码道 CodeArts'
88
+
89
+ /**
90
+ * Reasoning level ids the Host understands, mapped to what the gateway reads.
91
+ *
92
+ * The gateway reads `reasoning_effort` and ignores anything else, so a level
93
+ * only works when it maps to a value in this table.
94
+ */
95
+ const REASONING_LEVELS = {
96
+ off: 'none',
97
+ low: 'low',
98
+ medium: 'medium',
99
+ high: 'high',
100
+ max: 'max',
101
+ }
102
+
103
+ /** Reasoning effort ids the Host offers, in display order. */
104
+ const HOST_EFFORT_ORDER = ['off', 'low', 'medium', 'high', 'max']
105
+
106
+ /**
107
+ * Build the adapter.
108
+ *
109
+ * @param {AdapterDeps} deps adapter dependencies.
110
+ * @returns {any} an `LlmAdapter`-compatible instance.
111
+ */
112
+ export function createCodeArtsAdapter(deps) {
113
+ return new CodeArtsAdapter(deps)
114
+ }
115
+
116
+ /**
117
+ * The adapter.
118
+ *
119
+ * EXTENDS `LlmAdapter`, and that is not decoration. The base carries methods the
120
+ * Host calls unconditionally — `imageRequestPricing` and `imageRequestTarget`
121
+ * among them — with sane defaults for a provider that prices no images. A plain
122
+ * class that merely *looks* like an adapter passes registration and streams
123
+ * fine, then dies mid-session the first time any other code path asks for one of
124
+ * those methods: `this.adapters.get(...)?.adapter.imageRequestPricing is not a
125
+ * function`.
126
+ */
127
+ class CodeArtsAdapter extends LlmAdapter {
128
+ /**
129
+ * @param {AdapterDeps} deps adapter dependencies.
130
+ */
131
+ constructor(deps) {
132
+ // `super()` first: this class extends the Host's base, and a derived
133
+ // constructor may not touch `this` before it runs.
134
+ super()
135
+ this.deps = deps
136
+ this.clients = new Map()
137
+ }
138
+
139
+ /** Human-readable route metadata. */
140
+ providerInfo(provider) {
141
+ return { id: provider, name: PROVIDER_NAME }
142
+ }
143
+
144
+ /**
145
+ * The provider-owned retry policy.
146
+ *
147
+ * A rejected request body is never worth retrying: the same bytes produce
148
+ * the same 400 whoever sends them. Transport failures and 5xx are.
149
+ */
150
+ providerRetryPolicy() {
151
+ return {
152
+ mode: 'normal',
153
+ maxRetries: 2,
154
+ retryableCodes: ['REQUEST_FAILED', 'PROVIDER_ERROR', 'RATE_LIMITED'],
155
+ initialDelayMs: 1000,
156
+ maxDelayMs: 15_000,
157
+ jitterRatio: 0.2,
158
+ }
159
+ }
160
+
161
+ /** The catalog this route advertises. */
162
+ async listModels(provider) {
163
+ if (provider !== PROVIDER_ID) return []
164
+ // The SELECTION, not the raw roster: a model the user unticked must leave
165
+ // the picker, and one they ticked must appear even if the upstream added it
166
+ // after the last refresh.
167
+ const catalog = this.deps.catalog
168
+ const models = typeof catalog.visible === 'function' ? catalog.visible() : catalog.models()
169
+ return models.map((model) => this.#modelInfo(provider, this.#effective(model)))
170
+ }
171
+
172
+ /** Resolve one model's exact metadata. */
173
+ async resolveModel(provider, modelId) {
174
+ if (provider !== PROVIDER_ID) {
175
+ throw new GatewayError(`码道适配器不服务于 provider "${provider}"`)
176
+ }
177
+ const model = this.#effective(this.deps.catalog.find(modelId))
178
+ if (!model) {
179
+ // The Host accepts unlisted model ids for routing, but there is nothing
180
+ // to declare about one, so answer with the bare identity rather than
181
+ // inventing capabilities.
182
+ return { provider, id: modelId, name: modelId }
183
+ }
184
+ return {
185
+ ...this.#modelInfo(provider, model),
186
+ context: model.context > 0 ? { contextWindow: model.context } : undefined,
187
+ defaultMaxTokens: model.maxOutput,
188
+ ...(this.#reasoningInfo(model) ? { reasoning: this.#reasoningInfo(model) } : {}),
189
+ }
190
+ }
191
+
192
+ /** Bind model metadata and dispatch to one adapter generation. */
193
+ async prepareCall(provider, modelId) {
194
+ const resolved = await this.resolveModel(provider, modelId)
195
+ return {
196
+ model: resolved,
197
+ stream: (options) => this.stream(options),
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Stream one call.
203
+ *
204
+ * Emits the block lifecycle explicitly: the Host's assembler is tolerant of
205
+ * delta-only streams, but starting and closing each block keeps the
206
+ * transcript correct when text and reasoning interleave.
207
+ *
208
+ * @param {any} options Host generation options.
209
+ * @returns {AsyncGenerator<any>} Host stream chunks.
210
+ */
211
+ async *stream(options) {
212
+ const model = this.#effective(this.deps.catalog.find(options.model))
213
+ const client = await this.#client()
214
+
215
+ /** @type {number} */ let nextIndex = 0
216
+ /** Open text block index, or undefined when none is open. */
217
+ let textIndex
218
+ /** Open reasoning block index. */
219
+ let reasoningIndex
220
+ /** Open tool-call blocks, keyed by the upstream call index. */
221
+ const toolBlocks = new Map()
222
+ /** Tool-call ids by upstream index, so later argument frames match. */
223
+ const toolIds = new Map()
224
+ // The Host assembler treats a `block-end` block as authoritative: it
225
+ // REPLACES whatever the deltas accumulated. So each close must echo the
226
+ // content this adapter streamed, or the block ends up empty.
227
+ let textContent = ''
228
+ let reasoningContent = ''
229
+ /** Accumulated arguments and names, keyed by upstream call index. */
230
+ const toolArgs = new Map()
231
+ const toolNames = new Map()
232
+ let sawToolCall = false
233
+ /** Finish reason seen on the wire, emitted once the stream settles. */
234
+ let pendingFinish
235
+
236
+ const closeAll = function* () {
237
+ if (textIndex !== undefined) {
238
+ yield { type: 'block-end', index: textIndex, block: { type: 'text', text: textContent } }
239
+ textIndex = undefined
240
+ }
241
+ if (reasoningIndex !== undefined) {
242
+ yield {
243
+ type: 'block-end',
244
+ index: reasoningIndex,
245
+ block: { type: 'reasoning', text: reasoningContent },
246
+ }
247
+ reasoningIndex = undefined
248
+ }
249
+ for (const [callIndex, blockIndex] of toolBlocks) {
250
+ yield {
251
+ type: 'block-end',
252
+ index: blockIndex,
253
+ block: {
254
+ type: 'tool-call',
255
+ id: toolIds.get(callIndex) ?? `tool-${callIndex}`,
256
+ name: toolNames.get(callIndex) ?? '',
257
+ arguments: toolArgs.get(callIndex) ?? '',
258
+ },
259
+ }
260
+ }
261
+ toolBlocks.clear()
262
+ }
263
+
264
+ try {
265
+ const messages = await toGatewayMessages(options, this.deps.attachments)
266
+ const request = {
267
+ // Never the display string: the gateway answers a `name · ratio` value
268
+ // with HTTP 200 and an empty body, which surfaces only as "returned a
269
+ // completed response with no content".
270
+ model:
271
+ typeof this.deps.catalog?.resolveId === 'function'
272
+ ? this.deps.catalog.resolveId(options.model)
273
+ : options.model,
274
+ messages,
275
+ maxTokens: options.maxTokens ?? model?.maxOutput,
276
+ temperature: options.temperature,
277
+ ...(options.stop ? { stop: options.stop } : {}),
278
+ ...(options.tools && options.tools.length > 0
279
+ ? { tools: options.tools.map(toGatewayTool) }
280
+ : {}),
281
+ ...(options.reasoningEffort ? { reasoningEffort: String(options.reasoningEffort) } : {}),
282
+ signal: options.signal,
283
+ }
284
+
285
+ await client.heartbeat('busy')
286
+
287
+ for await (const event of client.streamChat(request)) {
288
+ if (options.signal?.aborted) {
289
+ yield* closeAll()
290
+ yield { type: 'finish', reason: { kind: 'aborted', failure: { message: '已取消', code: 'ABORTED' } } }
291
+ return
292
+ }
293
+
294
+ if (event.reasoning) {
295
+ if (reasoningIndex === undefined) {
296
+ reasoningIndex = nextIndex++
297
+ yield { type: 'block-start', index: reasoningIndex, blockType: 'reasoning' }
298
+ }
299
+ reasoningContent += event.reasoning
300
+ yield { type: 'reasoning-delta', index: reasoningIndex, text: event.reasoning }
301
+ }
302
+
303
+ if (event.text) {
304
+ if (textIndex === undefined) {
305
+ textIndex = nextIndex++
306
+ yield { type: 'block-start', index: textIndex, blockType: 'text' }
307
+ }
308
+ textContent += event.text
309
+ yield { type: 'text-delta', index: textIndex, text: event.text }
310
+ }
311
+
312
+ if (event.toolCalls) {
313
+ sawToolCall = true
314
+ for (const delta of event.toolCalls) {
315
+ const callIndex = typeof delta.index === 'number' ? delta.index : 0
316
+ if (delta.id) toolIds.set(callIndex, delta.id)
317
+
318
+ let blockIndex = toolBlocks.get(callIndex)
319
+ if (blockIndex === undefined) {
320
+ blockIndex = nextIndex++
321
+ toolBlocks.set(callIndex, blockIndex)
322
+ // Close a pending text block first: a tool call terminates the
323
+ // assistant's visible text for that turn.
324
+ if (textIndex !== undefined) {
325
+ yield {
326
+ type: 'block-end',
327
+ index: textIndex,
328
+ block: { type: 'text', text: textContent },
329
+ }
330
+ textIndex = undefined
331
+ }
332
+ yield { type: 'block-start', index: blockIndex, blockType: 'tool-call' }
333
+ }
334
+
335
+ const id = toolIds.get(callIndex) ?? `tool-${callIndex}`
336
+ const name = delta.function?.name
337
+ const argumentsDelta = delta.function?.arguments ?? ''
338
+ if (name) toolNames.set(callIndex, name)
339
+ if (argumentsDelta) toolArgs.set(callIndex, (toolArgs.get(callIndex) ?? '') + argumentsDelta)
340
+ if (name || argumentsDelta) {
341
+ yield {
342
+ type: 'tool-call-delta',
343
+ index: blockIndex,
344
+ id,
345
+ ...(name ? { name } : {}),
346
+ argumentsDelta,
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ if (event.usage) {
353
+ yield {
354
+ type: 'usage',
355
+ usage: {
356
+ inputTokens: event.usage.inputTokens,
357
+ outputTokens: event.usage.outputTokens,
358
+ ...(event.usage.totalTokens ? { totalTokens: event.usage.totalTokens } : {}),
359
+ },
360
+ }
361
+ }
362
+
363
+ // The gateway's own order is text/reasoning, then `finish`, then the
364
+ // `usage` frame, then `[DONE]`. Returning on `finish` would therefore
365
+ // discard the token counts, so the reason is recorded and the finish
366
+ // chunk is emitted once the stream is actually over.
367
+ if (event.finish) {
368
+ pendingFinish = mapFinishReason(event.finish, sawToolCall)
369
+ }
370
+
371
+ if (event.done) break
372
+ }
373
+
374
+ // A completed reply with reasoning but no visible text and no tool call
375
+ // is the failure mode this gateway produces when the output budget runs
376
+ // out inside the thinking phase: reasoning and content share
377
+ // `max_tokens`. The Host would otherwise report only "returned a
378
+ // completed response with no content", which names no cause and suggests
379
+ // no fix. Say what happened instead.
380
+ if (
381
+ textContent === '' &&
382
+ reasoningContent !== '' &&
383
+ !sawToolCall &&
384
+ (pendingFinish === undefined || pendingFinish.kind === 'stop')
385
+ ) {
386
+ const budget = request.maxTokens ?? 0
387
+ const note =
388
+ `(模型把输出预算都用在思考上了:思考 ${reasoningContent.length} 字,正文 0 字,` +
389
+ `本次 max_tokens=${budget}。思考与正文共用这个预算——提高 max_tokens(几百以上)通常即可恢复。)`
390
+ if (textIndex === undefined) {
391
+ textIndex = nextIndex++
392
+ yield { type: 'block-start', index: textIndex, blockType: 'text' }
393
+ }
394
+ textContent = note
395
+ yield { type: 'text-delta', index: textIndex, text: note }
396
+ }
397
+
398
+ // Settle: close open blocks, then finish with whatever reason arrived.
399
+ yield* closeAll()
400
+ yield {
401
+ type: 'finish',
402
+ reason: pendingFinish ?? (sawToolCall ? { kind: 'tool-calls' } : { kind: 'stop' }),
403
+ }
404
+ } catch (error) {
405
+ yield* closeAll()
406
+
407
+ const failure = describeFailure(error)
408
+ // A cancellation surfaces as an aborted finish; anything else as an error.
409
+ yield {
410
+ type: 'finish',
411
+ reason:
412
+ error?.name === 'AbortError'
413
+ ? { kind: 'aborted', failure }
414
+ : { kind: 'error', failure },
415
+ }
416
+ } finally {
417
+ // Releasing the concurrency slot matters even on failure: the gateway
418
+ // allows only a few sessions, and a held slot blocks every new turn.
419
+ void client.heartbeat('idle').catch(() => {})
420
+ }
421
+ }
422
+
423
+ /** Build (or reuse) the gateway client for the current credential. */
424
+ async #client() {
425
+ const resolved = await this.deps.credentials.resolve()
426
+ const key = resolved.key
427
+ const signature = `${key.ak}:${key.securityToken}`
428
+ const existing = this.clients.get(signature)
429
+ if (existing) return existing
430
+
431
+ // A renewed credential replaces the client: the old one signs with a
432
+ // dead token.
433
+ this.clients.clear()
434
+ const client = this.deps.createClient
435
+ ? this.deps.createClient(key)
436
+ : new MadaoClient({ credentials: key, gateway: this.deps.gateway?.() })
437
+ this.clients.set(signature, client)
438
+ return client
439
+ }
440
+
441
+ /**
442
+ * Apply the user's capability overrides to one model, when the catalog can.
443
+ *
444
+ * Optional on purpose: `effective` is a later addition, and a catalog that
445
+ * predates it (a test double, a downgraded host) must degrade to the plain
446
+ * model rather than break every request.
447
+ */
448
+ #effective(model) {
449
+ const catalog = this.deps.catalog
450
+ return typeof catalog?.effective === 'function' ? catalog.effective(model) : model
451
+ }
452
+
453
+ /** Convert one catalog entry into Host model metadata. */
454
+ #modelInfo(provider, model) {
455
+ return {
456
+ provider,
457
+ id: model.id,
458
+ name: model.ratio ? `${model.name} · ${model.ratio}` : model.name,
459
+ ...(model.description ? { description: model.description } : {}),
460
+ ...(model.supportsImages ? { inputModalities: ['text', 'image'] } : { inputModalities: ['text'] }),
461
+ }
462
+ }
463
+
464
+ /** Build the Host reasoning descriptor for a model that declares levels. */
465
+ #reasoningInfo(model) {
466
+ if (!model.strengths || model.strengths.length === 0) return undefined
467
+ const levels = new Set(model.strengths)
468
+ // `allowOff` is the user's answer to "should this model offer a 'no thinking'
469
+ // level". Undefined keeps the upstream answer; false withholds it, because a
470
+ // model that refuses `off` fails the whole request for anyone who picks it.
471
+ const offerOff = model.allowOff !== false
472
+ return {
473
+ efforts: HOST_EFFORT_ORDER.filter(
474
+ (level) => (level === 'off' ? offerOff : levels.has(level)),
475
+ ).map(
476
+ (level) => ({
477
+ id: level,
478
+ name: REASONING_LABELS[level] ?? level,
479
+ }),
480
+ ),
481
+ defaultEffort: model.defaultStrength && levels.has(model.defaultStrength)
482
+ ? model.defaultStrength
483
+ : [...levels][0],
484
+ }
485
+ }
486
+ }
487
+
488
+ /** Display names for the reasoning levels. */
489
+ const REASONING_LABELS = {
490
+ off: '关闭思考',
491
+ low: '低',
492
+ medium: '中',
493
+ high: '高',
494
+ max: '最高',
495
+ }
496
+
497
+ /**
498
+ * Convert Host messages into OpenAI chat messages.
499
+ *
500
+ * Three conversions are load-bearing:
501
+ *
502
+ * • `developer` becomes `system`. The gateway accepts only
503
+ * system/user/assistant/tool; a `developer` message is answered with an
504
+ * empty 200 response, which the Host can only report as an empty reply.
505
+ * • Tool results attach to the tool call they answer, as `tool` messages.
506
+ * • Images become `image_url` parts carrying a data URL — the gateway
507
+ * recognises that OpenAI shape and not the client's internal `file` one.
508
+ * The bytes come from the attachment service, because a durable image
509
+ * block holds a reference, not a payload.
510
+ *
511
+ * @param {any} options Host generation options.
512
+ * @param {any} [attachments] the Host attachment service, when mounted.
513
+ * @returns {Promise<Array<object>>} gateway messages.
514
+ */
515
+ async function toGatewayMessages(options, attachments) {
516
+ /** @type {Array<object>} */
517
+ const messages = []
518
+
519
+ if (typeof options.system === 'string' && options.system !== '') {
520
+ messages.push({ role: 'system', content: options.system })
521
+ }
522
+
523
+ for (const message of options.messages ?? []) {
524
+ switch (message.role) {
525
+ case 'system':
526
+ case 'developer':
527
+ // The gateway silently ignores `developer`, so it must be downgraded
528
+ // rather than dropped: it carries the system prompt.
529
+ messages.push({ role: 'system', content: flattenText(message.content) })
530
+ break
531
+
532
+ case 'user': {
533
+ const content = await toGatewayContent(message.content, attachments, options.signal)
534
+ if (content !== '') messages.push({ role: 'user', content })
535
+ break
536
+ }
537
+
538
+ case 'assistant': {
539
+ const text = flattenText(message.content)
540
+ const toolCalls = (message.content ?? [])
541
+ .filter((block) => block?.type === 'tool-call')
542
+ .map((block) => ({
543
+ id: block.id,
544
+ type: 'function',
545
+ function: { name: block.name, arguments: block.arguments },
546
+ }))
547
+ if (text === '' && toolCalls.length === 0) break
548
+ messages.push({
549
+ role: 'assistant',
550
+ ...(text !== '' ? { content: text } : { content: null }),
551
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
552
+ })
553
+ break
554
+ }
555
+
556
+ case 'tool':
557
+ messages.push({
558
+ role: 'tool',
559
+ tool_call_id: message.toolCallId ?? message.source?.callId,
560
+ content: flattenText(message.content),
561
+ })
562
+ break
563
+
564
+ default:
565
+ break
566
+ }
567
+ }
568
+
569
+ return messages
570
+ }
571
+
572
+ /**
573
+ * Flatten Host content blocks into plain text.
574
+ * @param {Array<any>|string|undefined} content content blocks.
575
+ * @returns {string} concatenated text.
576
+ */
577
+ function flattenText(content) {
578
+ if (typeof content === 'string') return content
579
+ if (!Array.isArray(content)) return ''
580
+ return content
581
+ .filter((block) => block?.type === 'text')
582
+ .map((block) => block.text ?? '')
583
+ .join('')
584
+ }
585
+
586
+ /**
587
+ * Convert Host content into the gateway's content form.
588
+ *
589
+ * All-text content collapses to a plain string, which is both cheaper on the
590
+ * wire and the only form some models accept.
591
+ *
592
+ * @param {Array<any>|string|undefined} content content blocks.
593
+ * @param {any} [attachments] the Host attachment service.
594
+ * @param {AbortSignal} [signal] cancellation.
595
+ * @returns {Promise<string|Array<object>>} gateway content.
596
+ */
597
+ async function toGatewayContent(content, attachments, signal) {
598
+ if (typeof content === 'string') return content
599
+ if (!Array.isArray(content)) return ''
600
+
601
+ const parts = []
602
+ for (const block of content) {
603
+ if (block?.type === 'text' && typeof block.text === 'string') {
604
+ parts.push({ type: 'text', text: block.text })
605
+ } else if (block?.type === 'image' && block.attachment) {
606
+ // A durable image block carries a reference; the bytes come from the
607
+ // attachment service as a data URL the gateway understands.
608
+ const encoded = await encodeImage(block.attachment, attachments, signal)
609
+ if (encoded) parts.push({ type: 'image_url', image_url: { url: encoded } })
610
+ }
611
+ }
612
+
613
+ if (parts.length === 0) return ''
614
+ if (parts.every((part) => part.type === 'text')) {
615
+ return parts.map((part) => part.text).join('')
616
+ }
617
+ return parts
618
+ }
619
+
620
+ /**
621
+ * Encode one durable image as a data URL.
622
+ *
623
+ * An image that cannot be read is reported to the model as a short text note
624
+ * rather than silently dropped: a missing picture must not look like the
625
+ * question was never sent with one.
626
+ *
627
+ * @param {any} ref the image attachment reference.
628
+ * @param {any} attachments the Host attachment service.
629
+ * @param {AbortSignal} [signal] cancellation.
630
+ * @returns {Promise<string|null>} the data URL, or null when unreadable.
631
+ */
632
+ async function encodeImage(ref, attachments, signal) {
633
+ try {
634
+ if (typeof attachments?.readImageRequest === 'function') {
635
+ // Ask for the image at its stored size: the gateway does its own
636
+ // resizing, and a second downscale here would only lose detail.
637
+ const read = await attachments.readImageRequest(
638
+ ref,
639
+ { width: ref.width, height: ref.height, maxBytes: ref.bytes },
640
+ signal,
641
+ )
642
+ return `data:${read.mediaType};base64,${Buffer.from(read.data).toString('base64')}`
643
+ }
644
+ if (typeof attachments?.readImage === 'function') {
645
+ const read = await attachments.readImage(ref, signal)
646
+ return `data:${ref.mediaType};base64,${Buffer.from(read.data).toString('base64')}`
647
+ }
648
+ } catch {
649
+ return null
650
+ }
651
+ return null
652
+ }
653
+
654
+ /**
655
+ * Convert one Host tool schema into the gateway's function-tool form.
656
+ * @param {any} tool Host tool schema.
657
+ * @returns {object} gateway tool schema.
658
+ */
659
+ function toGatewayTool(tool) {
660
+ return {
661
+ type: 'function',
662
+ function: {
663
+ name: tool.name,
664
+ description: tool.description ?? '',
665
+ parameters: tool.parameters ?? { type: 'object', properties: {} },
666
+ },
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Map an upstream finish reason onto the Host vocabulary.
672
+ * @param {string} finish upstream reason.
673
+ * @param {boolean} sawToolCall whether any tool call was streamed.
674
+ * @returns {any} Host finish reason.
675
+ */
676
+ function mapFinishReason(finish, sawToolCall) {
677
+ switch (finish) {
678
+ case 'tool_calls':
679
+ case 'function_call':
680
+ return { kind: 'tool-calls' }
681
+ case 'length':
682
+ case 'max_tokens':
683
+ return { kind: 'max-tokens' }
684
+ case 'content_filter':
685
+ return { kind: 'stop' }
686
+ default:
687
+ // Some gateways report `stop` even for a tool-call turn.
688
+ return sawToolCall ? { kind: 'tool-calls' } : { kind: 'stop' }
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Turn a thrown error into a Host failure.
694
+ *
695
+ * The gateway's queue codes are translated rather than relayed, because the
696
+ * upstream text names a business code and not what the user should do.
697
+ * @param {any} error the thrown error.
698
+ * @returns {{message: string, code: string, status?: number}} Host failure facts.
699
+ */
700
+ function describeFailure(error) {
701
+ if (error instanceof GatewayError) {
702
+ return {
703
+ message: error.message,
704
+ code: error.code ?? (error.status ? 'PROVIDER_ERROR' : 'REQUEST_FAILED'),
705
+ ...(error.status ? { status: error.status } : {}),
706
+ }
707
+ }
708
+ if (error?.name === 'AbortError') {
709
+ return { message: '已取消', code: 'ABORTED' }
710
+ }
711
+ return { message: error?.message ?? String(error), code: 'REQUEST_FAILED' }
712
+ }
713
+
714
+ /** Re-export so the Host half can name the identity helper without a second import. */
715
+ export { parseIdentity }