dsh-mobile-plugin 0.5.124 → 0.5.126

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.
package/lib/impl.js CHANGED
@@ -431,6 +431,7 @@ function apply(ctx) {
431
431
  controlTarget: () => (state.controlToken && state.instanceId
432
432
  ? { baseUrl: CONTROL_BASE_URL, token: state.controlToken, instanceId: state.instanceId }
433
433
  : null),
434
+ workspaceIdOf: ({ sessionId }) => require('./mobile/workspace-id.js').workspaceIdOf(ctx, { sessionId }),
434
435
  })
435
436
  // 镜像推送调度器:会话事件立即推,后台循环每个 tick 补推一个冷会话;凭据摘要由装配层给取值器(凭据库归本进程),中转靠它认离线缓存的读者。
436
437
  mirror = createMirrorPusher({ ctx, tunnelConnected, getSidecar: sidecarLifecycle.getSidecar, lastMobileAt: activity.snapshot, credentialDigests: () => credentials.activeDigests(state.instanceId), getHistoryKey, notifyTurnEnded: pushNotify.notifyTurnEnded })
@@ -496,14 +497,16 @@ function apply(ctx) {
496
497
  }
497
498
  return undefined
498
499
  }, `${name}: workspace tool`)
499
- ctx.effect(() => {
500
- // 反馈工具:设备身份从凭据库取(手机每条请求都上报,宿主写回记录),提交到分发平台。
501
- // hostVersion 从同进程的宿主版本台账取(host.js 启动时写入),作为 Harness 版本上报。
502
- try { installFeedback(ctx, { credentials, instanceId: () => state.instanceId, hostVersion: () => readCapabilityReport()?.runtimeVersion || '' }) } catch (error) {
500
+ // 反馈工具:设备身份从凭据库取(手机每条请求都上报,宿主写回记录),提交到分发平台。
501
+ // hostVersion 从同进程的宿主版本台账取(host.js 启动时写入),作为 Harness 版本上报。
502
+ // 用 `ctx.inject` 挂一个等 `tools` 的子作用域,而不是直接 `ctx.get('tools')` 注册:注册记在
503
+ // 这个子 fiber 名下,热重载换代时随旧代卸掉。直接注册只记在共享的服务上,下一次重载会被
504
+ // 判「dsh_feedback 已经注册过」而整代装载失败。
505
+ mount('反馈工具', () => ctx.inject(['tools'], (scoped) => {
506
+ try { installFeedback(scoped, { credentials, instanceId: () => state.instanceId, hostVersion: () => readCapabilityReport()?.runtimeVersion || '' }) } catch (error) {
503
507
  if (!String(error).includes('without inject')) throw error
504
508
  }
505
- return undefined
506
- }, `${name}: feedback tool`)
509
+ }))
507
510
  mount('统计采集', () => ctx.effect(() => statsScheduler.start(ctx), `${name}: stats collect`))
508
511
  mount('过程播报', () => ctx.effect(() => installNarration(ctx), `${name}: process narration`))
509
512
 
@@ -1236,7 +1236,7 @@ function createMirrorPusher(deps) {
1236
1236
  // 标题从镜像快照现查:中转与苹果都只认纯文本,没查到就用会话 id 前缀。
1237
1237
  if (p?.event?.type === 'turn/end' && notifyTurnEnded) {
1238
1238
  const fact = lastTurnOf(ctx, sessionId);
1239
- if (fact) notifyTurnEnded(sessionId, fact, sessionTitleOf(sessionId));
1239
+ if (fact) void notifyTurnEnded(sessionId, fact, sessionTitleOf(sessionId));
1240
1240
  }
1241
1241
  void pushSessionImmediately(sessionId);
1242
1242
  }
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * 手机端审批桥(DSH 0.2.x)。
4
+ * 手机答完 agent 照常往下走。2026-11-26:手机在看时也照转,桌面与手机同时出卡(与提问桥对齐),
5
+ * 谁先答用谁的;不再按「手机离开」交接。
5
6
  *
6
7
  * 0.2.x 删掉了 apiProxy,审批变成会话日志里的 `approval/asked` / `approval/decided` 事件对
7
8
  * 加一个进程内 waterfall 钩子 `approval/request`,帧级 rpcId 就此消失,而 App 的审批面板
@@ -10,8 +11,10 @@
10
11
  * rpcId 找到挂起项把结论交回钩子。
11
12
  *
12
13
  * 钩子必须 prepend:宿主自己的转发器在桌面窗口开着时会一直等桌面回答、不调用 `next()`,
13
- * 老实排在注册顺序后面等于「桌面开着时手机永远收不到」。手机在看时独占审批,最后一条
14
- * 会话连接离开后将未裁决的请求交给桌面;桌面不可用时仍保留手机作答入口。
14
+ * 老实排在注册顺序后面等于「桌面开着时手机永远收不到」。请求一律往下转发:桌面窗口与手机
15
+ * 同时出卡,谁先答用谁的(与提问桥 `mobile/questions.js` 同一口径);手机先答时按请求对象
16
+ * 撤回桌面那一发,避免留一张点不动的卡。桌面没接手(unavailable / NO_PROVIDER)不算结论,
17
+ * 保留手机作答入口,直到有人答或 turn 被中止。
15
18
  *
16
19
  * 钩子上没有宿主 id,且与 `approval/asked` 的到达顺序不定,所以两个来源共用一张挂起项表:
17
20
  * 先到的建项,后到的补字段。
@@ -91,16 +94,6 @@ function watcherCount(sessionId) {
91
94
  return set ? set.size : 0;
92
95
  }
93
96
 
94
- /**
95
- * 这条会话此刻有没有手机在看着 —— **自动审阅档唯一的「人在不在」判据**。
96
- *
97
- * 进程级的「最近有没有手机请求」不算:在别的会话里刷一下就会把这条会话算成有人,
98
- * 而手机放着不动两分钟又会把有人算成人不在。观众表按 sessionId 记 sink,才是准确的。
99
- */
100
- function isSessionWatched(sessionId) {
101
- return watcherCount(sessionId) > 0;
102
- }
103
-
104
97
  function openEntries(sessionId) {
105
98
  const list = bySession.get(sessionId);
106
99
  return list ? list.filter((entry) => !entry.settled) : [];
@@ -269,10 +262,7 @@ function attachSession(sessionId, sink) {
269
262
  }
270
263
  return () => {
271
264
  if (!set.delete(sink)) return;
272
- if (set.size === 0) {
273
- watchers.delete(sessionId);
274
- for (const entry of openEntries(sessionId)) entry.forwardToDesktop?.();
275
- }
265
+ if (set.size === 0) watchers.delete(sessionId);
276
266
  };
277
267
  }
278
268
 
@@ -656,41 +646,44 @@ function bindRequest(entry, request) {
656
646
  }
657
647
 
658
648
  /**
659
- * 手机在看时先独占;最后一条连接离开后,将同一审批交给桌面竞速一次。
660
- * 交接时桌面不可用只表示没人接手,仍等手机回来作答;不改变无人观看时的原有下游结论。
649
+ * 桌面与手机同时出卡:转发照旧发下去,谁先答用谁的(与提问桥 `holdForPhone` 同一口径)。
650
+ *
651
+ * 桌面那张卡只由「被转发的请求」长出来 —— 手机在看时不转发,桌面从源头就没有卡,之后切
652
+ * 过去也补不回来。转发后桌面先答就结算挂起项(手机卡由结算帧收掉);手机先答则把结论交回
653
+ * 钩子,`handleApprovalRespond` 里按请求对象撤回桌面那一发。
654
+ *
655
+ * `unavailable` / NO_PROVIDER 任何情况下都不是结论,也跟「手机此刻有没有在看这条会话」无关:
656
+ * 手机这条路本来就是「人离开了再看」,通知与侧栏待处理标记就是把人带回来的那两根线。只在
657
+ * 有观众时才据此继续等,会让手机停在别的会话 / 后台时,一条本来还能答的审批被当成没人答、
658
+ * 模型当被跳过继续跑 —— 用户看到的就是「点通知进来,审批已经自己跳过了」。
659
+ *
660
+ * 收尾只有两条:有人作答(`entry.wait`),或宿主的取消信号(停止这一轮 / 轮次被中止,见
661
+ * `bindRequest` 的 onAbort)。
661
662
  */
662
663
  function holdForPhone(entry, next) {
663
- const handoff = isSessionWatched(entry.sessionId);
664
- const downstream = new Promise((resolve, reject) => {
665
- let forwarded = false;
666
- entry.forwardToDesktop = () => {
667
- if (forwarded || entry.settled) return;
668
- forwarded = true;
669
- Promise.resolve().then(() => {
670
- if (!entry.settled) return next();
671
- }).then((outcome) => {
672
- if (entry.settled) return;
673
- const value = DECISIONS.has(outcome) ? outcome : 'unavailable';
674
- if (handoff && value === 'unavailable') return;
675
- settle(entry, value);
676
- resolve(value);
677
- }, (error) => {
678
- if (entry.settled || (handoff && error?.code === 'NO_PROVIDER')) return;
679
- reject(error);
680
- });
681
- };
682
- if (!handoff) entry.forwardToDesktop();
683
- });
684
- return Promise.race([entry.wait.then((result) => result.outcome), downstream])
685
- .finally(() => { entry.forwardToDesktop = null; });
664
+ const downstream = Promise.resolve().then(() => next()).then(
665
+ (outcome) => {
666
+ if (entry.settled) return undefined;
667
+ const value = DECISIONS.has(outcome) ? outcome : 'unavailable';
668
+ if (value === 'unavailable') return new Promise(() => {});
669
+ settle(entry, value);
670
+ return value;
671
+ },
672
+ (error) => {
673
+ if (entry.settled) return undefined;
674
+ if (error && error.code === 'NO_PROVIDER') return new Promise(() => {});
675
+ settle(entry, 'unavailable');
676
+ throw error;
677
+ },
678
+ );
679
+ return Promise.race([entry.wait.then((result) => result.outcome), downstream]);
686
680
  }
687
681
 
688
682
  /**
689
683
  * 收掉桌面那张审批卡:把宿主已经发给桌面窗口、还挂着的那一发转发撤掉。
690
684
  *
691
- * 手机在看时不转发;没有观众或最后一条连接离开后,桌面那一发会与手机作答竞速。手机先答
692
- * 时按请求对象撤回桌面卡,与提问桥共用传输层的收尾口子。认不到(老宿主没这道网关)就
693
- * 什么都不做 —— 「桌面没卡可收」本来就是对的。
685
+ * 桌面那一发与手机作答同时进行,手机先答时按请求对象撤回桌面卡,与提问桥共用传输层的收尾
686
+ * 口子。认不到(老宿主没这道网关)就什么都不做 —— 「桌面没卡可收」本来就是对的。
694
687
  */
695
688
  function cancelForwardedCards(ctx, entry) {
696
689
  if (!entry.requestRef) return;
@@ -716,7 +709,7 @@ async function onApprovalRequest(ctx, request, next) {
716
709
  reason: typeof request.reason === 'string' ? request.reason : undefined,
717
710
  }, { unboundOnly: true });
718
711
  bindRequest(entry, request);
719
- // 在场时手机先答;最后一条手机连接离开后由 attachSession 交接给桌面。
712
+ // 桌面与手机同时出卡,谁先答用谁的;手机没回时这条请求继续挂着等人,见 holdForPhone。
720
713
  return holdForPhone(entry, next);
721
714
  }
