dsh-mobile-plugin 0.5.124 → 0.5.125
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 +8 -6
- package/lib/mobile/approvals.js +39 -47
- package/lib/mobile/channel-proxy.js +240 -38
- package/lib/mobile/channels.js +99 -4
- package/lib/mobile/feedback.js +17 -8
- package/lib/mobile/relay-control.js +3 -2
- package/lib/relay/control.js +5 -4
- package/package.json +14 -15
package/lib/impl.js
CHANGED
|
@@ -496,14 +496,16 @@ function apply(ctx) {
|
|
|
496
496
|
}
|
|
497
497
|
return undefined
|
|
498
498
|
}, `${name}: workspace tool`)
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
499
|
+
// 反馈工具:设备身份从凭据库取(手机每条请求都上报,宿主写回记录),提交到分发平台。
|
|
500
|
+
// hostVersion 从同进程的宿主版本台账取(host.js 启动时写入),作为 Harness 版本上报。
|
|
501
|
+
// 用 `ctx.inject` 挂一个等 `tools` 的子作用域,而不是直接 `ctx.get('tools')` 注册:注册记在
|
|
502
|
+
// 这个子 fiber 名下,热重载换代时随旧代卸掉。直接注册只记在共享的服务上,下一次重载会被
|
|
503
|
+
// 判「dsh_feedback 已经注册过」而整代装载失败。
|
|
504
|
+
mount('反馈工具', () => ctx.inject(['tools'], (scoped) => {
|
|
505
|
+
try { installFeedback(scoped, { credentials, instanceId: () => state.instanceId, hostVersion: () => readCapabilityReport()?.runtimeVersion || '' }) } catch (error) {
|
|
503
506
|
if (!String(error).includes('without inject')) throw error
|
|
504
507
|
}
|
|
505
|
-
|
|
506
|
-
}, `${name}: feedback tool`)
|
|
508
|
+
}))
|
|
507
509
|
mount('统计采集', () => ctx.effect(() => statsScheduler.start(ctx), `${name}: stats collect`))
|
|
508
510
|
mount('过程播报', () => ctx.effect(() => installNarration(ctx), `${name}: process narration`))
|
|
509
511
|
|
package/lib/mobile/approvals.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
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
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
if (
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
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
|
-
//
|
|
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,30 @@
|
|
|
1
1
|
// 2026-11-26:手机够不着的渠道,由电脑代发模型请求(只转发模型调用,会话仍在手机上)。
|
|
2
|
+
// 2026-11-26:自建渠道查不到时退回 DSH 自己的模型服务,当前 DSH 渠道也能经电脑代发。
|
|
2
3
|
'use strict';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
|
-
* `POST /api/mobile/v1/channels/chat
|
|
6
|
+
* `POST /api/mobile/v1/channels/chat`:手机借这台电脑的手,向一条渠道发一次流式对话。
|
|
6
7
|
*
|
|
7
8
|
* 为什么需要:手机上的本机 Agent 是自己直连渠道的,但渠道地址可能是 `127.0.0.1`(Ollama、
|
|
8
9
|
* one-api 跑在这台电脑上)、或者只在内网可达 —— 手机拨不到。这样一条渠道不该变成「用不了」,
|
|
9
10
|
* 让电脑转一手就通了。
|
|
10
11
|
*
|
|
12
|
+
* 两条转发路,共用同一个出口:
|
|
13
|
+
* 1. 自建渠道(`llm-pi-ai` 的 providers):按 id 取电脑自己的地址与 Key,直接打它的
|
|
14
|
+
* OpenAI 兼容端点,上游的 `data:` 原样成帧回手机;
|
|
15
|
+
* 2. 其它渠道(DSH 当前在用的那种):电脑上没有可搬的地址与 Key,改请 DSH 自己的模型服务
|
|
16
|
+
* 按同一 id 跑这一次对话 —— 它认识宿主 / 插件注册的所有渠道,凭据也用电脑那份。
|
|
17
|
+
* 这一路把 DSH 的增量块翻成 OpenAI chunk,手机解析的代码一行不用改。
|
|
18
|
+
*
|
|
11
19
|
* 边界:**只转发模型调用这一层**。会话记录、手机侧的工具循环仍在手机上,这条路由不建会话、
|
|
12
20
|
* 不写任何日志、不碰工作区。请求体只收 OpenAI 兼容对话的四样东西(messages / model /
|
|
13
21
|
* tools / 生成参数),渠道的地址与 Key 一律用宿主自己那一份,手机给什么 id 就查什么 id。
|
|
14
22
|
*
|
|
15
|
-
* 回包是 SSE
|
|
16
|
-
*
|
|
17
|
-
* 上游中途失败时补一帧 `{ dshError }`,手机据此把它翻成界面上的失败原因。
|
|
23
|
+
* 回包是 SSE:协议 v2 的设备逐帧加密,与 `/session/stream` 同一套封装(见 `createFrameSealer`)。
|
|
24
|
+
* 上游中途失败时补一帧 `{ dshError: { code } }`,手机据此把它翻成界面上的失败原因。
|
|
18
25
|
*/
|
|
19
26
|
|
|
27
|
+
const { randomUUID } = require('node:crypto');
|
|
20
28
|
const { readJsonBody } = require('../shared/http-util');
|
|
21
29
|
const { writeSse } = require('../shared/sse-write.js');
|
|
22
30
|
const { customChannelWithKey } = require('./channels.js');
|
|
@@ -99,31 +107,184 @@ async function upstreamFailureOf(response) {
|
|
|
99
107
|
return detail;
|
|
100
108
|
}
|
|
101
109
|
|
|
110
|
+
/** 一条消息里有没有图片:DSH 那条入站要经附件服务落盘,这里没有那只桥,明确拒而不是静默丢。 */
|
|
111
|
+
function hasImagePart(content) {
|
|
112
|
+
if (!Array.isArray(content)) return false;
|
|
113
|
+
return content.some((part) => part && typeof part === 'object'
|
|
114
|
+
&& (part.type === 'image' || part.type === 'image_url'));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function contentTextOf(content) {
|
|
118
|
+
if (typeof content === 'string') return content;
|
|
119
|
+
if (!Array.isArray(content)) return '';
|
|
120
|
+
let text = '';
|
|
121
|
+
for (const part of content) {
|
|
122
|
+
if (!part || typeof part !== 'object') continue;
|
|
123
|
+
if (part.type === 'text' && typeof part.text === 'string') text += part.text;
|
|
124
|
+
}
|
|
125
|
+
return text;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* OpenAI 消息 → DSH 消息。形状照 DSH 自己的 OpenAI 网关那份写(`createGatewayMessage`):
|
|
130
|
+
* 文本是 part、assistant 的工具调用是 `tool-call`、工具结果是 `tool-result`,source 标出来源。
|
|
131
|
+
* 只认文本,图片明确回 `image-unsupported`(见 hasImagePart)。
|
|
132
|
+
*/
|
|
133
|
+
function dshMessagesOf(raw, provider, model) {
|
|
134
|
+
if (!Array.isArray(raw)) return [];
|
|
135
|
+
const source = { kind: 'plugin:dsh-mobile-channel-proxy' };
|
|
136
|
+
return raw.map((item) => {
|
|
137
|
+
if (!item || typeof item !== 'object') throw new Error('unsupported-role');
|
|
138
|
+
const role = item.role;
|
|
139
|
+
if (hasImagePart(item.content)) throw new Error('image-unsupported');
|
|
140
|
+
const text = contentTextOf(item.content);
|
|
141
|
+
const id = randomUUID();
|
|
142
|
+
if (role === 'system' || role === 'user') {
|
|
143
|
+
return { id, role, content: [{ type: 'text', text }], source };
|
|
144
|
+
}
|
|
145
|
+
if (role === 'assistant') {
|
|
146
|
+
const content = text ? [{ type: 'text', text }] : [];
|
|
147
|
+
if (Array.isArray(item.tool_calls)) {
|
|
148
|
+
for (const call of item.tool_calls) {
|
|
149
|
+
if (!call || typeof call !== 'object') continue;
|
|
150
|
+
const fn = call.function && typeof call.function === 'object' ? call.function : {};
|
|
151
|
+
content.push({
|
|
152
|
+
type: 'tool-call',
|
|
153
|
+
id: String(call.id ?? ''),
|
|
154
|
+
name: String(fn.name ?? ''),
|
|
155
|
+
arguments: typeof fn.arguments === 'string' ? fn.arguments : '',
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { id, role: 'assistant', content, source: { kind: 'model', provider, model } };
|
|
160
|
+
}
|
|
161
|
+
if (role === 'tool') {
|
|
162
|
+
const callId = typeof item.tool_call_id === 'string' ? item.tool_call_id : '';
|
|
163
|
+
return {
|
|
164
|
+
id,
|
|
165
|
+
role: 'user',
|
|
166
|
+
content: [{ type: 'tool-result', toolCallId: callId, content: [{ type: 'text', text }] }],
|
|
167
|
+
source: { kind: 'tool', callId },
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
throw new Error('unsupported-role');
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** OpenAI tools → DSH ToolSchema;非 function 的一律丢掉,不拿去麻烦模型。 */
|
|
175
|
+
function dshToolsOf(raw) {
|
|
176
|
+
if (!Array.isArray(raw) || raw.length === 0) return undefined;
|
|
177
|
+
const tools = [];
|
|
178
|
+
for (const item of raw) {
|
|
179
|
+
if (!item || typeof item !== 'object' || item.type !== 'function') continue;
|
|
180
|
+
const fn = item.function && typeof item.function === 'object' ? item.function : null;
|
|
181
|
+
if (!fn || typeof fn.name !== 'string' || !fn.name) continue;
|
|
182
|
+
const parameters = fn.parameters && typeof fn.parameters === 'object' && !Array.isArray(fn.parameters)
|
|
183
|
+
? fn.parameters : {};
|
|
184
|
+
tools.push({ name: fn.name, description: typeof fn.description === 'string' ? fn.description : '', parameters });
|
|
185
|
+
}
|
|
186
|
+
return tools.length > 0 ? tools : undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** DSH 的失败块 → 手机认得的短码。带上游状态码的优先,模型名写错这种确定性失败别让他重试。 */
|
|
190
|
+
function dshErrorCodeOf(reason) {
|
|
191
|
+
const failure = reason && reason.failure && typeof reason.failure === 'object' ? reason.failure : {};
|
|
192
|
+
const status = Number(failure.status);
|
|
193
|
+
if (status === 401 || status === 403) return 'http-401';
|
|
194
|
+
if (status === 429) return 'http-429';
|
|
195
|
+
if (status === 404) return 'http-404';
|
|
196
|
+
if (reason && reason.kind === 'aborted') return 'aborted';
|
|
197
|
+
return 'host-model-failed';
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* DSH 的增量块 → OpenAI chunk。手机那条解析路只认 OpenAI 形状,这里翻成同一份,
|
|
202
|
+
* `client.ts` 不必为「经电脑转发」再分一套。失败块单独返回 `dshError`,不混进正文。
|
|
203
|
+
*/
|
|
204
|
+
function openAiChunkOf(chunk, model, id) {
|
|
205
|
+
if (!chunk || typeof chunk !== 'object') return null;
|
|
206
|
+
let delta = null;
|
|
207
|
+
let finishReason = null;
|
|
208
|
+
switch (chunk.type) {
|
|
209
|
+
case 'text-delta': delta = { content: chunk.text }; break;
|
|
210
|
+
case 'reasoning-delta': delta = { reasoning_content: chunk.text }; break;
|
|
211
|
+
case 'tool-call-delta':
|
|
212
|
+
delta = {
|
|
213
|
+
tool_calls: [{
|
|
214
|
+
index: chunk.index,
|
|
215
|
+
id: String(chunk.id ?? ''),
|
|
216
|
+
type: 'function',
|
|
217
|
+
function: {
|
|
218
|
+
...(chunk.name === undefined ? {} : { name: chunk.name }),
|
|
219
|
+
arguments: typeof chunk.argumentsDelta === 'string' ? chunk.argumentsDelta : '',
|
|
220
|
+
},
|
|
221
|
+
}],
|
|
222
|
+
};
|
|
223
|
+
break;
|
|
224
|
+
case 'finish': {
|
|
225
|
+
const kind = chunk.reason && chunk.reason.kind;
|
|
226
|
+
if (kind === 'error' || kind === 'aborted') {
|
|
227
|
+
return { dshError: { code: dshErrorCodeOf(chunk.reason) } };
|
|
228
|
+
}
|
|
229
|
+
delta = {};
|
|
230
|
+
finishReason = kind === 'tool-calls' ? 'tool_calls' : kind === 'max-tokens' ? 'length' : 'stop';
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
case 'usage':
|
|
234
|
+
case 'block-start':
|
|
235
|
+
case 'block-end':
|
|
236
|
+
return null;
|
|
237
|
+
default:
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
id,
|
|
242
|
+
object: 'chat.completion.chunk',
|
|
243
|
+
model,
|
|
244
|
+
choices: [{ index: 0, delta, finish_reason: finishReason }],
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** DSH 自己的模型服务:同进程直查,不写进 inject;缺了只让这一路回 503。 */
|
|
249
|
+
function hostLlmOf(ctx) {
|
|
250
|
+
try {
|
|
251
|
+
if (!ctx || typeof ctx.get !== 'function') return null;
|
|
252
|
+
return ctx.get('llm') || null;
|
|
253
|
+
} catch {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function jsonError(res, status, error) {
|
|
259
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
|
|
260
|
+
res.end(JSON.stringify({ ok: false, error }));
|
|
261
|
+
}
|
|
262
|
+
|
|
102
263
|
/**
|
|
103
264
|
* POST /api/mobile/v1/channels/chat(token)
|
|
104
265
|
* { id, model, messages, tools?, toolChoice?, maxTokens?, temperature? }
|
|
105
|
-
* → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code
|
|
266
|
+
* → SSE:上游的每条 `data:` 原样成帧;失败时补一帧 `{ dshError: { code } }`。
|
|
106
267
|
*/
|
|
107
268
|
async function handleChannelChat(ctx, req, res) {
|
|
108
269
|
const body = await readJsonBody(req, MAX_BODY_BYTES);
|
|
109
270
|
const id = body && typeof body.id === 'string' ? body.id.trim() : '';
|
|
110
271
|
const model = body && typeof body.model === 'string' ? body.model.trim() : '';
|
|
111
272
|
if (!id || !model) {
|
|
112
|
-
res
|
|
113
|
-
res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '需要渠道 id 与模型' } }));
|
|
273
|
+
jsonError(res, 400, { code: 'bad-request', message: '需要渠道 id 与模型' });
|
|
114
274
|
return;
|
|
115
275
|
}
|
|
116
276
|
|
|
117
277
|
const found = await customChannelWithKey(ctx, id);
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
278
|
+
// 只有「电脑上没有这条自建渠道」才退回 DSH 自己的模型服务;查配置本身失败要如实报,
|
|
279
|
+
// 不能把宿主故障伪装成「换条路再试」。
|
|
280
|
+
const viaDsh = !!(found.error && found.error.code === 'channel-not-found');
|
|
281
|
+
if (found.error && !viaDsh) {
|
|
282
|
+
jsonError(res, found.status || 400, found.error);
|
|
121
283
|
return;
|
|
122
284
|
}
|
|
123
|
-
const url = chatCompletionUrlOf(found.channel.baseUrl);
|
|
124
|
-
if (url === '') {
|
|
125
|
-
res
|
|
126
|
-
res.end(JSON.stringify({ ok: false, error: { code: 'bad-request', message: '这条渠道没有可用地址' } }));
|
|
285
|
+
const url = viaDsh ? '' : chatCompletionUrlOf(found.channel.baseUrl);
|
|
286
|
+
if (!viaDsh && url === '') {
|
|
287
|
+
jsonError(res, 400, { code: 'bad-request', message: '这条渠道没有可用地址' });
|
|
127
288
|
return;
|
|
128
289
|
}
|
|
129
290
|
|
|
@@ -133,7 +294,35 @@ async function handleChannelChat(ctx, req, res) {
|
|
|
133
294
|
const timer = setTimeout(closed, UPSTREAM_IDLE_MS);
|
|
134
295
|
|
|
135
296
|
let upstream;
|
|
136
|
-
|
|
297
|
+
let llm = null;
|
|
298
|
+
let dshOptions = null;
|
|
299
|
+
const requestId = `chatcmpl-${randomUUID()}`;
|
|
300
|
+
if (viaDsh) {
|
|
301
|
+
llm = hostLlmOf(ctx);
|
|
302
|
+
if (!llm || typeof llm.stream !== 'function') {
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
res.off('close', closed);
|
|
305
|
+
jsonError(res, 503, { code: 'host-llm-unavailable', message: '这台电脑上的模型服务不可用' });
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
dshOptions = {
|
|
310
|
+
provider: id,
|
|
311
|
+
model,
|
|
312
|
+
messages: dshMessagesOf(body.messages, id, model),
|
|
313
|
+
signal: controller.signal,
|
|
314
|
+
};
|
|
315
|
+
const tools = dshToolsOf(body.tools);
|
|
316
|
+
if (tools) dshOptions.tools = tools;
|
|
317
|
+
const maxTokens = Number(body && body.maxTokens);
|
|
318
|
+
if (Number.isFinite(maxTokens) && maxTokens > 0) dshOptions.maxTokens = Math.trunc(maxTokens);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
clearTimeout(timer);
|
|
321
|
+
res.off('close', closed);
|
|
322
|
+
jsonError(res, 400, { code: String(error && error.message).slice(0, 80), message: '这条对话没法转给 DSH' });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
} else try {
|
|
137
326
|
upstream = await fetch(url, {
|
|
138
327
|
method: 'POST',
|
|
139
328
|
signal: controller.signal,
|
|
@@ -147,17 +336,15 @@ async function handleChannelChat(ctx, req, res) {
|
|
|
147
336
|
} catch (error) {
|
|
148
337
|
clearTimeout(timer);
|
|
149
338
|
res.off('close', closed);
|
|
150
|
-
res
|
|
151
|
-
res.end(JSON.stringify({ ok: false, error: { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) } }));
|
|
339
|
+
jsonError(res, 502, { code: 'upstream-unreachable', message: String(error && error.message).slice(0, 200) });
|
|
152
340
|
return;
|
|
153
341
|
}
|
|
154
342
|
|
|
155
|
-
if (!upstream.ok || !upstream.body) {
|
|
343
|
+
if (!viaDsh && (!upstream.ok || !upstream.body)) {
|
|
156
344
|
const detail = await upstreamFailureOf(upstream);
|
|
157
345
|
clearTimeout(timer);
|
|
158
346
|
res.off('close', closed);
|
|
159
|
-
res
|
|
160
|
-
res.end(JSON.stringify({ ok: false, error: { code: 'upstream-failed', message: detail } }));
|
|
347
|
+
jsonError(res, upstream.status || 502, { code: 'upstream-failed', message: detail });
|
|
161
348
|
return;
|
|
162
349
|
}
|
|
163
350
|
|
|
@@ -174,26 +361,33 @@ async function handleChannelChat(ctx, req, res) {
|
|
|
174
361
|
});
|
|
175
362
|
res.write(': connected\n\n');
|
|
176
363
|
|
|
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
364
|
try {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
365
|
+
if (viaDsh) {
|
|
366
|
+
for await (const chunk of llm.stream(dshOptions)) {
|
|
367
|
+
if (controller.signal.aborted || res.writableEnded) break;
|
|
368
|
+
const frame = openAiChunkOf(chunk, model, requestId);
|
|
369
|
+
if (frame) writeSse(res, frame, { sealFrame });
|
|
370
|
+
}
|
|
371
|
+
} else {
|
|
372
|
+
const pump = createRecordSplitter((record) => {
|
|
373
|
+
const data = dataOfRecord(record);
|
|
374
|
+
if (data === null || data === '[DONE]') return;
|
|
375
|
+
let payload;
|
|
376
|
+
try {
|
|
377
|
+
payload = JSON.parse(data);
|
|
378
|
+
} catch {
|
|
379
|
+
return; // 半截 / 非 JSON 的 data 直接跳过,别把坏帧塞给手机
|
|
380
|
+
}
|
|
381
|
+
writeSse(res, payload, { sealFrame });
|
|
382
|
+
});
|
|
383
|
+
const decoder = new TextDecoder('utf-8');
|
|
384
|
+
for await (const chunk of upstream.body) {
|
|
385
|
+
if (controller.signal.aborted || res.writableEnded) break;
|
|
386
|
+
pump(decoder.decode(chunk, { stream: true }));
|
|
387
|
+
}
|
|
194
388
|
}
|
|
195
389
|
} catch {
|
|
196
|
-
if (!res.writableEnded) writeSse(res, { dshError: { code: '
|
|
390
|
+
if (!res.writableEnded) writeSse(res, { dshError: { code: 'host-model-failed' } }, { sealFrame });
|
|
197
391
|
} finally {
|
|
198
392
|
clearTimeout(timer);
|
|
199
393
|
res.off('close', closed);
|
|
@@ -201,4 +395,12 @@ async function handleChannelChat(ctx, req, res) {
|
|
|
201
395
|
}
|
|
202
396
|
}
|
|
203
397
|
|
|
204
|
-
module.exports = {
|
|
398
|
+
module.exports = {
|
|
399
|
+
handleChannelChat,
|
|
400
|
+
chatCompletionUrlOf,
|
|
401
|
+
upstreamBodyOf,
|
|
402
|
+
createRecordSplitter,
|
|
403
|
+
dshMessagesOf,
|
|
404
|
+
dshToolsOf,
|
|
405
|
+
openAiChunkOf,
|
|
406
|
+
};
|
package/lib/mobile/channels.js
CHANGED
|
@@ -27,6 +27,28 @@ const { lanInterfaces } = require('../relay/lan-network.cjs');
|
|
|
27
27
|
/** 自建渠道写在这个命名空间里;桌面端 `src/custom-channels.js` 的 PI_AI_NS 同值。 */
|
|
28
28
|
const PI_AI_NS = 'llm-pi-ai';
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* 宿主自带的官方渠道里,手机「一键导入」能直接用的那几条。
|
|
32
|
+
*
|
|
33
|
+
* 它们不在 `llm-pi-ai` 的 providers 里,没有一份可搬的 profile;但官方 DeepSeek 的 Key
|
|
34
|
+
* 与 OpenAI 兼容地址是确定的。桌面这条走 Anthropic Messages(`api.deepseek.com/anthropic`),
|
|
35
|
+
* 手机本机 Agent 只认 OpenAI 那套,所以导出时换成手机能拨的 OpenAI 兼容地址,模型名与 Key
|
|
36
|
+
* 不变。其它插件 / 宿主渠道没有确定的地址与 Key,不在这里,导出去也用不了。
|
|
37
|
+
*/
|
|
38
|
+
const IMPORTABLE_BUILTINS = new Map([
|
|
39
|
+
['deepseek-official', {
|
|
40
|
+
name: 'DeepSeek',
|
|
41
|
+
protocol: 'openai-completions',
|
|
42
|
+
baseUrl: 'https://api.deepseek.com',
|
|
43
|
+
credentialRef: 'DEEPSEEK_API_KEY',
|
|
44
|
+
}],
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
/** 这条内置渠道是否可按上面的方式导入;不是就回 null。 */
|
|
48
|
+
function importableBuiltinOf(id) {
|
|
49
|
+
return typeof id === 'string' && IMPORTABLE_BUILTINS.has(id) ? IMPORTABLE_BUILTINS.get(id) : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
30
52
|
const PROTOCOLS = ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'];
|
|
31
53
|
const GEMINI_LEVELS = ['minimal', 'low', 'medium', 'high'];
|
|
32
54
|
|
|
@@ -278,7 +300,10 @@ async function handleChannels(ctx, req, res) {
|
|
|
278
300
|
}
|
|
279
301
|
|
|
280
302
|
const customIds = Object.keys(providers);
|
|
281
|
-
const refs =
|
|
303
|
+
const refs = [...new Set([
|
|
304
|
+
...customIds.map(credentialRefOf),
|
|
305
|
+
...[...IMPORTABLE_BUILTINS.values()].map((spec) => spec.credentialRef),
|
|
306
|
+
])];
|
|
282
307
|
let keyState = {};
|
|
283
308
|
if (refs.length > 0) {
|
|
284
309
|
const described = unwrap(await ctx.apiProxy.credentials.describe({
|
|
@@ -294,12 +319,21 @@ async function handleChannels(ctx, req, res) {
|
|
|
294
319
|
if (!item || typeof item.provider !== 'string' || item.provider === '') continue;
|
|
295
320
|
// 自建路由同样会出现在 llm.providers 里,跳过——下面会以「自建」身份列一次。
|
|
296
321
|
if (Object.prototype.hasOwnProperty.call(providers, item.provider)) continue;
|
|
322
|
+
const builtin = importableBuiltinOf(item.provider);
|
|
323
|
+
const view = builtin ? keyState[builtin.credentialRef] : null;
|
|
297
324
|
channels.push({
|
|
298
325
|
id: item.provider,
|
|
299
326
|
source: 'external',
|
|
300
327
|
name: typeof item.displayName === 'string' && item.displayName.trim() ? item.displayName.trim() : item.provider,
|
|
301
328
|
active: item.active === true,
|
|
302
329
|
models: modelsOf.get(item.provider) || [],
|
|
330
|
+
// 官方内置渠道额外给手机导入页要的三格;其余插件渠道维持只读、不出现导入入口。
|
|
331
|
+
...(builtin ? {
|
|
332
|
+
importable: true,
|
|
333
|
+
protocol: builtin.protocol,
|
|
334
|
+
baseUrl: builtin.baseUrl,
|
|
335
|
+
...(view ? { keySet: view.configured === true } : {}),
|
|
336
|
+
} : {}),
|
|
303
337
|
});
|
|
304
338
|
}
|
|
305
339
|
for (const id of customIds) {
|
|
@@ -671,15 +705,76 @@ async function customChannelWithKey(ctx, id) {
|
|
|
671
705
|
return { channel, apiKey, keySet: apiKey !== '' };
|
|
672
706
|
}
|
|
673
707
|
|
|
708
|
+
/**
|
|
709
|
+
* 按 provider id 取它的模型清单(`llm.models` 的 groups)。
|
|
710
|
+
*
|
|
711
|
+
* 只给内置官方渠道的导出用:自建那批的模型在它自己的 profile 里,不走这里。
|
|
712
|
+
*/
|
|
713
|
+
async function modelsOfProvider(ctx, id) {
|
|
714
|
+
const catalog = unwrap(await ctx.apiProxy.llm.models({
|
|
715
|
+
rpcId: 'mobile',
|
|
716
|
+
method: 'llm.models',
|
|
717
|
+
payload: {},
|
|
718
|
+
}));
|
|
719
|
+
if (catalog.error) return [];
|
|
720
|
+
const groups = Array.isArray(catalog.value && catalog.value.groups) ? catalog.value.groups : [];
|
|
721
|
+
const group = groups.find((entry) => entry && entry.id === id);
|
|
722
|
+
return (Array.isArray(group && group.models) ? group.models : [])
|
|
723
|
+
.map((model) => {
|
|
724
|
+
if (!model || typeof model !== 'object') return null;
|
|
725
|
+
const modelId = typeof model.id === 'string' ? model.id.trim() : '';
|
|
726
|
+
if (!modelId) return null;
|
|
727
|
+
return { id: modelId, name: typeof model.name === 'string' && model.name.trim() ? model.name.trim() : modelId };
|
|
728
|
+
})
|
|
729
|
+
.filter(Boolean);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* 内置官方渠道 → 可导出的那一条;不是这类 id 回 `null`,是这类但宿主上没注册回 `{ error }`。
|
|
734
|
+
*
|
|
735
|
+
* Key 取不到不算失败,与自建那条同一个口径:`keySet:false`,让用户自己填一次。
|
|
736
|
+
*/
|
|
737
|
+
async function builtinImportableChannel(ctx, id) {
|
|
738
|
+
const spec = importableBuiltinOf(id);
|
|
739
|
+
if (!spec) return null;
|
|
740
|
+
const listed = unwrap(await ctx.apiProxy.llm.providers({
|
|
741
|
+
rpcId: 'mobile',
|
|
742
|
+
method: 'llm.providers',
|
|
743
|
+
payload: {},
|
|
744
|
+
}));
|
|
745
|
+
if (listed.error) return { error: listed.error };
|
|
746
|
+
const registered = Array.isArray(listed.value && listed.value.providers) ? listed.value.providers : [];
|
|
747
|
+
if (!registered.some((item) => item && item.provider === id)) {
|
|
748
|
+
return { error: { code: 'channel-not-found', message: '这台电脑上没有这条渠道' }, status: 404 };
|
|
749
|
+
}
|
|
750
|
+
const models = await modelsOfProvider(ctx, id);
|
|
751
|
+
let apiKey = '';
|
|
752
|
+
try {
|
|
753
|
+
const resolved = unwrap(await ctx.apiProxy.credentials.resolve({
|
|
754
|
+
rpcId: 'mobile',
|
|
755
|
+
method: 'credentials.resolve',
|
|
756
|
+
payload: { ref: spec.credentialRef },
|
|
757
|
+
}));
|
|
758
|
+
if (!resolved.error && resolved.value && typeof resolved.value.value === 'string') apiKey = resolved.value.value;
|
|
759
|
+
} catch { /* 宿主没注册 resolve:按「没带 Key」处理 */ }
|
|
760
|
+
return {
|
|
761
|
+
channel: { id, name: spec.name, protocol: spec.protocol, baseUrl: spec.baseUrl, models },
|
|
762
|
+
apiKey,
|
|
763
|
+
keySet: apiKey !== '',
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
|
|
674
767
|
/**
|
|
675
768
|
* POST /api/mobile/v1/channels/export(token){ id }
|
|
676
769
|
* → { ok, channel, keySet, candidates }
|
|
677
770
|
*
|
|
678
|
-
*
|
|
771
|
+
* 把电脑上这条渠道整条交给手机,给「本机 Agent 新增渠道」页的一键导入用:名字、协议、
|
|
679
772
|
* 地址、模型,以及**它的 Key**。手机本来就为手动添加的渠道在本地存着同一把 Key,这里只是
|
|
680
773
|
* 把「用户再敲一遍」换成「电脑交过来」,不是新开一类暴露。
|
|
681
774
|
*
|
|
682
|
-
*
|
|
775
|
+
* 两类可导:`llm-pi-ai` 里的自建渠道,以及宿主自带的官方 DeepSeek(映射成 OpenAI 兼容
|
|
776
|
+
* 地址,见 `IMPORTABLE_BUILTINS`)。其它插件 / 宿主注册的提供方没有可搬的地址与 Key,
|
|
777
|
+
* 一律 404。
|
|
683
778
|
* Key 只在用户点名这一条时取一次,取不到(宿主没注册 resolve、凭据是环境变量提供的)就
|
|
684
779
|
* 如实回 keySet:false,由手机让用户自己填,不把失败报成整条导入失败。
|
|
685
780
|
*
|
|
@@ -692,7 +787,7 @@ async function handleChannelExport(ctx, req, res) {
|
|
|
692
787
|
if (!CHANNEL_ID_PATTERN.test(id)) {
|
|
693
788
|
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要渠道 id' } });
|
|
694
789
|
}
|
|
695
|
-
const found = await customChannelWithKey(ctx, id);
|
|
790
|
+
const found = (await builtinImportableChannel(ctx, id)) || await customChannelWithKey(ctx, id);
|
|
696
791
|
if (found.error) return sendJson(res, found.status || 400, { ok: false, error: found.error });
|
|
697
792
|
sendJson(res, 200, {
|
|
698
793
|
ok: true,
|
package/lib/mobile/feedback.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// 用途:插件反馈统一提交、读取与轮询等回复口;工具和本机面板按线程查看官方回复、继续跟进。
|
|
2
2
|
// 自检 / 探针文案不进真人反馈队列:submit 只收真实问题的现象描述。
|
|
3
|
+
// 2026-11-26:工具注册改为显式取 tools 服务,没声明注入的宿主也挂得上;真缺服务才跳过。
|
|
4
|
+
// 注册走调用方的注入作用域(`ctx.tools`),记在那一代 fiber 名下,热重载换代时随旧代卸掉。
|
|
3
5
|
'use strict';
|
|
4
6
|
|
|
5
7
|
/**
|
|
@@ -288,7 +290,19 @@ function registerFeedbackTool(ctx, deps) {
|
|
|
288
290
|
throw new Error('反馈工具缺少凭据库或实例号取值器');
|
|
289
291
|
}
|
|
290
292
|
const channels = feedbackChannels();
|
|
291
|
-
|
|
293
|
+
// 2026-11-26:显式取服务,不靠 inject。缺一个注入就整行 pending 的代价太大,
|
|
294
|
+
// 而 ctx.get('tools') 在有这个服务时(哪怕当前 fiber 没注入)照样取得到了。
|
|
295
|
+
// 但优先用 `ctx.tools`:它把注册记在当前 fiber 名下,换代时随旧代一起卸;直接拿服务对象
|
|
296
|
+
// 注册只记在服务上,热重载时旧代那份还在,会判「已经注册过」把整代装载打回去。
|
|
297
|
+
let tools = null;
|
|
298
|
+
try {
|
|
299
|
+
tools = ctx.tools ?? null;
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (!String(error?.message || error).includes('without inject')) throw error;
|
|
302
|
+
}
|
|
303
|
+
if (!tools && typeof ctx.get === 'function') tools = ctx.get('tools') || null;
|
|
304
|
+
if (!tools || typeof tools.register !== 'function') return false;
|
|
305
|
+
return tools.register(defineTool({
|
|
292
306
|
name: 'dsh_feedback',
|
|
293
307
|
description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
|
|
294
308
|
+ 'Do not use `submit` for connectivity tests or automated probes: those are not real problems and must not enter the human feedback queue; use `channels` to inspect the route instead. '
|
|
@@ -394,14 +408,9 @@ function renderSummary(value) {
|
|
|
394
408
|
}
|
|
395
409
|
}
|
|
396
410
|
|
|
397
|
-
/** 装配层入口:挂 `dsh_feedback`
|
|
411
|
+
/** 装配层入口:挂 `dsh_feedback` 工具;宿主没有 tools 服务时只少这个工具。 */
|
|
398
412
|
function installFeedback(ctx, deps) {
|
|
399
|
-
|
|
400
|
-
registerFeedbackTool(ctx, deps);
|
|
401
|
-
} catch (error) {
|
|
402
|
-
const message = error && error.message ? error.message : String(error);
|
|
403
|
-
if (!message.includes('without inject')) throw error;
|
|
404
|
-
}
|
|
413
|
+
return registerFeedbackTool(ctx, deps);
|
|
405
414
|
}
|
|
406
415
|
|
|
407
416
|
module.exports = {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-27:「立即同步」的上报半段只认「自动上报网络地址」开关,中转 / 远程控制关着也能催报一次(与 control.js 解耦口径一致)。
|
|
1
2
|
// 手机主动重连在回执发出后调用独立隧道动作,普通配置同步保持幂等。
|
|
2
3
|
// 既有中转配置复用有界健康判据与出网诊断,保留本实例吊销回执收尾。
|
|
3
4
|
// 2026-11-21:「立即同步」只上报不等查询 —— 查询归手机,宿主没有比自己更新的上游可查。
|
|
@@ -654,8 +655,8 @@ function createRelayControlHandlers(deps) {
|
|
|
654
655
|
*/
|
|
655
656
|
async function handleControlSync(_ctx, _req, res) {
|
|
656
657
|
if (typeof syncControl !== 'function' || typeof getControl !== 'function') return unavailable(res);
|
|
657
|
-
//
|
|
658
|
-
const reporting = Boolean(state && state.
|
|
658
|
+
// 用户关了自动上报:连都不会连,催也催不动,等也等不出回执,当场给结论。中转关不关不影响这一条。
|
|
659
|
+
const reporting = Boolean(state && state.controlReportEnabled !== false);
|
|
659
660
|
if (reporting) {
|
|
660
661
|
try { syncControl(); } catch { /* 拨号失败会在下面的快照里如实反映 */ }
|
|
661
662
|
}
|
package/lib/relay/control.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-27:总控上报与「中转 / 远程控制」总开关解耦——只认「自动上报网络地址」这个开关,中转关着也照样把地址报给总控。
|
|
1
2
|
// 2026-11-24:服务商线路清单改由「当前这一代」注入(`getProviderLines`),外壳不再静态 require 那份计算 ——
|
|
2
3
|
// 这样加/改服务商只换代,不动外壳、不重启 DSH。清单本身仍与配对二维码 / 手机心跳同源。
|
|
3
4
|
// 2026-11-23:服务商线路清单收口到 provider-lines,与配对二维码 / 手机心跳同源。
|
|
@@ -348,8 +349,8 @@ function createControlClient(options = {}) {
|
|
|
348
349
|
|
|
349
350
|
function connect() {
|
|
350
351
|
if (!running || sock) return;
|
|
351
|
-
|
|
352
|
-
//
|
|
352
|
+
// 只认「自动上报网络地址」这个开关:它关了就立刻不连(sync/stop 会把已在连的这条也收掉)。
|
|
353
|
+
// 上报是「把本机地址交给地址目录」,不需要中转 / 远程控制先开着 —— 别把它绑在中转总开关上。
|
|
353
354
|
if (getState().controlReportEnabled === false) return;
|
|
354
355
|
const addresses = build(getState());
|
|
355
356
|
if (!Array.isArray(addresses) || (addresses.length === 0 && !hasPublished)) {
|
|
@@ -496,7 +497,7 @@ function createControlClient(options = {}) {
|
|
|
496
497
|
tickTimer = setInterval(tick, 30_000);
|
|
497
498
|
if (tickTimer.unref) tickTimer.unref();
|
|
498
499
|
}
|
|
499
|
-
if (getState().
|
|
500
|
+
if (getState().controlReportEnabled !== false && !sock && !reconnectTimer) connect();
|
|
500
501
|
return snapshot();
|
|
501
502
|
}
|
|
502
503
|
|
|
@@ -513,7 +514,7 @@ function createControlClient(options = {}) {
|
|
|
513
514
|
|
|
514
515
|
/** 配置变更后复核;已发布的地址变空也要沿现有连接清空目录。 */
|
|
515
516
|
function sync() {
|
|
516
|
-
if (
|
|
517
|
+
if (getState().controlReportEnabled === false || !hk()) {
|
|
517
518
|
stop();
|
|
518
519
|
return;
|
|
519
520
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mobile-plugin",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.125",
|
|
4
4
|
"description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"icon": "./icon.png",
|
|
@@ -117,24 +117,23 @@
|
|
|
117
117
|
"yaml": "2.9.1"
|
|
118
118
|
},
|
|
119
119
|
"dshMobileReleaseNotes": {
|
|
120
|
-
"version": "0.5.
|
|
120
|
+
"version": "0.5.125",
|
|
121
121
|
"kinds": [
|
|
122
122
|
"fix",
|
|
123
|
-
"feature"
|
|
124
|
-
"other"
|
|
123
|
+
"feature"
|
|
125
124
|
],
|
|
126
125
|
"notes": {
|
|
127
|
-
"zh-Hans": "
|
|
128
|
-
"zh-Hant": "
|
|
129
|
-
"en": "
|
|
130
|
-
"ja": "
|
|
131
|
-
"ko": "
|
|
132
|
-
"de": "
|
|
133
|
-
"es": "
|
|
134
|
-
"fr": "
|
|
135
|
-
"pt": "
|
|
136
|
-
"ru": "
|
|
137
|
-
"tr": "
|
|
126
|
+
"zh-Hans": "手机和电脑同时打开同一个会话时,越权审批在两端都会出卡,哪边先答就算哪边的;手机停在别的会话或后台时,审批不再被当成没人处理而直接跳过。\n只用局域网、直连或 IPv6、没开中转的机器,网络地址上报照常工作(以前中转开关一关就一条地址都不报)。\n本机 Agent 支持一键导入官方 DeepSeek 渠道,带的还是同一把 Key。\n电脑代发找不到自建渠道时,自动改走 DSH 当前渠道重试,不再一律报「发送失败」;失败原因也会写明,图片这类不支持的内容直接说清。\n面板「AI 网络排查」用到的反馈工具在部分环境里没挂上、AI 回「没有这个工具」,现在改用更可靠的方式注册,热重载后也稳定。",
|
|
127
|
+
"zh-Hant": "手機和電腦同時打開同一個會話時,越權審批在兩端都會出卡,哪邊先答就算哪邊的;手機停在別的會話或背景時,審批不會再被當成沒人處理而直接跳過。\n只用區域網路、直連或 IPv6、沒開中轉的機器,網路位址上報照常運作(以前中轉開關一關就一條位址都不報)。\n本機 Agent 支援一鍵匯入官方 DeepSeek 渠道,帶的還是同一把 Key。\n電腦代發找不到自建渠道時,自動改走 DSH 目前渠道重試,不再一律回報「傳送失敗」;失敗原因也會寫明,圖片這類不支援的內容直接說清。\n面板「AI 網路排查」用到的回饋工具在部分環境裡沒掛上、AI 回「沒有這個工具」,現在改用更可靠的方式註冊,熱重載後也穩定。",
|
|
128
|
+
"en": "When a phone and a computer have the same session open, permission approval prompts now appear on both sides, and whichever answers first wins; approvals are no longer skipped as if nobody was there while the phone sits in another session or in the background.\nOn machines that only use LAN, direct connection or IPv6 without the relay turned on, network address reporting now works as usual (previously not a single address was reported once the relay switch was off).\nThe on-device Agent can now import the official DeepSeek channel in one tap, still using the same key.\nWhen the computer-side proxy cannot find a custom channel, it now falls back to DSH’s current channel and retries instead of always showing \"send failed\"; the reason is spelled out, and unsupported content such as images is reported clearly.\nThe feedback tool used by the panel’s \"AI Network Check\" was not registered in some environments, so the AI replied \"no such tool\"; it is now registered in a more reliable way and stays stable across hot reloads.",
|
|
129
|
+
"ja": "スマートフォンとパソコンで同じセッションを開いているとき、権限承認のカードが両方に表示され、先に答えたほうが採用されます。スマートフォンが別のセッションやバックグラウンドにあるときも、承認が「誰も対応していない」とみなされて飛ばされることはなくなりました。\nLAN・直接接続・IPv6 のみを使い中継を有効にしていない環境でも、ネットワークアドレスの報告が通常どおり動作します(以前は中継スイッチを切るとアドレスが一件も報告されませんでした)。\n端末内 Agent は公式 DeepSeek チャネルをワンタップで取り込めるようになりました。使うキーは同じです。\nパソコン側の代理送信で独自チャネルが見つからないとき、DSH の現在のチャネルに切り替えて再試行するようになり、「送信失敗」とだけ出すことはなくなりました。失敗理由も明示され、画像など未対応の内容ははっきり伝えます。\nパネルの「AI ネットワーク診断」で使うフィードバックツールが一部環境で登録されず、AI が「そのようなツールはない」と答えていましたが、より確実な方法で登録するよう改め、ホットリロード後も安定します。",
|
|
130
|
+
"ko": "휴대폰과 컴퓨터에서 같은 세션을 열어 두면 권한 승인 카드가 양쪽에 모두 뜨고 먼저 답한 쪽이 적용됩니다. 휴대폰이 다른 세션이나 백그라운드에 있을 때 승인이 \"아무도 응답하지 않은 것\"으로 처리되어 건너뛰어지지 않습니다.\nLAN, 직접 연결, IPv6만 쓰고 중계를 켜지 않은 기기에서도 네트워크 주소 보고가 정상 동작합니다(이전에는 중계 스위치를 끄면 주소가 하나도 보고되지 않았습니다).\n온디바이스 Agent에서 공식 DeepSeek 채널을 한 번에 가져올 수 있습니다. 같은 키를 그대로 사용합니다.\n컴퓨터 측 대리 전송에서 사용자 지정 채널을 찾지 못하면 DSH 현재 채널로 자동 전환해 다시 시도하며, 더 이상 \"전송 실패\"만 표시하지 않습니다. 실패 이유도 명시되고 이미지처럼 지원되지 않는 내용은 분명히 알립니다.\n패널의 \"AI 네트워크 점검\"에서 쓰는 피드백 도구가 일부 환경에서 등록되지 않아 AI가 \"그런 도구가 없다\"고 답했는데, 더 안정적인 방식으로 등록하도록 고쳐 핫 리로드 후에도 유지됩니다.",
|
|
131
|
+
"de": "Wenn Smartphone und Computer dieselbe Sitzung geöffnet haben, erscheint die Freigabeanfrage jetzt auf beiden Seiten, und die erste Antwort zählt; Anfragen werden nicht mehr übersprungen, als wäre niemand da, während das Smartphone in einer anderen Sitzung oder im Hintergrund ist.\nAuf Geräten, die nur LAN, Direktverbindung oder IPv6 ohne aktives Relay nutzen, funktioniert die Meldung der Netzwerkadresse jetzt normal (bisher wurde keine einzige Adresse gemeldet, sobald der Relay-Schalter aus war).\nDer Agent auf dem Gerät kann den offiziellen DeepSeek-Kanal jetzt mit einem Tippen importieren, weiterhin mit demselben Schlüssel.\nWenn die Weiterleitung auf dem Computer keinen eigenen Kanal findet, wechselt sie jetzt zum aktuellen DSH-Kanal und versucht es erneut, statt immer nur „Senden fehlgeschlagen“ anzuzeigen; der Grund wird genannt, und nicht unterstützte Inhalte wie Bilder werden klar gemeldet.\nDas Feedback-Werkzeug für die „KI-Netzwerkprüfung“ im Panel wurde in manchen Umgebungen nicht registriert, sodass die KI „kein solches Werkzeug“ antwortete; es wird jetzt zuverlässiger registriert und bleibt auch nach Hot-Reloads stabil.",
|
|
132
|
+
"es": "Cuando un teléfono y un ordenador tienen abierta la misma sesión, la solicitud de aprobación de permisos aparece ahora en ambos lados y prevalece la primera respuesta; ya no se omiten las aprobaciones como si nadie estuviera cuando el teléfono está en otra sesión o en segundo plano.\nEn equipos que solo usan LAN, conexión directa o IPv6 sin el relay activado, el reporte de la dirección de red funciona ahora con normalidad (antes no se reportaba ni una sola dirección en cuanto se apagaba el interruptor del relay).\nEl Agent del dispositivo ya puede importar el canal oficial de DeepSeek con un toque, usando la misma clave.\nCuando el proxy del ordenador no encuentra un canal personalizado, ahora recurre al canal actual de DSH y reintenta en lugar de mostrar siempre «envío fallido»; el motivo se indica y los contenidos no admitidos, como las imágenes, se comunican con claridad.\nLa herramienta de comentarios que usa la «Comprobación de red IA» del panel no se registraba en algunos entornos y la IA respondía «no existe esa herramienta»; ahora se registra de forma más fiable y se mantiene estable tras las recargas en caliente.",
|
|
133
|
+
"fr": "Lorsqu’un téléphone et un ordinateur ont la même session ouverte, la demande d’approbation des permissions s’affiche désormais des deux côtés et la première réponse l’emporte ; les approbations ne sont plus ignorées comme si personne n’était présent lorsque le téléphone est dans une autre session ou en arrière-plan.\nSur les machines qui n’utilisent que le LAN, la connexion directe ou l’IPv6 sans le relais activé, le signalement de l’adresse réseau fonctionne désormais normalement (auparavant, plus aucune adresse n’était signalée dès que l’interrupteur du relais était coupé).\nL’Agent de l’appareil peut désormais importer le canal officiel DeepSeek en un geste, toujours avec la même clé.\nLorsque le relais côté ordinateur ne trouve pas de canal personnalisé, il bascule désormais sur le canal actuel de DSH et réessaie au lieu d’afficher systématiquement « échec de l’envoi » ; la cause est précisée et les contenus non pris en charge, comme les images, sont signalés clairement.\nL’outil de commentaires utilisé par le « Contrôle réseau IA » du panneau n’était pas enregistré dans certains environnements et l’IA répondait « pas un tel outil » ; il est désormais enregistré de façon plus fiable et reste stable après les rechargements à chaud.",
|
|
134
|
+
"pt": "Quando um telefone e um computador têm a mesma sessão aberta, o pedido de aprovação de permissões passa a aparecer dos dois lados e vale a primeira resposta; as aprovações deixam de ser ignoradas como se ninguém estivesse presente quando o telefone está noutra sessão ou em segundo plano.\nEm máquinas que só usam LAN, ligação direta ou IPv6 sem o relay ativado, o reporte do endereço de rede volta a funcionar normalmente (antes não se reportava um único endereço assim que o interruptor do relay era desligado).\nO Agent do dispositivo já consegue importar o canal oficial DeepSeek com um toque, usando a mesma chave.\nQuando o proxy do computador não encontra um canal personalizado, passa a usar o canal atual do DSH e tenta de novo, em vez de mostrar sempre «envio falhado»; o motivo é indicado e os conteúdos não suportados, como imagens, são comunicados com clareza.\nA ferramenta de comentários usada pela «Verificação de rede IA» do painel não era registada em alguns ambientes e a IA respondia «não existe essa ferramenta»; agora é registada de forma mais fiável e mantém-se estável após recargas a quente.",
|
|
135
|
+
"ru": "Когда на телефоне и компьютере открыта одна и та же сессия, запрос на подтверждение прав теперь появляется на обеих сторонах, и засчитывается первый ответ; подтверждения больше не пропускаются как «никого нет», пока телефон находится в другой сессии или в фоне.\nНа машинах, которые используют только локальную сеть, прямое подключение или IPv6 без включённого релея, отправка сетевого адреса снова работает как обычно (раньше при выключенном переключателе релея не отправлялся ни один адрес).\nAgent на устройстве теперь может импортировать официальный канал DeepSeek одним нажатием, с тем же ключом.\nКогда прокси на компьютере не находит пользовательский канал, он переключается на текущий канал DSH и повторяет попытку вместо постоянного «ошибка отправки»; причина указывается, а неподдерживаемое содержимое, например изображения, сообщается прямо.\nИнструмент обратной связи, который использует «ИИ-проверка сети» на панели, в некоторых окружениях не регистрировался, и ИИ отвечал «нет такого инструмента»; теперь он регистрируется надёжнее и остаётся стабильным после горячих перезагрузок.",
|
|
136
|
+
"tr": "Bir telefon ve bilgisayarda aynı oturum açıkken izin onay isteği artık her iki tarafta da görünüyor ve ilk yanıt geçerli oluyor; telefon başka bir oturumda veya arka planda olsa bile onaylar \"kimse yok\" diye atlanmıyor.\nYalnızca yerel ağ, doğrudan bağlantı veya IPv6 kullanan ve aktarımı açık olmayan makinelerde ağ adresi bildirimi artık normal çalışıyor (önceden aktarım anahtarı kapatılınca tek bir adres bile bildirilmiyordu).\nCihazdaki Agent artık resmi DeepSeek kanalını tek dokunuşla içe aktarabiliyor, aynı anahtar kullanılıyor.\nBilgisayar tarafındaki aktarım özel bir kanal bulamadığında artık DSH’nin mevcut kanalına geçip yeniden deniyor, her seferinde yalnızca \"gönderim başarısız\" göstermiyor; neden belirtiliyor ve görsel gibi desteklenmeyen içerikler açıkça bildiriliyor.\nPanelin \"AI Ağ Kontrolü\" tarafından kullanılan geri bildirim aracı bazı ortamlarda kaydedilmiyordu ve AI \"böyle bir araç yok\" diyordu; artık daha güvenilir şekilde kaydediliyor ve sıcak yeniden yüklemelerden sonra da kararlı kalıyor."
|
|
138
137
|
}
|
|
139
138
|
}
|
|
140
139
|
}
|