dsh-mobile-plugin 0.5.134 → 0.5.136

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.
@@ -1,412 +0,0 @@
1
- // 2026-11-27:上游明确说不支持 tools 时回专用短码,手机据此降级去掉工具重试。
2
- // 2026-11-26:手机够不着的渠道,由电脑代发模型请求(只转发模型调用,会话仍在手机上)。
3
- // 2026-11-26:自建渠道查不到时退回 DSH 自己的模型服务,当前 DSH 渠道也能经电脑代发。
4
- 'use strict';
5
-
6
- /**
7
- * `POST /api/mobile/v1/channels/chat`:手机借这台电脑的手,向一条渠道发一次流式对话。
8
- *
9
- * 为什么需要:手机上的本机 Agent 是自己直连渠道的,但渠道地址可能是 `127.0.0.1`(Ollama、
10
- * one-api 跑在这台电脑上)、或者只在内网可达 —— 手机拨不到。这样一条渠道不该变成「用不了」,
11
- * 让电脑转一手就通了。
12
- *
13
- * 两条转发路,共用同一个出口:
14
- * 1. 自建渠道(`llm-pi-ai` 的 providers):按 id 取电脑自己的地址,直接打它的
15
- * OpenAI 兼容端点,上游的 `data:` 原样成帧回手机;插件不读 Key,鉴权由上游自己那侧处理;
16
- * 2. 其它渠道(DSH 当前在用的那种):电脑上没有可搬的地址,改请 DSH 自己的模型服务
17
- * 按同一 id 跑这一次对话 —— 它认识宿主 / 插件注册的所有渠道,凭据也用电脑那份。
18
- * 这一路把 DSH 的增量块翻成 OpenAI chunk,手机解析的代码一行不用改。
19
- *
20
- * 边界:**只转发模型调用这一层**。会话记录、手机侧的工具循环仍在手机上,这条路由不建会话、
21
- * 不写任何日志、不碰工作区。请求体只收 OpenAI 兼容对话的四样东西(messages / model /
22
- * tools / 生成参数),渠道的地址与 Key 一律用宿主自己那一份,手机给什么 id 就查什么 id。
23
- *
24
- * 回包是 SSE:协议 v2 的设备逐帧加密,与 `/session/stream` 同一套封装(见 `createFrameSealer`)。
25
- * 上游中途失败时补一帧 `{ dshError: { code } }`,手机据此把它翻成界面上的失败原因。
26
- */
27
-
28
- const { randomUUID } = require('node:crypto');
29
- const { readJsonBody } = require('../shared/http-util');
30
- const { writeSse } = require('../shared/sse-write.js');
31
- const { customChannelById } = require('./channels.js');
32
- const { createFrameSealer } = require('./stream.js');
33
-
34
- /** 请求体上限:一条带图带文件的对话也远小于这个数。 */
35
- const MAX_BODY_BYTES = 4 * 1024 * 1024;
36
- /** 上游单次连接的超时:模型第一个字常常要等十几秒,给足。 */
37
- const UPSTREAM_IDLE_MS = 120_000;
38
-
39
- /** 渠道地址 → chat/completions 地址。规则与桌面端、手机端同一份:写了 `/v1` 就不再补。 */
40
- function chatCompletionUrlOf(baseUrl) {
41
- const root = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
42
- if (root === '') return '';
43
- return root.endsWith('/v1') ? `${root}/chat/completions` : `${root}/v1/chat/completions`;
44
- }
45
-
46
- /**
47
- * 手机报上来的对话原样交给渠道:只放行 OpenAI 兼容的那几个字段,其余一律不转发。
48
- *
49
- * 不把整个 body 透传是有意的:透传等于让手机决定这次请求的地址、Key、流开关,
50
- * 那就不再是「借电脑的手发一次对话」了。
51
- */
52
- function upstreamBodyOf(body, model) {
53
- const pick = (key) => (body && typeof body === 'object' ? body[key] : undefined);
54
- const messages = pick('messages');
55
- const out = {
56
- model,
57
- stream: true,
58
- messages: Array.isArray(messages) ? messages : [],
59
- };
60
- const tools = pick('tools');
61
- if (Array.isArray(tools) && tools.length > 0) {
62
- out.tools = tools;
63
- out.tool_choice = pick('toolChoice') === 'none' ? 'none' : 'auto';
64
- }
65
- const maxTokens = Number(pick('maxTokens'));
66
- if (Number.isFinite(maxTokens) && maxTokens > 0) out.max_tokens = Math.trunc(maxTokens);
67
- const temperature = Number(pick('temperature'));
68
- if (Number.isFinite(temperature) && temperature >= 0) out.temperature = temperature;
69
- return out;
70
- }
71
-
72
- /** 一条 SSE 记录里的 `data:` 正文;不是 data 行就回 null(注释行、event 行都不算)。 */
73
- function dataOfRecord(record) {
74
- const lines = record.split('\n');
75
- const parts = [];
76
- for (const line of lines) {
77
- if (!line.startsWith('data:')) continue;
78
- parts.push(line.slice(5).replace(/^ /, ''));
79
- }
80
- return parts.length > 0 ? parts.join('\n') : null;
81
- }
82
-
83
- /**
84
- * 把上游的字节流切成一条条 SSE 记录(空行分隔),逐条交出去。
85
- *
86
- * 只认 `\n\n`:OpenAI 兼容端点用的都是这个分隔符,`\r\n\r\n` 顺带兼容一下。
87
- */
88
- function createRecordSplitter(onRecord) {
89
- let buffer = '';
90
- return (chunk) => {
91
- buffer += chunk;
92
- for (;;) {
93
- const at = buffer.search(/\r?\n\r?\n/);
94
- if (at < 0) return;
95
- const record = buffer.slice(0, at);
96
- buffer = buffer.slice(at + (buffer[at] === '\r' ? 4 : 2));
97
- if (record.trim() !== '') onRecord(record);
98
- }
99
- };
100
- }
101
-
102
- /** 上游回了一个非 2xx:把状态码原样带给手机,界面按同一套错误分类翻。 */
103
- async function upstreamFailureOf(response) {
104
- let detail = '';
105
- try {
106
- detail = (await response.text()).slice(0, 400);
107
- } catch { /* 读不到正文就只报状态码 */ }
108
- return detail;
109
- }
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
-
270
- /**
271
- * POST /api/mobile/v1/channels/chat(token)
272
- * { id, model, messages, tools?, toolChoice?, maxTokens?, temperature? }
273
- * → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code } }`。
274
- */
275
- async function handleChannelChat(ctx, req, res) {
276
- const body = await readJsonBody(req, MAX_BODY_BYTES);
277
- const id = body && typeof body.id === 'string' ? body.id.trim() : '';
278
- const model = body && typeof body.model === 'string' ? body.model.trim() : '';
279
- if (!id || !model) {
280
- jsonError(res, 400, { code: 'bad-request', message: '需要渠道 id 与模型' });
281
- return;
282
- }
283
-
284
- const found = await customChannelById(ctx, id);
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);
290
- return;
291
- }
292
- const url = viaDsh ? '' : chatCompletionUrlOf(found.channel.baseUrl);
293
- if (!viaDsh && url === '') {
294
- jsonError(res, 400, { code: 'bad-request', message: '这条渠道没有可用地址' });
295
- return;
296
- }
297
-
298
- const controller = new AbortController();
299
- const closed = () => controller.abort();
300
- res.on('close', closed);
301
- const timer = setTimeout(closed, UPSTREAM_IDLE_MS);
302
-
303
- let upstream;
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 {
333
- upstream = await fetch(url, {
334
- method: 'POST',
335
- signal: controller.signal,
336
- headers: {
337
- 'content-type': 'application/json',
338
- accept: 'text/event-stream',
339
- },
340
- body: JSON.stringify(upstreamBodyOf(body, model)),
341
- });
342
- } catch (error) {
343
- clearTimeout(timer);
344
- res.off('close', closed);
345
- jsonError(res, 502, { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) });
346
- return;
347
- }
348
-
349
- if (!viaDsh && (!upstream.ok || !upstream.body)) {
350
- const detail = await upstreamFailureOf(upstream);
351
- clearTimeout(timer);
352
- res.off('close', closed);
353
- jsonError(res, upstream.status || 502, { code: 'upstream-failed', message: detail });
354
- return;
355
- }
356
-
357
- // 协议 v2 的设备逐帧加密:封装器由请求那一步挂上的解封信息生成(见 createFrameSealer)。
358
- // 要在 writeHead 之前算好,`x-dsh-proto` 只能在头发出去之前声明。
359
- const sealFrame = createFrameSealer(req);
360
- res.writeHead(200, {
361
- 'content-type': 'text/event-stream; charset=utf-8',
362
- 'cache-control': 'no-cache',
363
- connection: 'keep-alive',
364
- 'x-accel-buffering': 'no',
365
- 'content-encoding': 'identity',
366
- ...(sealFrame ? { 'x-dsh-proto': '2' } : {}),
367
- });
368
- res.write(': connected\n\n');
369
-
370
- try {
371
- if (viaDsh) {
372
- for await (const chunk of llm.stream(dshOptions)) {
373
- if (controller.signal.aborted || res.writableEnded) break;
374
- const frame = openAiChunkOf(chunk, model, requestId);
375
- if (frame) writeSse(res, frame, { sealFrame });
376
- }
377
- } else {
378
- const pump = createRecordSplitter((record) => {
379
- const data = dataOfRecord(record);
380
- if (data === null || data === '[DONE]') return;
381
- let payload;
382
- try {
383
- payload = JSON.parse(data);
384
- } catch {
385
- return; // 半截 / 非 JSON 的 data 直接跳过,别把坏帧塞给手机
386
- }
387
- writeSse(res, payload, { sealFrame });
388
- });
389
- const decoder = new TextDecoder('utf-8');
390
- for await (const chunk of upstream.body) {
391
- if (controller.signal.aborted || res.writableEnded) break;
392
- pump(decoder.decode(chunk, { stream: true }));
393
- }
394
- }
395
- } catch {
396
- if (!res.writableEnded) writeSse(res, { dshError: { code: 'host-model-failed' } }, { sealFrame });
397
- } finally {
398
- clearTimeout(timer);
399
- res.off('close', closed);
400
- try { res.end(); } catch { /* 已关闭 */ }
401
- }
402
- }
403
-
404
- module.exports = {
405
- handleChannelChat,
406
- chatCompletionUrlOf,
407
- upstreamBodyOf,
408
- createRecordSplitter,
409
- dshMessagesOf,
410
- dshToolsOf,
411
- openAiChunkOf,
412
- };