722
715
 
@@ -818,7 +811,6 @@ module.exports = {
818
811
  attachSession,
819
812
  hasPending,
820
813
  pendingCardOf,
821
- isSessionWatched,
822
814
  setPushNotifier,
823
815
  resetForTest,
824
816
  };
@@ -1,22 +1,31 @@
1
+ // 2026-11-27:上游明确说不支持 tools 时回专用短码,手机据此降级去掉工具重试。
1
2
  // 2026-11-26:手机够不着的渠道,由电脑代发模型请求(只转发模型调用,会话仍在手机上)。
3
+ // 2026-11-26:自建渠道查不到时退回 DSH 自己的模型服务,当前 DSH 渠道也能经电脑代发。
2
4
  'use strict';
3
5
 
4
6
  /**
5
- * `POST /api/mobile/v1/channels/chat`:手机借这台电脑的手,向一条自建渠道发一次流式对话。
7
+ * `POST /api/mobile/v1/channels/chat`:手机借这台电脑的手,向一条渠道发一次流式对话。
6
8
  *
7
9
  * 为什么需要:手机上的本机 Agent 是自己直连渠道的,但渠道地址可能是 `127.0.0.1`(Ollama、
8
10
  * one-api 跑在这台电脑上)、或者只在内网可达 —— 手机拨不到。这样一条渠道不该变成「用不了」,
9
11
  * 让电脑转一手就通了。
10
12
  *
13
+ * 两条转发路,共用同一个出口:
14
+ * 1. 自建渠道(`llm-pi-ai` 的 providers):按 id 取电脑自己的地址与 Key,直接打它的
15
+ * OpenAI 兼容端点,上游的 `data:` 原样成帧回手机;
16
+ * 2. 其它渠道(DSH 当前在用的那种):电脑上没有可搬的地址与 Key,改请 DSH 自己的模型服务
17
+ * 按同一 id 跑这一次对话 —— 它认识宿主 / 插件注册的所有渠道,凭据也用电脑那份。
18
+ * 这一路把 DSH 的增量块翻成 OpenAI chunk,手机解析的代码一行不用改。
19
+ *
11
20
  * 边界:**只转发模型调用这一层**。会话记录、手机侧的工具循环仍在手机上,这条路由不建会话、
12
21
  * 不写任何日志、不碰工作区。请求体只收 OpenAI 兼容对话的四样东西(messages / model /
13
22
  * tools / 生成参数),渠道的地址与 Key 一律用宿主自己那一份,手机给什么 id 就查什么 id。
14
23
  *
15
- * 回包是 SSE:把上游的 `data:` 逐条解析出来,按同一条流式通道(`writeSse`)回给手机 ——
16
- * 协议 v2 的设备逐帧加密,与 `/session/stream` 同一套封装(见 `createFrameSealer`)。
17
- * 上游中途失败时补一帧 `{ dshError }`,手机据此把它翻成界面上的失败原因。
24
+ * 回包是 SSE:协议 v2 的设备逐帧加密,与 `/session/stream` 同一套封装(见 `createFrameSealer`)。
25
+ * 上游中途失败时补一帧 `{ dshError: { code } }`,手机据此把它翻成界面上的失败原因。
18
26
  */
