dsh-connect-workbuddy-gateway 1.4.4 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/client.js +3 -2
- package/index.js +43 -0
- package/package.json +1 -1
- package/src/lan-adapter.js +464 -0
- package/src/pairing.js +16 -1
- package/src/routes.js +246 -11
package/README.md
CHANGED
|
@@ -558,7 +558,7 @@ hy4flash-free@#9 ← 昵称含中文/emoji,退化成序号
|
|
|
558
558
|
node tests/harness.mjs
|
|
559
559
|
```
|
|
560
560
|
|
|
561
|
-
覆盖
|
|
561
|
+
覆盖 327 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
|
|
562
562
|
非 ASCII 序号)、跨区同名、按名字路由、推理档透传、**固定监听端口与占用提示**、**局域网分享与接入**、**两种角色模式**、
|
|
563
563
|
并行工具调用按 index 分组、
|
|
564
564
|
Responses 流的规范校验(`sequence_number`、part 一致性、terminal 的 output 顺序)、
|
package/client.js
CHANGED
|
@@ -1596,7 +1596,8 @@ window.__ModuleLoader__.load({
|
|
|
1596
1596
|
setScanning(true)
|
|
1597
1597
|
setError(undefined)
|
|
1598
1598
|
try {
|
|
1599
|
-
|
|
1599
|
+
/* 把手填的地址一起送去 —— 它能顺带测 TCP,指出「广播被拦但地址通」。 */
|
|
1600
|
+
setDiag(await onDiagnose(manual.trim()))
|
|
1600
1601
|
} catch (caught) {
|
|
1601
1602
|
setError(String(caught.message ?? caught))
|
|
1602
1603
|
} finally {
|
|
@@ -1936,7 +1937,7 @@ window.__ModuleLoader__.load({
|
|
|
1936
1937
|
return body?.peers ?? []
|
|
1937
1938
|
}, [])
|
|
1938
1939
|
|
|
1939
|
-
const diagnosePeers = useCallback(async () => adminPost('/peers/diagnose', {}), [])
|
|
1940
|
+
const diagnosePeers = useCallback(async (baseUrl) => adminPost('/peers/diagnose', { baseUrl: baseUrl ?? '' }), [])
|
|
1940
1941
|
|
|
1941
1942
|
const requestPeer = useCallback(async (baseUrl, deviceName) => {
|
|
1942
1943
|
await adminPost('/peers/request', { baseUrl, deviceName })
|
package/index.js
CHANGED
|
@@ -22,6 +22,8 @@ import { workbuddyProviders } from './src/backend.js'
|
|
|
22
22
|
import { closeDirect } from './src/direct.js'
|
|
23
23
|
import { readConfig, writeConfig, makeKey, normalizeSelections, configPath, useDataDir } from './src/config.js'
|
|
24
24
|
import { catalogForSettings } from './src/models.js'
|
|
25
|
+
import { LAN_PROVIDER, createLanAdapter } from './src/lan-adapter.js'
|
|
26
|
+
import { readPeers } from './src/peers.js'
|
|
25
27
|
|
|
26
28
|
export const name = 'workbuddy-gateway'
|
|
27
29
|
|
|
@@ -200,6 +202,47 @@ export function apply(ctx, config) {
|
|
|
200
202
|
void closeDirect()
|
|
201
203
|
}
|
|
202
204
|
})
|
|
205
|
+
|
|
206
|
+
/*
|
|
207
|
+
* **client 模式:把已接入的网关注册成 DSH 的模型来源。**
|
|
208
|
+
*
|
|
209
|
+
* 这是「装上插件就能在会话里用那台机器的模型」的落点。只存 peers 是不够的 ——
|
|
210
|
+
* 宿主要先认识那个 provider,模型选择器里才会出现它。
|
|
211
|
+
*
|
|
212
|
+
* 用的是鸭子类型的 adapter(见 src/lan-adapter.js):不继承 `LlmAdapter`,
|
|
213
|
+
* 因为那个类所在的包插件解析不到。注册表只调那几个方法,这样就够了。
|
|
214
|
+
*/
|
|
215
|
+
if (settings.mode === 'client') {
|
|
216
|
+
ctx.effect(() => {
|
|
217
|
+
const llm = ctx.get('llm')
|
|
218
|
+
if (llm === undefined) {
|
|
219
|
+
ctx.logger.warn('workbuddy-gateway: no llm service, so shared models cannot be offered')
|
|
220
|
+
return () => {}
|
|
221
|
+
}
|
|
222
|
+
let handle
|
|
223
|
+
try {
|
|
224
|
+
handle = llm.registerAdapter([LAN_PROVIDER], createLanAdapter({
|
|
225
|
+
getPeers: readPeers,
|
|
226
|
+
logger: ctx.logger,
|
|
227
|
+
}))
|
|
228
|
+
} catch (error) {
|
|
229
|
+
/*
|
|
230
|
+
* 重复注册(例如插件被热重载两次)不该把整个插件搞崩 —— 那只意味着
|
|
231
|
+
* 这个 provider 已经有人服务了。
|
|
232
|
+
*/
|
|
233
|
+
ctx.logger.warn(`workbuddy-gateway: could not register the LAN provider: ${error instanceof Error ? error.message : String(error)}`)
|
|
234
|
+
return () => {}
|
|
235
|
+
}
|
|
236
|
+
ctx.logger.info(`workbuddy-gateway: registered provider "${LAN_PROVIDER}" for shared models`)
|
|
237
|
+
return () => {
|
|
238
|
+
try {
|
|
239
|
+
handle()
|
|
240
|
+
} catch {
|
|
241
|
+
/* 已经卸载了 */
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
})
|
|
245
|
+
}
|
|
203
246
|
}
|
|
204
247
|
|
|
205
248
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-connect-workbuddy-gateway",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "把 dsh-connect-workbuddy 的 WorkBuddy 模型开放成 HTTP API:OpenAI Chat / Responses、Anthropic Messages、Gemini 四协议共用一个固定 base URL,模型按 API key 逐个勾选。也可切换成接收方,接入局域网内另一台设备分享的模型。",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh-plugin",
|
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 接收方把「接入的网关」注册成 DSH 的模型来源。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么必须做这一步
|
|
5
|
+
*
|
|
6
|
+
* 只把凭据存进 `peers` 是**不够的**:设置页能看到「已接入」,但 DSH 的模型选择器
|
|
7
|
+
* 里什么都没有 —— 因为宿主根本不认识那个 provider,会话页自然也拿不到模型。
|
|
8
|
+
*
|
|
9
|
+
* 用户要的是「装上插件就能在会话里用那台机器的模型」,所以必须:
|
|
10
|
+
*
|
|
11
|
+
* 1. `llm.registerAdapter(['workbuddy-lan'], adapter)` —— 让宿主认识这个路由
|
|
12
|
+
* 2. `adapter.listModels()` 返回远端网关的模型
|
|
13
|
+
* 3. `adapter.stream()` 把 DSH 的请求转成远端网关的 HTTP 调用,再把 SSE 转回
|
|
14
|
+
* `StreamChunk`
|
|
15
|
+
*
|
|
16
|
+
* 第 3 步是双向转换:DSH 用 `StreamChunk`,网关用 OpenAI Chat 的 SSE。工具的
|
|
17
|
+
* 参数分片、思考增量、usage 都要对齐,否则客户端会看到不完整的回复。
|
|
18
|
+
*
|
|
19
|
+
* ## 一个 provider 承载多台网关
|
|
20
|
+
*
|
|
21
|
+
* 模型名里编码了网关 id(`<peerId>/<modelId>`),所以 `workbuddy-lan` 这一个路由
|
|
22
|
+
* 可以同时接多台机器。这比「一台机器一个 provider」简单:宿主的 provider 列表
|
|
23
|
+
* 是静态注册的,而用户可以随时接入/断开。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** 接收方统一的 provider 路由名。 */
|
|
27
|
+
export const LAN_PROVIDER = 'workbuddy-lan'
|
|
28
|
+
|
|
29
|
+
/** 模型名里 peer 与模型的间隔符。`/` 在模型 id 里几乎不出现,且不属于保留字符。 */
|
|
30
|
+
const MODEL_SEPARATOR = '/'
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 把一个 peer 的模型名编码成宿主可见的 id。
|
|
34
|
+
*
|
|
35
|
+
* @param peerId peer 的 id
|
|
36
|
+
* @param modelId 远端模型 id
|
|
37
|
+
*/
|
|
38
|
+
export function encodeModelId(peerId, modelId) {
|
|
39
|
+
return `${peerId}${MODEL_SEPARATOR}${modelId}`
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 拆回 `{ peerId, modelId }`。
|
|
44
|
+
*
|
|
45
|
+
* 从**第一个**分隔符处切:远端模型 id 里若有 `/`(某些网关会带),要保留在
|
|
46
|
+
* modelId 里,不能一起切掉。
|
|
47
|
+
*
|
|
48
|
+
* @param value 宿主传来的模型 id
|
|
49
|
+
*/
|
|
50
|
+
export function decodeModelId(value) {
|
|
51
|
+
const text = typeof value === 'string' ? value : ''
|
|
52
|
+
const at = text.indexOf(MODEL_SEPARATOR)
|
|
53
|
+
if (at <= 0) return undefined
|
|
54
|
+
return { peerId: text.slice(0, at), modelId: text.slice(at + 1) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 造一个 adapter:把 DSH 的调用转到远端网关。
|
|
59
|
+
*
|
|
60
|
+
* ## 为什么不继承 `LlmAdapter`
|
|
61
|
+
*
|
|
62
|
+
* 宿主约定 `registerAdapter(providers, adapter)` 收一个 `LlmAdapter`,但那是个
|
|
63
|
+
* **带默认实现的抽象类**,而它所在的包(`@deepseek-ai/dsh-llm-pi-ai`)打在
|
|
64
|
+
* `app.asar` 里,插件从 profile 的 node_modules 解析不到 —— 上游插件能 import 是
|
|
65
|
+
* 因为它装在能看见宿主依赖的位置。
|
|
66
|
+
*
|
|
67
|
+
* 所以这里用**鸭子类型**:提供一个同名方法的普通对象。注册表只调这些方法,
|
|
68
|
+
* 不需要真的 `instanceof`。少一层继承,也少一个「安装位置变了就炸」的依赖。
|
|
69
|
+
*
|
|
70
|
+
* @param options 配置
|
|
71
|
+
* @param options.getPeers 返回当前 peers 的函数(每次现读,接入/断开立刻生效)
|
|
72
|
+
* @param options.logger 日志
|
|
73
|
+
*/
|
|
74
|
+
export function createLanAdapter({ getPeers, logger }) {
|
|
75
|
+
return {
|
|
76
|
+
/** 宿主要显示的 provider 名字。 */
|
|
77
|
+
providerInfo(provider) {
|
|
78
|
+
return { id: provider, name: 'WorkBuddy(局域网接入)' }
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
/** 重试策略交给宿主默认(不返回自定义策略)。 */
|
|
82
|
+
providerRetryPolicy() {
|
|
83
|
+
return undefined
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
imageRequestPricing() {
|
|
87
|
+
return undefined
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
/** 远端投影会把图片丢掉,所以给一个「不接受图片」的兜底尺寸。 */
|
|
91
|
+
imageRequestTarget(_provider, _model, image) {
|
|
92
|
+
return { width: image?.width ?? 0, height: image?.height ?? 0, maxBytes: image?.bytes ?? 0 }
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 列出所有已接入网关的模型。
|
|
97
|
+
*
|
|
98
|
+
* 用**缓存**而不是每次现拉:DSH 会在很多地方问模型列表,逐次发 HTTP 会让
|
|
99
|
+
* 会话页卡顿。缓存由接入时的 `models` 以及「刷新模型」按钮更新。
|
|
100
|
+
*/
|
|
101
|
+
async listModels(provider) {
|
|
102
|
+
const out = []
|
|
103
|
+
for (const peer of getPeers()) {
|
|
104
|
+
for (const model of peer.models ?? []) {
|
|
105
|
+
out.push({
|
|
106
|
+
provider,
|
|
107
|
+
id: encodeModelId(peer.id, model.id),
|
|
108
|
+
name: model.displayName ?? model.id,
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return out
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
/** 解析一个模型的元信息。上下文窗口必须给数值,否则长对话会被截断。 */
|
|
116
|
+
async resolveModel(provider, model) {
|
|
117
|
+
const found = findPeerModel(getPeers(), model)
|
|
118
|
+
if (found === undefined) {
|
|
119
|
+
throw lanError(`this model is no longer available (its gateway was disconnected): ${model}`, 'MODEL_NOT_FOUND', 404)
|
|
120
|
+
}
|
|
121
|
+
const { meta } = found
|
|
122
|
+
const efforts = Array.isArray(meta.reasoningEfforts) ? meta.reasoningEfforts : []
|
|
123
|
+
return {
|
|
124
|
+
provider,
|
|
125
|
+
id: model,
|
|
126
|
+
name: meta.displayName ?? meta.id,
|
|
127
|
+
context: { contextWindow: typeof meta.contextWindow === 'number' ? meta.contextWindow : 128000 },
|
|
128
|
+
...(typeof meta.maxTokens === 'number' ? { defaultMaxTokens: meta.maxTokens } : {}),
|
|
129
|
+
inputModalities: ['text'],
|
|
130
|
+
...(efforts.length === 0
|
|
131
|
+
? {}
|
|
132
|
+
: { reasoning: { efforts: efforts.map((effort) => ({ id: effort, name: effort })) } }),
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 起一条流。
|
|
138
|
+
*
|
|
139
|
+
* 把 DSH 的 `GenerateOptions` 翻成 OpenAI Chat 请求发给远端网关,再把回来的
|
|
140
|
+
* SSE 翻成 `StreamChunk`。**失败也走 chunk 通道**(terminal error finish),
|
|
141
|
+
* 不在生成器里抛 —— 与 host-backend.js 同一个理由:调用方先 `break` 时,
|
|
142
|
+
* 生成器里的 throw 会被吞掉,表现为「流正常结束、错误消失」。
|
|
143
|
+
*/
|
|
144
|
+
async *stream(options) {
|
|
145
|
+
const found = findPeerModel(getPeers(), options.model)
|
|
146
|
+
if (found === undefined) {
|
|
147
|
+
yield finishError(`the gateway for this model is no longer connected: ${options.model}`)
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
const { peer, modelId } = found
|
|
151
|
+
|
|
152
|
+
const body = buildChatRequest(modelId, options)
|
|
153
|
+
let response
|
|
154
|
+
try {
|
|
155
|
+
response = await fetch(`${peer.baseUrl}/v1/chat/completions`, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: {
|
|
158
|
+
'Content-Type': 'application/json',
|
|
159
|
+
Authorization: `Bearer ${peer.secret}`,
|
|
160
|
+
},
|
|
161
|
+
body: JSON.stringify(body),
|
|
162
|
+
signal: options.signal,
|
|
163
|
+
})
|
|
164
|
+
} catch (error) {
|
|
165
|
+
yield finishError(describeFetchFailure(error))
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (!response.ok) {
|
|
170
|
+
/* 把远端的错误读出来给用户看,而不是只说「失败了」。 */
|
|
171
|
+
const text = await response.text().catch(() => '')
|
|
172
|
+
yield finishError(describeHttpFailure(response.status, text))
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
if (response.body === null) {
|
|
176
|
+
yield finishError('the gateway returned no stream body')
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const state = { index: 0, textIndex: -1, reasoningIndex: -1, tools: new Map() }
|
|
181
|
+
try {
|
|
182
|
+
for await (const event of readChatSse(response.body)) {
|
|
183
|
+
for (const chunk of chunksOf(event, state)) yield chunk
|
|
184
|
+
}
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (options.signal?.aborted === true) {
|
|
187
|
+
yield { type: 'finish', reason: { kind: 'aborted', failure: { message: 'cancelled', code: 'ABORTED' } } }
|
|
188
|
+
return
|
|
189
|
+
}
|
|
190
|
+
yield finishError(describeFetchFailure(error))
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/*
|
|
195
|
+
* 收尾:把还没关的 block 关掉。
|
|
196
|
+
*
|
|
197
|
+
* DSH 依赖 `block-end` 才能把工具调用交给执行层;漏掉它,模型「调了工具」
|
|
198
|
+
* 但会话里什么都没发生。
|
|
199
|
+
*/
|
|
200
|
+
for (const chunk of closeBlocks(state)) yield chunk
|
|
201
|
+
yield { type: 'finish', reason: { kind: 'stop' } }
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 在已接入的网关里找一个模型。
|
|
208
|
+
*
|
|
209
|
+
* @param peers 当前 peers
|
|
210
|
+
* @param model 宿主传来的编码后 id
|
|
211
|
+
* @returns `{ peer, meta, modelId }` 或 undefined
|
|
212
|
+
*/
|
|
213
|
+
function findPeerModel(peers, model) {
|
|
214
|
+
const decoded = decodeModelId(model)
|
|
215
|
+
if (decoded === undefined) return undefined
|
|
216
|
+
const peer = peers.find((entry) => entry.id === decoded.peerId)
|
|
217
|
+
if (peer === undefined) return undefined
|
|
218
|
+
const meta = (peer.models ?? []).find((entry) => entry.id === decoded.modelId)
|
|
219
|
+
if (meta === undefined) return undefined
|
|
220
|
+
return { peer, meta, modelId: decoded.modelId }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* DSH 的 `GenerateOptions` → OpenAI Chat 请求体。
|
|
225
|
+
*
|
|
226
|
+
* @param modelId 远端模型 id
|
|
227
|
+
* @param options 宿主的调用参数
|
|
228
|
+
*/
|
|
229
|
+
export function buildChatRequest(modelId, options) {
|
|
230
|
+
const messages = []
|
|
231
|
+
if (typeof options.system === 'string' && options.system !== '') {
|
|
232
|
+
messages.push({ role: 'system', content: options.system })
|
|
233
|
+
}
|
|
234
|
+
for (const message of Array.isArray(options.messages) ? options.messages : []) {
|
|
235
|
+
if (message.role === 'tool') {
|
|
236
|
+
messages.push({
|
|
237
|
+
role: 'tool',
|
|
238
|
+
tool_call_id: message.toolCallId,
|
|
239
|
+
content: textOfBlocks(message.content),
|
|
240
|
+
})
|
|
241
|
+
continue
|
|
242
|
+
}
|
|
243
|
+
if (message.role === 'assistant') {
|
|
244
|
+
const text = textOfBlocks(message.content)
|
|
245
|
+
const calls = []
|
|
246
|
+
for (const block of Array.isArray(message.content) ? message.content : []) {
|
|
247
|
+
if (block?.type !== 'tool-call') continue
|
|
248
|
+
calls.push({
|
|
249
|
+
id: block.id,
|
|
250
|
+
type: 'function',
|
|
251
|
+
function: { name: block.name, arguments: block.arguments ?? '{}' },
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
messages.push({
|
|
255
|
+
role: 'assistant',
|
|
256
|
+
content: text === '' && calls.length > 0 ? null : text,
|
|
257
|
+
...(calls.length === 0 ? {} : { tool_calls: calls }),
|
|
258
|
+
})
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
messages.push({ role: message.role === 'developer' ? 'system' : 'user', content: textOfBlocks(message.content) })
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
model: modelId,
|
|
266
|
+
messages,
|
|
267
|
+
stream: true,
|
|
268
|
+
/* 让网关把 usage 一起发回来,DSH 的计费显示要用。 */
|
|
269
|
+
stream_options: { include_usage: true },
|
|
270
|
+
...(Array.isArray(options.tools) && options.tools.length > 0
|
|
271
|
+
? {
|
|
272
|
+
tools: options.tools.map((tool) => ({
|
|
273
|
+
type: 'function',
|
|
274
|
+
function: { name: tool.name, description: tool.description, parameters: tool.parameters },
|
|
275
|
+
})),
|
|
276
|
+
}
|
|
277
|
+
: {}),
|
|
278
|
+
...(options.temperature === undefined ? {} : { temperature: options.temperature }),
|
|
279
|
+
...(options.maxTokens === undefined ? {} : { max_tokens: options.maxTokens }),
|
|
280
|
+
...(Array.isArray(options.stop) && options.stop.length > 0 ? { stop: options.stop } : {}),
|
|
281
|
+
...(options.reasoningEffort === undefined ? {} : { reasoning_effort: options.reasoningEffort }),
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 取一段 content 里的纯文本(图片/文件在远端无法投影,丢掉)。 */
|
|
286
|
+
function textOfBlocks(content) {
|
|
287
|
+
if (typeof content === 'string') return content
|
|
288
|
+
if (!Array.isArray(content)) return ''
|
|
289
|
+
const parts = []
|
|
290
|
+
for (const block of content) {
|
|
291
|
+
if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
292
|
+
}
|
|
293
|
+
return parts.join('\n')
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 读 OpenAI Chat 的 SSE,产出解析后的事件。
|
|
298
|
+
*
|
|
299
|
+
* 逐行处理 `data: {...}`,忽略注释行与空行;`[DONE]` 结束。
|
|
300
|
+
*
|
|
301
|
+
* @param body Web ReadableStream
|
|
302
|
+
*/
|
|
303
|
+
export async function* readChatSse(body) {
|
|
304
|
+
const decoder = new TextDecoder()
|
|
305
|
+
let buffer = ''
|
|
306
|
+
const reader = body.getReader()
|
|
307
|
+
try {
|
|
308
|
+
for (;;) {
|
|
309
|
+
const { done, value } = await reader.read()
|
|
310
|
+
if (done) break
|
|
311
|
+
buffer += decoder.decode(value, { stream: true })
|
|
312
|
+
let at
|
|
313
|
+
while ((at = buffer.indexOf('\n')) >= 0) {
|
|
314
|
+
const line = buffer.slice(0, at).replace(/\r$/u, '')
|
|
315
|
+
buffer = buffer.slice(at + 1)
|
|
316
|
+
const parsed = parseSseLine(line)
|
|
317
|
+
if (parsed === DONE) return
|
|
318
|
+
if (parsed !== undefined) yield parsed
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/* 收尾:最后一行可能没有换行。 */
|
|
322
|
+
const last = parseSseLine(buffer.replace(/\r$/u, ''))
|
|
323
|
+
if (last !== undefined && last !== DONE) yield last
|
|
324
|
+
} finally {
|
|
325
|
+
reader.releaseLock?.()
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const DONE = Symbol('done')
|
|
330
|
+
|
|
331
|
+
/** 解析一行 SSE。返回 undefined 表示这行没有内容。 */
|
|
332
|
+
function parseSseLine(line) {
|
|
333
|
+
const text = line.trim()
|
|
334
|
+
if (text === '' || text.startsWith(':')) return undefined
|
|
335
|
+
if (!text.startsWith('data:')) return undefined
|
|
336
|
+
const payload = text.slice(5).trim()
|
|
337
|
+
if (payload === '[DONE]') return DONE
|
|
338
|
+
try {
|
|
339
|
+
return JSON.parse(payload)
|
|
340
|
+
} catch {
|
|
341
|
+
return undefined
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 一个 Chat chunk → 若干 `StreamChunk`。
|
|
347
|
+
*
|
|
348
|
+
* `state` 记录当前开着的 block:正文、思考、以及每个工具调用各自的 block index。
|
|
349
|
+
* 工具调用必须按**上游的 `index`** 分开,否则并行调用的参数会串在一起(这个坑在
|
|
350
|
+
* 网关的 Anthropic 输出那边踩过一次)。
|
|
351
|
+
*/
|
|
352
|
+
function* chunksOf(event, state) {
|
|
353
|
+
const choice = Array.isArray(event?.choices) ? event.choices[0] : undefined
|
|
354
|
+
const delta = choice?.delta
|
|
355
|
+
|
|
356
|
+
if (typeof delta?.reasoning_content === 'string' && delta.reasoning_content !== '') {
|
|
357
|
+
if (state.reasoningIndex < 0) {
|
|
358
|
+
state.reasoningIndex = state.index
|
|
359
|
+
state.index += 1
|
|
360
|
+
yield { type: 'block-start', index: state.reasoningIndex, blockType: 'reasoning' }
|
|
361
|
+
}
|
|
362
|
+
yield { type: 'reasoning-delta', index: state.reasoningIndex, text: delta.reasoning_content }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (typeof delta?.content === 'string' && delta.content !== '') {
|
|
366
|
+
if (state.textIndex < 0) {
|
|
367
|
+
state.textIndex = state.index
|
|
368
|
+
state.index += 1
|
|
369
|
+
yield { type: 'block-start', index: state.textIndex, blockType: 'text' }
|
|
370
|
+
}
|
|
371
|
+
yield { type: 'text-delta', index: state.textIndex, text: delta.content }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
for (const call of Array.isArray(delta?.tool_calls) ? delta.tool_calls : []) {
|
|
375
|
+
const upstream = Number.isInteger(call.index) ? call.index : 0
|
|
376
|
+
let entry = state.tools.get(upstream)
|
|
377
|
+
if (entry === undefined) {
|
|
378
|
+
entry = { index: state.index, id: call.id ?? `call_${upstream}`, name: call.function?.name ?? '', args: '' }
|
|
379
|
+
state.index += 1
|
|
380
|
+
state.tools.set(upstream, entry)
|
|
381
|
+
yield { type: 'block-start', index: entry.index, blockType: 'tool-call' }
|
|
382
|
+
}
|
|
383
|
+
if (typeof call.function?.name === 'string' && call.function.name !== '' && entry.name === '') {
|
|
384
|
+
entry.name = call.function.name
|
|
385
|
+
}
|
|
386
|
+
const piece = call.function?.arguments
|
|
387
|
+
if (typeof piece === 'string' && piece !== '') entry.args += piece
|
|
388
|
+
yield {
|
|
389
|
+
type: 'tool-call-delta',
|
|
390
|
+
index: entry.index,
|
|
391
|
+
id: entry.id,
|
|
392
|
+
...(entry.name === '' ? {} : { name: entry.name }),
|
|
393
|
+
argumentsDelta: typeof piece === 'string' ? piece : '',
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/* usage 只在最后一个 chunk 出现(带 stream_options.include_usage 时)。 */
|
|
398
|
+
if (event?.usage !== undefined && event.usage !== null) {
|
|
399
|
+
yield {
|
|
400
|
+
type: 'usage',
|
|
401
|
+
usage: {
|
|
402
|
+
inputTokens: Number(event.usage.prompt_tokens ?? 0),
|
|
403
|
+
outputTokens: Number(event.usage.completion_tokens ?? 0),
|
|
404
|
+
...(event.usage.total_tokens === undefined ? {} : { totalTokens: event.usage.total_tokens }),
|
|
405
|
+
},
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** 收尾:先关正文/思考,再把每个工具调用整块交出去。 */
|
|
412
|
+
function* closeBlocks(state) {
|
|
413
|
+
if (state.reasoningIndex >= 0) {
|
|
414
|
+
yield { type: 'block-end', index: state.reasoningIndex, block: { type: 'reasoning', text: '' } }
|
|
415
|
+
state.reasoningIndex = -1
|
|
416
|
+
}
|
|
417
|
+
if (state.textIndex >= 0) {
|
|
418
|
+
yield { type: 'block-end', index: state.textIndex, block: { type: 'text', text: '' } }
|
|
419
|
+
state.textIndex = -1
|
|
420
|
+
}
|
|
421
|
+
for (const entry of state.tools.values()) {
|
|
422
|
+
/* 参数不合法时给 `{}`:交给 DSH 的工具层去报错,比在这里丢掉整个调用好。 */
|
|
423
|
+
yield {
|
|
424
|
+
type: 'block-end',
|
|
425
|
+
index: entry.index,
|
|
426
|
+
block: { type: 'tool-call', id: entry.id, name: entry.name, arguments: entry.args === '' ? '{}' : entry.args },
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
state.tools.clear()
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** 造一个 terminal error finish。 */
|
|
433
|
+
function finishError(message) {
|
|
434
|
+
return { type: 'finish', reason: { kind: 'error', failure: { message, code: 'LAN_GATEWAY_ERROR' } } }
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** HTTP 失败 → 可读消息(带上远端给的错误文本)。 */
|
|
438
|
+
function describeHttpFailure(status, text) {
|
|
439
|
+
let detail = text
|
|
440
|
+
try {
|
|
441
|
+
const parsed = JSON.parse(text)
|
|
442
|
+
detail = parsed?.error?.message ?? parsed?.message ?? text
|
|
443
|
+
} catch {
|
|
444
|
+
/* 不是 JSON 就原样用 */
|
|
445
|
+
}
|
|
446
|
+
const trimmed = String(detail ?? '').slice(0, 300)
|
|
447
|
+
if (status === 401) return 'the key this device was given is no longer valid; ask for a new share'
|
|
448
|
+
if (status === 403) return `the gateway refused this device: ${trimmed}`
|
|
449
|
+
return `the gateway answered ${status}${trimmed === '' ? '' : `: ${trimmed}`}`
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 网络层失败 → 可读消息。 */
|
|
453
|
+
function describeFetchFailure(error) {
|
|
454
|
+
if (error?.name === 'AbortError') return 'cancelled'
|
|
455
|
+
return `cannot reach the gateway: ${error instanceof Error ? error.message : String(error)}`
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** 带 code/status 的错误,与宿主的 LlmError 形状一致。 */
|
|
459
|
+
function lanError(message, code, status) {
|
|
460
|
+
const error = new Error(message)
|
|
461
|
+
error.code = code
|
|
462
|
+
error.status = status
|
|
463
|
+
return error
|
|
464
|
+
}
|
package/src/pairing.js
CHANGED
|
@@ -159,7 +159,22 @@ export function createPairingRegistry({ logger, now = () => Date.now() } = {}) {
|
|
|
159
159
|
}))
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
-
|
|
162
|
+
/**
|
|
163
|
+
* 查一条请求的申请方信息(不改变状态)。
|
|
164
|
+
*
|
|
165
|
+
* 给「批准时怎么命名那把 key」用:批准流程要**先**知道是谁,才能建出可区分的
|
|
166
|
+
* 标签,而不是等 approve 的返回值。
|
|
167
|
+
*
|
|
168
|
+
* @param nonce 请求 id
|
|
169
|
+
* @returns `{ deviceName, address }` 或 undefined
|
|
170
|
+
*/
|
|
171
|
+
function describe(nonce) {
|
|
172
|
+
const entry = pending.get(nonce)
|
|
173
|
+
if (entry === undefined) return undefined
|
|
174
|
+
return { deviceName: entry.deviceName, address: entry.address }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { request, approve, claim, deny, list, describe }
|
|
163
178
|
}
|
|
164
179
|
|
|
165
180
|
/**
|
package/src/routes.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { networkInterfaces, hostname } from 'node:os'
|
|
18
18
|
import { startResponder, discoverPeers, broadcastAddresses, DEFAULT_DISCOVERY_PORT } from './discovery.js'
|
|
19
19
|
import { createPairingRegistry, PAIR_TTL_MS } from './pairing.js'
|
|
20
|
+
import { LAN_PROVIDER } from './lan-adapter.js'
|
|
20
21
|
import { sendJson, failureOf } from './util.js'
|
|
21
22
|
import { handleChat } from './openai-chat.js'
|
|
22
23
|
import { handleResponses } from './openai-responses.js'
|
|
@@ -239,6 +240,40 @@ async function dispatchApi(req, res, ctx, env) {
|
|
|
239
240
|
* 也是三家鉴权头里唯一能区分调用方的信号。没带就当 OpenAI 处理。
|
|
240
241
|
*/
|
|
241
242
|
const wantsAnthropicShape = typeof req.headers['anthropic-version'] === 'string'
|
|
243
|
+
|
|
244
|
+
/*
|
|
245
|
+
* 接收方主动断开时来通知。
|
|
246
|
+
*
|
|
247
|
+
* 放在这里而不是 `/pair/*` 那段:它**需要 key 鉴权**(用对方持有的那把),
|
|
248
|
+
* 而配对接口是按「还没有 key」设计的。也不走协议路由 —— 它不属于任何协议。
|
|
249
|
+
*/
|
|
250
|
+
if (path === '/peer/disconnect') {
|
|
251
|
+
if (method !== 'POST') {
|
|
252
|
+
sendJson(res, 405, { error: { message: 'use POST', type: 'invalid_request_error', code: 'method_not_allowed' } })
|
|
253
|
+
return
|
|
254
|
+
}
|
|
255
|
+
/*
|
|
256
|
+
* 只允许断开「通过配对分享出去的」key。自己手动建的 key 不该被远端
|
|
257
|
+
* 一句话删掉 —— 它可能被别的用途在用。
|
|
258
|
+
*/
|
|
259
|
+
if (keyEntry.sharedWith === undefined) {
|
|
260
|
+
sendJson(res, 400, {
|
|
261
|
+
error: {
|
|
262
|
+
message: 'this key was not issued through pairing, so it cannot be disconnected remotely',
|
|
263
|
+
type: 'invalid_request_error',
|
|
264
|
+
code: 'not_a_shared_key',
|
|
265
|
+
},
|
|
266
|
+
})
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
const config = readConfig()
|
|
270
|
+
config.keys = config.keys.filter((entry) => entry.id !== keyEntry.id)
|
|
271
|
+
writeConfig(config)
|
|
272
|
+
ctx.logger.info('workbuddy-gateway: a device disconnected; its shared key was removed')
|
|
273
|
+
sendJson(res, 200, { ok: true, removed: keyEntry.id })
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
|
|
242
277
|
try {
|
|
243
278
|
if (route === '/healthz' || route === '/') {
|
|
244
279
|
const info = describeEndpoints(originOf(ctx, env))
|
|
@@ -508,8 +543,18 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
508
543
|
return
|
|
509
544
|
}
|
|
510
545
|
|
|
511
|
-
/*
|
|
512
|
-
|
|
546
|
+
/*
|
|
547
|
+
* 新 key:独立凭据,撤销它不影响源 key。
|
|
548
|
+
*
|
|
549
|
+
* **标签必须能区分是哪个设备。** 之前固定叫 `LAN share`,结果用户手动建的
|
|
550
|
+
* key 也叫这个名字时,设置页里出现两条一模一样的「LAN share」—— 撤销时
|
|
551
|
+
* 点错哪一条完全靠运气,删掉了不该删的那把。现在带上设备名或地址。
|
|
552
|
+
*/
|
|
553
|
+
const requester = env.pairing?.describe(nonce)
|
|
554
|
+
const sharedLabel = typeof body?.label === 'string' && body.label.trim() !== ''
|
|
555
|
+
? body.label.trim()
|
|
556
|
+
: defaultShareLabel(requester?.deviceName, requester?.address)
|
|
557
|
+
const created = makeKey({ label: sharedLabel })
|
|
513
558
|
created.selections = normalizeSelections(picked)
|
|
514
559
|
created.seeded = true
|
|
515
560
|
config.keys.push(created)
|
|
@@ -697,13 +742,26 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
697
742
|
* 广播跨不过路由器、跨不过 AP 隔离、跨不过不同网段 —— 这些失败在接收方
|
|
698
743
|
* 看来都是同一句「没找到」,而原因完全不同,处理方式也不同。所以把能查的
|
|
699
744
|
* 都查一遍,逐条给出结论。
|
|
745
|
+
*
|
|
746
|
+
* **同时测 TCP**:UDP 广播被拦但 TCP 通,是 AP 隔离最典型的表现 —— 那种
|
|
747
|
+
* 情况手动填地址就能用,值得单独指出来。
|
|
700
748
|
*/
|
|
701
749
|
const port = env.config.discoveryPort ?? DEFAULT_DISCOVERY_PORT
|
|
702
750
|
const addresses = await lanAddresses()
|
|
703
751
|
const found = await discoverPeers({ port, timeoutMs: 1500, logger: ctx.logger })
|
|
752
|
+
/*
|
|
753
|
+
* 请求体只读一次 —— 流只能消费一遍,读第二次会拿到空对象。
|
|
754
|
+
*/
|
|
755
|
+
const body = await readJsonBody(req)
|
|
756
|
+
const manual = normalizeBaseUrl(typeof body?.baseUrl === 'string' ? body.baseUrl : '')
|
|
757
|
+
|
|
758
|
+
/* 若用户手填了地址,顺带测一下 TCP 是否通。 */
|
|
759
|
+
let reachable
|
|
760
|
+
if (manual !== undefined) {
|
|
761
|
+
reachable = await probeTcp(manual, 2500)
|
|
762
|
+
}
|
|
704
763
|
|
|
705
764
|
sendJson(res, 200, {
|
|
706
|
-
/* 本机看到的自己,用来和对方对比"是不是同一个网段"。 */
|
|
707
765
|
localAddresses: addresses,
|
|
708
766
|
broadcastTargets: broadcastAddresses(),
|
|
709
767
|
discoveryPort: port,
|
|
@@ -713,10 +771,7 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
713
771
|
baseUrl: `http://${entry.host}:${entry.httpPort}`,
|
|
714
772
|
name: entry.name,
|
|
715
773
|
})),
|
|
716
|
-
|
|
717
|
-
* 逐条结论。`ok` 为 false 的项就是需要处理的那一项 —— 不给一堆数据让人
|
|
718
|
-
* 自己判断。
|
|
719
|
-
*/
|
|
774
|
+
...(manual === undefined ? {} : { manual, reachable }),
|
|
720
775
|
checks: [
|
|
721
776
|
{
|
|
722
777
|
id: 'broadcast-possible',
|
|
@@ -729,17 +784,27 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
729
784
|
{
|
|
730
785
|
id: 'found-any',
|
|
731
786
|
ok: found.length > 0,
|
|
732
|
-
label: '
|
|
787
|
+
label: '广播扫描到了网关',
|
|
733
788
|
detail: found.length > 0
|
|
734
789
|
? `找到 ${found.length} 个`
|
|
735
|
-
: '
|
|
790
|
+
: '广播一个都没收到。若下面「手动地址」是通的,就是广播被拦(AP 隔离最常见),用手动地址即可',
|
|
736
791
|
},
|
|
792
|
+
...(manual === undefined
|
|
793
|
+
? []
|
|
794
|
+
: [{
|
|
795
|
+
id: 'tcp-reachable',
|
|
796
|
+
ok: reachable === true,
|
|
797
|
+
label: `TCP 能连到 ${manual}`,
|
|
798
|
+
detail: reachable === true
|
|
799
|
+
? 'TCP 通,可以直接用这个地址申请接入'
|
|
800
|
+
: 'TCP 也不通:两台机器不在同一网络,或对方没开网关/被防火墙拦',
|
|
801
|
+
}]),
|
|
737
802
|
],
|
|
738
803
|
hints: [
|
|
739
804
|
'两台机器必须在同一个二层网络(同一个路由器的同一网段,例如都是 192.168.31.x)',
|
|
740
805
|
'很多路由器/访客 WiFi 默认开启「AP 隔离」,它会拦掉设备之间的广播 —— 换成主网络再试',
|
|
741
806
|
'Windows 首次开启局域网访问可能需要在防火墙里放行 UDP 8791 与 TCP 8790',
|
|
742
|
-
'
|
|
807
|
+
'广播被拦时直接用手动地址:http://<对方IP>:8790',
|
|
743
808
|
],
|
|
744
809
|
})
|
|
745
810
|
return
|
|
@@ -858,18 +923,40 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
858
923
|
return
|
|
859
924
|
}
|
|
860
925
|
if (method === 'POST' && path === '/peers/remove') {
|
|
926
|
+
/*
|
|
927
|
+
* 接收方断开一台网关。
|
|
928
|
+
*
|
|
929
|
+
* **要通知对方。** 只删自己这边的 peer,分享方那边的 key 和分享记录还在,
|
|
930
|
+
* 界面显示「共享给某某」却没人用了 —— 用户报的就是这个不同步。
|
|
931
|
+
*
|
|
932
|
+
* 通知走一次尽力而为的请求:对方可能已经关机、可能撤销了。**通知失败不能
|
|
933
|
+
* 阻止本地断开**,否则用户会被一台连不上的机器卡住。所以先删本地,再通知。
|
|
934
|
+
*/
|
|
861
935
|
const body = await readJsonBody(req)
|
|
862
936
|
const id = typeof body?.id === 'string' ? body.id : ''
|
|
863
937
|
const before = readPeers()
|
|
938
|
+
const target = before.find((entry) => entry.id === id)
|
|
864
939
|
const after = before.filter((entry) => entry.id !== id)
|
|
865
940
|
if (after.length === before.length) {
|
|
866
941
|
sendJson(res, 404, { error: `no such peer: ${id}` })
|
|
867
942
|
return
|
|
868
943
|
}
|
|
869
944
|
writePeers(after)
|
|
870
|
-
|
|
945
|
+
|
|
946
|
+
/* 尽力通知对方:让它在自己那边把这次分享收回。 */
|
|
947
|
+
let notified = false
|
|
948
|
+
if (target !== undefined) {
|
|
949
|
+
notified = await notifyDisconnect(target, ctx.logger)
|
|
950
|
+
}
|
|
951
|
+
sendJson(res, 200, {
|
|
952
|
+
ok: true,
|
|
953
|
+
peers: after.map(publicPeer),
|
|
954
|
+
notified,
|
|
955
|
+
...(notified ? {} : { note: 'the other device could not be told; revoke the share there if you want it gone' }),
|
|
956
|
+
})
|
|
871
957
|
return
|
|
872
958
|
}
|
|
959
|
+
|
|
873
960
|
if (method === 'POST' && path === '/peers/refresh') {
|
|
874
961
|
/* 拉一次某台网关的实时模型清单,顺便把它缓存回 peers。 */
|
|
875
962
|
const body = await readJsonBody(req)
|
|
@@ -891,6 +978,39 @@ async function dispatchAdmin(req, res, ctx, env) {
|
|
|
891
978
|
return
|
|
892
979
|
}
|
|
893
980
|
|
|
981
|
+
if (method === 'GET' && path === '/lan/status') {
|
|
982
|
+
/*
|
|
983
|
+
* 接收方的接入状态:宿主认识 `workbuddy-lan` 吗、它现在能列出哪些模型。
|
|
984
|
+
*
|
|
985
|
+
* 这是「设置页能看到模型、会话里却没有」这类问题的判断依据 —— 两种情况
|
|
986
|
+
* 各有明确原因,看一眼就知道该修哪。
|
|
987
|
+
*/
|
|
988
|
+
const llm = ctx.get('llm')
|
|
989
|
+
const providers = llm === undefined ? [] : llm.listProviders().map((entry) => entry.id)
|
|
990
|
+
const registered = providers.includes(LAN_PROVIDER)
|
|
991
|
+
let models = []
|
|
992
|
+
let error
|
|
993
|
+
if (registered) {
|
|
994
|
+
try {
|
|
995
|
+
models = (await llm.listModels(LAN_PROVIDER)).map((model) => ({ id: model.id, name: model.name }))
|
|
996
|
+
} catch (caught) {
|
|
997
|
+
error = caught instanceof Error ? caught.message : String(caught)
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
const peers = readPeers()
|
|
1001
|
+
sendJson(res, 200, {
|
|
1002
|
+
mode: env.config.mode === 'client' ? 'client' : 'upstream',
|
|
1003
|
+
provider: LAN_PROVIDER,
|
|
1004
|
+
registered,
|
|
1005
|
+
providers,
|
|
1006
|
+
peers: peers.map((peer) => ({ id: peer.id, label: peer.label, baseUrl: peer.baseUrl, models: (peer.models ?? []).length })),
|
|
1007
|
+
models,
|
|
1008
|
+
...(error === undefined ? {} : { error }),
|
|
1009
|
+
hints: buildLanHints({ mode: env.config.mode, registered, peers, models }),
|
|
1010
|
+
})
|
|
1011
|
+
return
|
|
1012
|
+
}
|
|
1013
|
+
|
|
894
1014
|
if (method === 'POST' && path === '/config/mode') {
|
|
895
1015
|
/*
|
|
896
1016
|
* 切换运行模式。
|
|
@@ -1546,6 +1666,112 @@ function publicPeer(peer) {
|
|
|
1546
1666
|
}
|
|
1547
1667
|
}
|
|
1548
1668
|
|
|
1669
|
+
/**
|
|
1670
|
+
* 测一个网关地址的 TCP 是否可达。
|
|
1671
|
+
*
|
|
1672
|
+
* 用 HTTP 请求而不是裸 TCP 连接:能顺带确认「端口通但上面不是网关」这种情况,
|
|
1673
|
+
* 那是另一个需要区别对待的失败。
|
|
1674
|
+
*
|
|
1675
|
+
* 任何 HTTP 响应(包括 401/404)都算「通」—— 能应答就说明网络是通的。
|
|
1676
|
+
*
|
|
1677
|
+
* @param baseUrl 已规整的网关地址
|
|
1678
|
+
* @param timeoutMs 超时
|
|
1679
|
+
*/
|
|
1680
|
+
async function probeTcp(baseUrl, timeoutMs = 2500) {
|
|
1681
|
+
try {
|
|
1682
|
+
await fetch(`${baseUrl}/healthz`, { signal: AbortSignal.timeout(timeoutMs) })
|
|
1683
|
+
return true
|
|
1684
|
+
} catch {
|
|
1685
|
+
/*
|
|
1686
|
+
* 走到这里说明连 HTTP 响应都没拿到:DNS 失败、ECONNREFUSED、超时。
|
|
1687
|
+
* 都属于「不通」—— 能应答的服务器至少会返回 401 或 404。
|
|
1688
|
+
*/
|
|
1689
|
+
return false
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
/**
|
|
1694
|
+
* 接收方断开时通知分享方。
|
|
1695
|
+
*
|
|
1696
|
+
* 用**那把 key 自己的 secret** 认证:它就是这台设备持有的凭据,撤销自己天经地义。
|
|
1697
|
+
* 不需要额外的身份机制。
|
|
1698
|
+
*
|
|
1699
|
+
* 尽力而为:超时短(3 秒)、失败不抛。对方可能已经关机、已经撤销,这些都不该
|
|
1700
|
+
* 阻止本地断开。
|
|
1701
|
+
*
|
|
1702
|
+
* @param peer 要断开的网关
|
|
1703
|
+
* @param logger 日志
|
|
1704
|
+
* @returns 是否通知成功
|
|
1705
|
+
*/
|
|
1706
|
+
async function notifyDisconnect(peer, logger) {
|
|
1707
|
+
try {
|
|
1708
|
+
const response = await fetch(`${peer.baseUrl}/peer/disconnect`, {
|
|
1709
|
+
method: 'POST',
|
|
1710
|
+
headers: {
|
|
1711
|
+
'Content-Type': 'application/json',
|
|
1712
|
+
Authorization: `Bearer ${peer.secret}`,
|
|
1713
|
+
},
|
|
1714
|
+
signal: AbortSignal.timeout(3000),
|
|
1715
|
+
})
|
|
1716
|
+
if (!response.ok) {
|
|
1717
|
+
logger?.info?.(`workbuddy-gateway: the gateway answered ${response.status} to the disconnect notice`)
|
|
1718
|
+
return false
|
|
1719
|
+
}
|
|
1720
|
+
return true
|
|
1721
|
+
} catch (error) {
|
|
1722
|
+
logger?.info?.(`workbuddy-gateway: could not tell the gateway we disconnected: ${error instanceof Error ? error.message : String(error)}`)
|
|
1723
|
+
return false
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* 「接入的模型为什么没出现在会话里」的逐条判断。
|
|
1729
|
+
*
|
|
1730
|
+
* 三种情况各有明确原因,混在一起只会让人猜:
|
|
1731
|
+
* 1. 不在 client 模式 → 根本没注册 provider
|
|
1732
|
+
* 2. 注册了但一个 peer 都没有 → 还没接入
|
|
1733
|
+
* 3. 有 peer 但模型数为 0 → 接入时的模型清单是空的,刷新一下
|
|
1734
|
+
*
|
|
1735
|
+
* @param input `{ mode, registered, peers, models }`
|
|
1736
|
+
*/
|
|
1737
|
+
function buildLanHints({ mode, registered, peers, models }) {
|
|
1738
|
+
const hints = []
|
|
1739
|
+
if (mode !== 'client') {
|
|
1740
|
+
hints.push('当前是「从上游插件获取」模式;切到「接入其他设备」后本机才会注册局域网 provider')
|
|
1741
|
+
return hints
|
|
1742
|
+
}
|
|
1743
|
+
if (!registered) {
|
|
1744
|
+
hints.push('provider 没有注册成功,检查日志里有没有 "could not register the LAN provider"')
|
|
1745
|
+
return hints
|
|
1746
|
+
}
|
|
1747
|
+
if (peers.length === 0) {
|
|
1748
|
+
hints.push('还没有接入任何网关;在下方「接入其他设备的网关」里申请一次')
|
|
1749
|
+
return hints
|
|
1750
|
+
}
|
|
1751
|
+
if (models.length === 0) {
|
|
1752
|
+
hints.push('已接入网关但它的模型清单是空的;点该网关的「刷新模型」')
|
|
1753
|
+
}
|
|
1754
|
+
return hints
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/**
|
|
1758
|
+
* 分享生成的 key 用来自动命名。
|
|
1759
|
+
*
|
|
1760
|
+
* 目标是**在设置页里一眼能分出来**,所以优先用设备名,其次地址。两者都没有时
|
|
1761
|
+
* 才退成 `LAN share` —— 那种情况说明对方既没报名字、我们也没拿到地址,极少见。
|
|
1762
|
+
*
|
|
1763
|
+
* @param deviceName 对方自报的名字
|
|
1764
|
+
* @param address 服务端看到的对端地址
|
|
1765
|
+
*/
|
|
1766
|
+
function defaultShareLabel(deviceName, address) {
|
|
1767
|
+
const name = typeof deviceName === 'string' ? deviceName.trim() : ''
|
|
1768
|
+
const host = typeof address === 'string' ? address.trim() : ''
|
|
1769
|
+
if (name !== '' && host !== '') return `共享给 ${name} (${host})`.slice(0, 80)
|
|
1770
|
+
if (name !== '') return `共享给 ${name}`.slice(0, 80)
|
|
1771
|
+
if (host !== '') return `共享给 ${host}`.slice(0, 80)
|
|
1772
|
+
return 'LAN share'
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1549
1775
|
/**
|
|
1550
1776
|
* 对端地址(去掉 IPv6 映射前缀)。
|
|
1551
1777
|
*
|
|
@@ -1914,4 +2140,13 @@ export function normalizeBaseUrlForTest(value) {
|
|
|
1914
2140
|
return normalizeBaseUrl(value)
|
|
1915
2141
|
}
|
|
1916
2142
|
|
|
2143
|
+
/**
|
|
2144
|
+
* 测试用入口:分享 key 的自动命名。生产代码不走它。
|
|
2145
|
+
* @param deviceName 对方名字
|
|
2146
|
+
* @param address 对方地址
|
|
2147
|
+
*/
|
|
2148
|
+
export function defaultShareLabelForTest(deviceName, address) {
|
|
2149
|
+
return defaultShareLabel(deviceName, address)
|
|
2150
|
+
}
|
|
2151
|
+
|
|
1917
2152
|
export { PREFIX, ADMIN_PREFIX, normalizeConfig }
|