dsh-connect-workbuddy-gateway 1.5.1 → 1.5.2

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 CHANGED
@@ -558,7 +558,7 @@ hy4flash-free@#9 ← 昵称含中文/emoji,退化成序号
558
558
  node tests/harness.mjs
559
559
  ```
560
560
 
561
- 覆盖 338 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
561
+ 覆盖 339 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
562
562
  非 ASCII 序号)、跨区同名、按名字路由、推理档透传、**固定监听端口与占用提示**、**局域网分享与接入**、**两种角色模式**、
563
563
  并行工具调用按 index 分组、
564
564
  Responses 流的规范校验(`sequence_number`、part 一致性、terminal 的 output 顺序)、
package/index.js CHANGED
@@ -207,11 +207,10 @@ export function apply(ctx, config) {
207
207
  * **client 模式:把已接入的网关注册成 DSH 的模型来源。**
208
208
  *
209
209
  * 这是「装上插件就能在会话里用那台机器的模型」的落点。只存 peers 是不够的 ——
210
- * 宿主要先认识那个 provider,模型选择器里才会出现它。
210
+ * 宿主要先认识那个 provider,模型选择器里才会出现它,会话里才选得到。
211
211
  *
212
- * `LlmAdapter` 从 `@deepseek-ai/dsh-llm` 取(上游插件同样从那里取符号,DSH 会把
213
- * 这些包注入插件的解析路径)。用**动态 import**:静态 import 一旦解析不到,
214
- * 整个插件都加载不起来;动态的只让「接入共享模型」这一项失败,并给出原因。
212
+ * 不需要 import `LlmAdapter`:那个包在运行时解析不到(见 src/lan-adapter.js
213
+ * 文件头),而基类唯一有逻辑的方法 `prepareCall` 我们已经自己实现了。
215
214
  */
216
215
  if (settings.mode === 'client') {
217
216
  ctx.effect(() => {
@@ -220,36 +219,24 @@ export function apply(ctx, config) {
220
219
  ctx.logger.warn('workbuddy-gateway: no llm service, so shared models cannot be offered')
221
220
  return () => {}
222
221
  }
223
-
224
- let disposed = false
225
222
  let handle
226
-
227
- /* 异步就位,所以注册结果只能在这里拿到;卸载前要等到它。 */
228
- void import('@deepseek-ai/dsh-llm').then((module) => {
229
- if (disposed) return
230
- const Adapter = module.LlmAdapter
231
- if (typeof Adapter !== 'function') {
232
- ctx.logger.warn('workbuddy-gateway: this DSH build does not export LlmAdapter, so shared models cannot be offered')
233
- return
234
- }
223
+ try {
235
224
  handle = llm.registerAdapter([LAN_PROVIDER], createLanAdapter({
236
225
  getPeers: readPeers,
237
226
  logger: ctx.logger,
238
- Adapter,
239
227
  }))
240
228
  ctx.logger.info(`workbuddy-gateway: registered provider "${LAN_PROVIDER}" for shared models`)
241
- }).catch((error) => {
229
+ } catch (error) {
242
230
  /*
243
231
  * 重复注册(插件被热重载两次)只意味着这个 provider 已经有人服务;
244
- * 解析不到 `dsh-llm` 则说明宿主太旧。两种都不该把插件搞崩。
232
+ * 不该把插件搞崩。
245
233
  */
246
234
  ctx.logger.warn(`workbuddy-gateway: could not register the LAN provider: ${error instanceof Error ? error.message : String(error)}`)
247
- })
248
-
235
+ return () => {}
236
+ }
249
237
  return () => {
250
- disposed = true
251
238
  try {
252
- handle?.()
239
+ handle()
253
240
  } catch {
254
241
  /* 已经卸载了 */
255
242
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-connect-workbuddy-gateway",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
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",
@@ -31,9 +31,6 @@
31
31
  "engines": {
32
32
  "node": "^22.19.0 || >=24.0.0"
33
33
  },
34
- "peerDependencies": {
35
- "@deepseek-ai/dsh-llm": ">=0.1.7-rc.1 <0.3.0-0"
36
- },
37
34
  "publishConfig": {
38
35
  "registry": "https://registry.npmjs.org/",
39
36
  "access": "public"
@@ -57,34 +57,70 @@ export function decodeModelId(value) {
57
57
  /**
58
58
  * 造一个 adapter:把 DSH 的调用转到远端网关。
59
59
  *
60
- * ## 为什么必须继承 `LlmAdapter`
60
+ * ## 为什么不用 `extends LlmAdapter`
61
61
  *
62
- * 最初这里用鸭子类型(一个带同名方法的普通对象),注册成功、模型也出现在选择器里,
63
- * 但一发起对话就报:
62
+ * 理论上该继承它,但**那个包在运行时分母解析不到**:
64
63
  *
65
64
  * ```