19
27
 
28
+ const { randomUUID } = require('node:crypto');
20
29
  const { readJsonBody } = require('../shared/http-util');
21
30
  const { writeSse } = require('../shared/sse-write.js');
22
31
  const { customChannelWithKey } = require('./channels.js');
@@ -99,31 +108,190 @@ async function upstreamFailureOf(response) {
99
108
  return detail;
100
109
  }
101
110
 
111
+ /** 一条消息里有没有图片:DSH 那条入站要经附件服务落盘,这里没有那只桥,明确拒而不是静默丢。 */
112
+ function hasImagePart(content) {
113
+ if (!Array.isArray(content)) return false;
114
+ return content.some((part) => part && typeof part === 'object'
115
+ && (part.type === 'image' || part.type === 'image_url'));
116
+ }
117
+
118
+ function contentTextOf(content) {
119
+ if (typeof content === 'string') return content;
120
+ if (!Array.isArray(content)) return '';
121
+ let text = '';
122
+ for (const part of content) {
123
+ if (!part || typeof part !== 'object') continue;
124
+ if (part.type === 'text' && typeof part.text === 'string') text += part.text;
125
+ }
126
+ return text;
127
+ }
128
+
129
+ /**
130
+ * OpenAI 消息 → DSH 消息。形状照 DSH 自己的 OpenAI 网关那份写(`createGatewayMessage`):
131
+ * 文本是 part、assistant 的工具调用是 `tool-call`、工具结果是 `tool-result`,source 标出来源。
132
+ * 只认文本,图片明确回 `image-unsupported`(见 hasImagePart)。
133
+ */
134
+ function dshMessagesOf(raw, provider, model) {
135
+ if (!Array.isArray(raw)) return [];
136
+ const source = { kind: 'plugin:dsh-mobile-channel-proxy' };
137
+ return raw.map((item) => {
138
+ if (!item || typeof item !== 'object') throw new Error('unsupported-role');
139
+ const role = item.role;
140
+ if (hasImagePart(item.content)) throw new Error('image-unsupported');
141
+ const text = contentTextOf(item.content);
142
+ const id = randomUUID();
143
+ if (role === 'system' || role === 'user') {
144
+ return { id, role, content: [{ type: 'text', text }], source };
145
+ }
146
+ if (role === 'assistant') {
147
+ const content = text ? [{ type: 'text', text }] : [];
148
+ if (Array.isArray(item.tool_calls)) {
149
+ for (const call of item.tool_calls) {
150
+ if (!call || typeof call !== 'object') continue;
151
+ const fn = call.function && typeof call.function === 'object' ? call.function : {};
152
+ content.push({
153
+ type: 'tool-call',
154
+ id: String(call.id ?? ''),
155
+ name: String(fn.name ?? ''),
156
+ arguments: typeof fn.arguments === 'string' ? fn.arguments : '',
157
+ });
158
+ }
159
+ }
160
+ return { id, role: 'assistant', content, source: { kind: 'model', provider, model } };
161
+ }
162
+ if (role === 'tool') {
163
+ const callId = typeof item.tool_call_id === 'string' ? item.tool_call_id : '';
164
+ return {
165
+ id,
166
+ role: 'user',
167
+ content: [{ type: 'tool-result', toolCallId: callId, content: [{ type: 'text', text }] }],
168
+ source: { kind: 'tool', callId },
169
+ };
170
+ }
171
+ throw new Error('unsupported-role');
172
+ });
173
+ }
174
+
175
+ /** OpenAI tools → DSH ToolSchema;非 function 的一律丢掉,不拿去麻烦模型。 */
176
+ function dshToolsOf(raw) {
177
+ if (!Array.isArray(raw) || raw.length === 0) return undefined;
178
+ const tools = [];
179
+ for (const item of raw) {
180
+ if (!item || typeof item !== 'object' || item.type !== 'function') continue;
181
+ const fn = item.function && typeof item.function === 'object' ? item.function : null;
182
+ if (!fn || typeof fn.name !== 'string' || !fn.name) continue;
183
+ const parameters = fn.parameters && typeof fn.parameters === 'object' && !Array.isArray(fn.parameters)
184
+ ? fn.parameters : {};
185
+ tools.push({ name: fn.name, description: typeof fn.description === 'string' ? fn.description : '', parameters });
186
+ }
187
+ return tools.length > 0 ? tools : undefined;
188
+ }
189
+
190
+ /** DSH 的失败块 → 手机认得的短码。带上游状态码的优先,模型名写错这种确定性失败别让他重试。 */
191
+ function dshErrorCodeOf(reason) {
192
+ const failure = reason && reason.failure && typeof reason.failure === 'object' ? reason.failure : {};
193
+ const status = Number(failure.status);
194
+ // 只有明确提到 tools / function / tool_calls 的 400 才算「不支持工具」;鉴权、限流、渠道缺失各走各的短码。
195
+ const detail = [failure.message, failure.body, failure.detail]
196
+ .flatMap((value) => typeof value === 'string' ? [value] : value && typeof value === 'object' ? [JSON.stringify(value)] : [])
197
+ .join(' ')
198
+ .toLowerCase();
199
+ if (status === 400 && /\btools?\b|\bfunctions?\b|tool_calls/.test(detail)) return 'tools-unsupported';
200
+ if (status === 401 || status === 403) return 'http-401';
201
+ if (status === 429) return 'http-429';
202
+ if (status === 404) return 'http-404';
203
+ if (reason && reason.kind === 'aborted') return 'aborted';
204
+ return 'host-model-failed';
205
+ }
206
+
207
+ /**
208
+ * DSH 的增量块 → OpenAI chunk。手机那条解析路只认 OpenAI 形状,这里翻成同一份,
209
+ * `client.ts` 不必为「经电脑转发」再分一套。失败块单独返回 `dshError`,不混进正文。
210
+ */
211
+ function openAiChunkOf(chunk, model, id) {
212
+ if (!chunk || typeof chunk !== 'object') return null;
213
+ let delta = null;
214
+ let finishReason = null;
215
+ switch (chunk.type) {
216
+ case 'text-delta': delta = { content: chunk.text }; break;
217
+ case 'reasoning-delta': delta = { reasoning_content: chunk.text }; break;
218
+ case 'tool-call-delta':
219
+ delta = {
220
+ tool_calls: [{
221
+ index: chunk.index,
222
+ id: String(chunk.id ?? ''),
223
+ type: 'function',
224
+ function: {
225
+ ...(chunk.name === undefined ? {} : { name: chunk.name }),
226
+ arguments: typeof chunk.argumentsDelta === 'string' ? chunk.argumentsDelta : '',
227
+ },
228
+ }],
229
+ };
230
+ break;
231
+ case 'finish': {
232
+ const kind = chunk.reason && chunk.reason.kind;
233
+ if (kind === 'error' || kind === 'aborted') {
234
+ return { dshError: { code: dshErrorCodeOf(chunk.reason) } };
235
+ }
236
+ delta = {};
237
+ finishReason = kind === 'tool-calls' ? 'tool_calls' : kind === 'max-tokens' ? 'length' : 'stop';
238
+ break;
239
+ }
240
+ case 'usage':
241
+ case 'block-start':
242
+ case 'block-end':
243
+ return null;
244
+ default:
245
+ return null;
246
+ }
247
+ return {
248
+ id,
249
+ object: 'chat.completion.chunk',
250
+ model,
251
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
252
+ };
253
+ }
254
+
255
+ /** DSH 自己的模型服务:同进程直查,不写进 inject;缺了只让这一路回 503。 */
256
+ function hostLlmOf(ctx) {
257
+ try {
258
+ if (!ctx || typeof ctx.get !== 'function') return null;
259
+ return ctx.get('llm') || null;
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+
265
+ function jsonError(res, status, error) {
266
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
267
+ res.end(JSON.stringify({ ok: false, error }));
268
+ }
269
+
102
270
  /**
103
271
  * POST /api/mobile/v1/channels/chat(token)
104
272
  * { id, model, messages, tools?, toolChoice?, maxTokens?, temperature? }
105
- * → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code, status? } }`。
273
+ * → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code } }`。
106
274
  */
107
275
  async function handleChannelChat(ctx, req, res) {
108
276
  const body = await readJsonBody(req, MAX_BODY_BYTES);
109
277
  const id = body && typeof body.id === 'string' ? body.id.trim() : '';
110
278
  const model = body && typeof body.model === 'string' ? body.model.trim() : '';
111
279
  if (!id || !model) {
112
- res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
113
- res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '需要渠道 id 与模型' } }));
280
+ jsonError(res, 400, { code: 'bad-request', message: '需要渠道 id 与模型' });
114
281
  return;