66
- * registration.adapter.prepareCall is not a function
65
+ * import('@deepseek-ai/dsh-llm')
66
+ * -> ERR_MODULE_NOT_FOUND
67
67
  * ```
68
68
  *
69
- * 因为宿主**不只调我实现的那几个方法**。`prepareCall` 是基类提供的(它把
70
- * `resolveModel` 与 `stream` 组合成一次带注册快照的调用),普通对象没有它,
71
- * 运行时直接崩。基类还提供 `providerRetryPolicy` / `imageRequestPricing` 等默认
72
- * 实现,将来宿主新增方法时也会跟着有。
69
+ * `@deepseek-ai/*` 这些运行时包打在 DSH 的 `app.asar` 里,宿主并不通过 node 的模块
70
+ * 解析把它们暴露给插件;插件拿到 `llm` 服务靠的是 `ctx.get('llm')`,不是 import。
71
+ * 实测两台机器(Windows 装了上游插件、Mac 没装)都解析不到,所以这不是安装位置的
72
+ * 偶然问题。
73
+ *
74
+ * ## 那就把基类该做的事自己实现
75
+ *
76
+ * `LlmAdapter` 的声明(宿主 inspect 给出的原文)只有八个方法,其中 `prepareCall`
77
+ * 是**唯一一个有实际逻辑的默认实现**,文档说它:
78
+ *
79
+ * > Resolve one call under its current adapter registration.
80
+ *
81
+ * 也就是 `resolveModel` + 一个绑定当前注册的 `stream`。这两件事我这里都有,所以
82
+ * 自己组合即可 —— 这也正是之前漏掉它导致崩溃的那一步。
83
+ *
84
+ * ## 教训
73
85
  *
74
- * `LlmAdapter` 从 `@deepseek-ai/dsh-llm` 导入 —— 上游插件同样从这里取符号,
75
- * 说明 DSH 运行时会把这些包注入到插件的模块解析路径里。
86
+ * 早先这里是个「只有同名方法的普通对象」,注册和列表都正常、模型也出现在选择器
87
+ * 里,但第一次对话就报:
88
+ *
89
+ * ```
90
+ * registration.adapter.prepareCall is not a function
91
+ * ```
92
+ *
93
+ * 宿主**不只调你实现的那几个方法**。所以这里把基类的八个方法全部提供,一个不落。
76
94
  *
77
95
  * @param options 配置
78
96
  * @param options.getPeers 返回当前 peers 的函数(每次现读,接入/断开立刻生效)
79
97
  * @param options.logger 日志
80
- * @param options.Adapter `LlmAdapter` 基类
81
98
  */