115
282
  }
116
283
 
117
284
  const found = await customChannelWithKey(ctx, id);
118
- if (found.error) {
119
- res.writeHead(found.status || 400, { 'content-type': 'application/json; charset=utf-8' });
120
- res.end(JSON.stringify({ ok: false, error: found.error }));
285
+ // 只有「电脑上没有这条自建渠道」才退回 DSH 自己的模型服务;查配置本身失败要如实报,
286
+ // 不能把宿主故障伪装成「换条路再试」。
287
+ const viaDsh = !!(found.error && found.error.code === 'channel-not-found');
288
+ if (found.error && !viaDsh) {
289
+ jsonError(res, found.status || 400, found.error);
121
290
  return;
122
291
  }
123
- const url = chatCompletionUrlOf(found.channel.baseUrl);
124
- if (url === '') {
125
- res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
126
- res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '这条渠道没有可用地址' } }));
292
+ const url = viaDsh ? '' : chatCompletionUrlOf(found.channel.baseUrl);
293
+ if (!viaDsh && url === '') {
294
+ jsonError(res, 400, { code: 'bad-request', message: '这条渠道没有可用地址' });
127
295
  return;
128
296
  }
129
297
 
@@ -133,7 +301,35 @@ async function handleChannelChat(ctx, req, res) {
133
301
  const timer = setTimeout(closed, UPSTREAM_IDLE_MS);
134
302
 
135
303
  let upstream;
136
- try {
304
+ let llm = null;
305
+ let dshOptions = null;
306
+ const requestId = `chatcmpl-${randomUUID()}`;
307
+ if (viaDsh) {
308
+ llm = hostLlmOf(ctx);
309
+ if (!llm || typeof llm.stream !== 'function') {
310
+ clearTimeout(timer);
311
+ res.off('close', closed);
312
+ jsonError(res, 503, { code: 'host-llm-unavailable', message: '这台电脑上的模型服务不可用' });
313
+ return;
314
+ }
315
+ try {
316
+ dshOptions = {
317
+ provider: id,
318
+ model,
319
+ messages: dshMessagesOf(body.messages, id, model),
320
+ signal: controller.signal,
321
+ };
322
+ const tools = dshToolsOf(body.tools);
323
+ if (tools) dshOptions.tools = tools;
324
+ const maxTokens = Number(body && body.maxTokens);
325
+ if (Number.isFinite(maxTokens) && maxTokens > 0) dshOptions.maxTokens = Math.trunc(maxTokens);
326
+ } catch (error) {
327
+ clearTimeout(timer);
328
+ res.off('close', closed);
329
+ jsonError(res, 400, { code: String(error && error.message).slice(0, 80), message: '这条对话没法转给 DSH' });
330
+ return;
331
+ }
332
+ } else try {
137
333
  upstream = await fetch(url, {
138
334
  method: 'POST',
139
335
  signal: controller.signal,
@@ -147,17 +343,15 @@ async function handleChannelChat(ctx, req, res) {
147
343
  } catch (error) {
148
344
  clearTimeout(timer);
149
345
  res.off('close', closed);
150
- res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' });
151
- res.end(JSON.stringify({ ok: false, error: { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) } }));
346
+ jsonError(res, 502, { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) });
152
347
  return;
153
348
  }
154
349
 
155
- if (!upstream.ok || !upstream.body) {
350
+ if (!viaDsh && (!upstream.ok || !upstream.body)) {
156
351
  const detail = await upstreamFailureOf(upstream);
157
352
  clearTimeout(timer);
158
353
  res.off('close', closed);
159
- res.writeHead(upstream.status || 502, { 'content-type': 'application/json; charset=utf-8' });
160
- res.end(JSON.stringify({ ok: false, error: { code: 'upstream-failed', message: detail } }));
354
+ jsonError(res, upstream.status || 502, { code: 'upstream-failed', message: detail });
161
355
  return;
162
356
  }
163
357
 
@@ -174,26 +368,33 @@ async function handleChannelChat(ctx, req, res) {
174
368
  });
175
369
  res.write(': connected\n\n');
176
370
 
177
- const pump = createRecordSplitter((record) => {
178
- const data = dataOfRecord(record);
179
- if (data === null || data === '[DONE]') return;
180
- let payload;
181
- try {
182
- payload = JSON.parse(data);
183
- } catch {
184
- return; // 半截 / 非 JSON 的 data 直接跳过,别把坏帧塞给手机
185
- }
186
- writeSse(res, payload, { sealFrame });
187
- });
188
-
189
371
  try {
190
- const decoder = new TextDecoder('utf-8');
191
- for await (const chunk of upstream.body) {
192
- if (controller.signal.aborted || res.writableEnded) break;
193
- pump(decoder.decode(chunk, { stream: true }));
372
+ if (viaDsh) {
373
+ for await (const chunk of llm.stream(dshOptions)) {
374
+ if (controller.signal.aborted || res.writableEnded) break;
375
+ const frame = openAiChunkOf(chunk, model, requestId);
376
+ if (frame) writeSse(res, frame, { sealFrame });
377
+ }
378
+ } else {
379
+ const pump = createRecordSplitter((record) => {
380
+ const data = dataOfRecord(record);
381
+ if (data === null || data === '[DONE]') return;
382
+ let payload;
383
+ try {
384
+ payload = JSON.parse(data);
385
+ } catch {
386
+ return; // 半截 / 非 JSON 的 data 直接跳过,别把坏帧塞给手机
387
+ }
388
+ writeSse(res, payload, { sealFrame });
389
+ });
390
+ const decoder = new TextDecoder('utf-8');
391
+ for await (const chunk of upstream.body) {
392
+ if (controller.signal.aborted || res.writableEnded) break;
393
+ pump(decoder.decode(chunk, { stream: true }));
394
+ }
194
395
  }
195
396
  } catch {
196
- if (!res.writableEnded) writeSse(res, { dshError: { code: 'upstream-interrupted' } }, { sealFrame });
397
+ if (!res.writableEnded) writeSse(res, { dshError: { code: 'host-model-failed' } }, { sealFrame });
197
398
  } finally {
198
399
  clearTimeout(timer);
199
400
  res.off('close', closed);
@@ -201,4 +402,12 @@ async function handleChannelChat(ctx, req, res) {
201
402
  }
202
403
  }
203
404
 
204
- module.exports = { handleChannelChat, chatCompletionUrlOf, upstreamBodyOf, createRecordSplitter, dataOfRecord };
405
+ module.exports = {
406
+ handleChannelChat,
407
+ chatCompletionUrlOf,
408
+ upstreamBodyOf,
409
+ createRecordSplitter,
410
+ dshMessagesOf,
411
+ dshToolsOf,
412
+ openAiChunkOf,
413
+ };