82
- export function createLanAdapter({ getPeers, logger, Adapter }) {
83
- class LanAdapter extends Adapter {
99
+ export function createLanAdapter({ getPeers, logger }) {
100
+ const adapter = {
84
101
  /** 宿主要显示的 provider 名字。 */
85
102
  providerInfo(provider) {
86
103
  return { id: provider, name: 'WorkBuddy(局域网接入)' }
87
- }
104
+ },
105
+
106
+ /** 没有自定义重试策略,交给宿主默认。 */
107
+ providerRetryPolicy() {
108
+ return undefined
109
+ },
110
+
111
+ /** 远端投影会丢掉图片,所以没有图片定价。 */
112
+ imageRequestPricing() {
113
+ return undefined
114
+ },
115
+
116
+ /** 同上:给一个不放大图片的兜底尺寸。 */
117
+ imageRequestTarget(_provider, _model, image) {
118
+ return {
119
+ width: image?.width ?? 0,
120
+ height: image?.height ?? 0,
121
+ maxBytes: image?.bytes ?? 0,
122
+ }
123
+ },
88
124
 
89
125
  /**
90
126
  * 列出所有已接入网关的模型。
@@ -104,7 +140,7 @@ export function createLanAdapter({ getPeers, logger, Adapter }) {
104
140
  }
105
141
  }
106
142
  return out
107
- }
143
+ },
108
144
 
109
145
  /** 解析一个模型的元信息。上下文窗口必须给数值,否则长对话会被截断。 */
110
146
  async resolveModel(provider, model) {
@@ -125,78 +161,94 @@ export function createLanAdapter({ getPeers, logger, Adapter }) {
125
161
  ? {}
126
162
  : { reasoning: { efforts: efforts.map((effort) => ({ id: effort, name: effort })) } }),
127
163
  }
128
- }
164
+ },
129
165
 
130
166
  /**
131
- * 起一条流。
167
+ * 准备一次调用 —— **这是宿主真正走的那条路**。
168
+ *
169
+ * 基类的默认实现就是「解析模型 + 交出绑定当前注册的 stream」;这里自己写,
170
+ * 因为基类解析不到(见文件头)。返回值形状必须带 `model` 与 `stream`。
132
171
  *
133
- * 把 DSH 的 `GenerateOptions` 翻成 OpenAI Chat 请求发给远端网关,再把回来的
134
- * SSE 翻成 `StreamChunk`。**失败也走 chunk 通道**(terminal error finish),
135
- * 不在生成器里抛 —— 与 host-backend.js 同一个理由:调用方先 `break` 时,
136
- * 生成器里的 throw 会被吞掉,表现为「流正常结束、错误消失」。
172
+ * `signal` 透传给远端请求:用户在 DSH 里点停止时,那条 HTTP 流要一起断。
137
173
  */
138
- async *stream(options) {
139
- const found = findPeerModel(getPeers(), options.model)
140
- if (found === undefined) {
141
- yield finishError(`the gateway for this model is no longer connected: ${options.model}`)
142
- return
143
- }
144
- const { peer, modelId } = found
145
-
146
- const body = buildChatRequest(modelId, options)
147
- let response
148
- try {
149
- response = await fetch(`${peer.baseUrl}/v1/chat/completions`, {
150
- method: 'POST',
151
- headers: {
152
- 'Content-Type': 'application/json',
153
- Authorization: `Bearer ${peer.secret}`,
154
- },
155
- body: JSON.stringify(body),
156
- signal: options.signal,
157
- })
158
- } catch (error) {
159
- yield finishError(describeFetchFailure(error))
160
- return
174
+ async prepareCall(provider, model, signal) {
175
+ const resolved = await this.resolveModel(provider, model)
176
+ return {
177
+ model: resolved,
178
+ stream: (options) => this.stream({ ...options, provider, model, ...(signal === undefined ? {} : { signal }) }),
161
179
  }
180
+ },
181
+ }
162
182
 
163
- if (!response.ok) {
164
- /* 把远端的错误读出来给用户看,而不是只说「失败了」。 */
165
- const text = await response.text().catch(() => '')
166
- yield finishError(describeHttpFailure(response.status, text))
167
- return
168
- }
169
- if (response.body === null) {
170
- yield finishError('the gateway returned no stream body')
171
- return
172
- }
183
+ /**
184
+ * 起一条流。
185
+ *
186
+ * 把 DSH 的 `GenerateOptions` 翻成 OpenAI Chat 请求发给远端网关,再把回来的
187
+ * SSE 翻成 `StreamChunk`。**失败也走 chunk 通道**(terminal error finish),
188
+ * 不在生成器里抛 —— 与 host-backend.js 同一个理由:调用方先 `break` 时,
189
+ * 生成器里的 throw 会被吞掉,表现为「流正常结束、错误消失」。
190
+ */
191
+ adapter.stream = async function* stream(options) {
192
+ const found = findPeerModel(getPeers(), options.model)
193
+ if (found === undefined) {
194
+ yield finishError(`the gateway for this model is no longer connected: ${options.model}`)
195
+ return
196
+ }
197
+ const { peer, modelId } = found
173
198
 
174
- const state = { index: 0, textIndex: -1, reasoningIndex: -1, tools: new Map() }
175
- try {
176
- for await (const event of readChatSse(response.body)) {
177
- for (const chunk of chunksOf(event, state)) yield chunk
178
- }
179
- } catch (error) {
180
- if (options.signal?.aborted === true) {
181
- yield { type: 'finish', reason: { kind: 'aborted', failure: { message: 'cancelled', code: 'ABORTED' } } }
182
- return
183
- }
184
- yield finishError(describeFetchFailure(error))
199
+ const body = buildChatRequest(modelId, options)
200
+ let response
201
+ try {
202
+ response = await fetch(`${peer.baseUrl}/v1/chat/completions`, {
203
+ method: 'POST',
204
+ headers: {
205
+ 'Content-Type': 'application/json',
206
+ Authorization: `Bearer ${peer.secret}`,
207
+ },
208
+ body: JSON.stringify(body),
209
+ signal: options.signal,
210
+ })
211
+ } catch (error) {
212
+ yield finishError(describeFetchFailure(error))
213
+ return
214
+ }
215
+
216
+ if (!response.ok) {
217
+ /* 把远端的错误读出来给用户看,而不是只说「失败了」。 */
218
+ const text = await response.text().catch(() => '')
219
+ yield finishError(describeHttpFailure(response.status, text))
220
+ return
221
+ }
222
+ if (response.body === null) {
223
+ yield finishError('the gateway returned no stream body')
224
+ return
225
+ }
226
+
227
+ const state = { index: 0, textIndex: -1, reasoningIndex: -1, tools: new Map() }
228
+ try {
229
+ for await (const event of readChatSse(response.body)) {
230
+ for (const chunk of chunksOf(event, state)) yield chunk
231
+ }
232
+ } catch (error) {
233
+ if (options.signal?.aborted === true) {
234
+ yield { type: 'finish', reason: { kind: 'aborted', failure: { message: 'cancelled', code: 'ABORTED' } } }
185
235
  return
186
236
  }
187
-
188
- /*
189
- * 收尾:把还没关的 block 关掉。
190
- *
191
- * DSH 依赖 `block-end` 才能把工具调用交给执行层;漏掉它,模型「调了工具」
192
- * 但会话里什么都没发生。
193
- */
194
- for (const chunk of closeBlocks(state)) yield chunk
195
- yield { type: 'finish', reason: { kind: 'stop' } }
237
+ yield finishError(describeFetchFailure(error))
238
+ return
196
239
  }
240
+
241
+ /*
242
+ * 收尾:把还没关的 block 关掉。
243
+ *
244
+ * DSH 依赖 `block-end` 才能把工具调用交给执行层;漏掉它,模型「调了工具」
245
+ * 但会话里什么都没发生。
246
+ */
247
+ for (const chunk of closeBlocks(state)) yield chunk
248
+ yield { type: 'finish', reason: { kind: 'stop' } }
197
249
  }
198
250
 
199
- return new LanAdapter()
251
+ return adapter
200
252
  }
201
253
 
202
254
  /**
package/src/routes.js CHANGED
@@ -978,6 +978,53 @@ async function dispatchAdmin(req, res, ctx, env) {
978
978
  return
979
979
  }
980
980
 
981
+ if (method === 'POST' && path === '/lan/probe') {
982
+ /*
983
+ * 自检:宿主能不能真的用这个 provider 发起一次调用。
984
+ *
985
+ * 起因是一个真实故障 —— adapter 只是「方法名相同」的普通对象时,注册和
986
+ * 列表都正常(模型出现在选择器里),但第一次对话就崩:
987
+ *
988
+ * registration.adapter.prepareCall is not a function
989
+ *
990
+ * 因为这个方法是 `LlmAdapter` 基类提供的。只看「注册成功」不够,必须让
991
+ * 宿主真的解析一个模型,才能证明整条路径可用。
992
+ *
993
+ * 这里用 `resolveModelInfo`(它会走到 adapter 的 resolveModel),不发起
994
+ * 真实对话 —— 那个要花钱,用户自己会试。
995
+ */
996
+ const body = await readJsonBody(req)
997
+ const llm = ctx.get('llm')
998
+ if (llm === undefined) {
999
+ sendJson(res, 503, { error: 'no llm service' })
1000
+ return
1001
+ }
1002
+ const modelId = typeof body?.modelId === 'string' && body.modelId !== ''
1003
+ ? body.modelId
1004
+ : (await llm.listModels(LAN_PROVIDER).catch(() => []))[0]?.id
1005
+ if (modelId === undefined) {
1006
+ sendJson(res, 400, { error: 'no model to probe; connect a gateway first' })
1007
+ return
1008
+ }
1009
+ try {
1010
+ const info = await llm.resolveModelInfo(LAN_PROVIDER, modelId)
1011
+ sendJson(res, 200, {
1012
+ ok: true,
1013
+ modelId,
1014
+ name: info?.name,
1015
+ contextWindow: info?.context?.contextWindow,
1016
+ maxTokens: info?.defaultMaxTokens,
1017
+ })
1018
+ } catch (error) {
1019
+ sendJson(res, 500, {
1020
+ ok: false,
1021
+ modelId,
1022
+ error: error instanceof Error ? error.message : String(error),
1023
+ code: error?.code,
1024
+ })
1025
+ }
1026
+ return
1027
+ }
981
1028
  if (method === 'GET' && path === '/lan/status') {
982
1029
  /*
983
1030
  * 接收方的接入状态:宿主认识 `workbuddy-lan` 吗、它现在能列出哪些模型。