dsh-connect-workbuddy-gateway 1.5.0 → 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
- 覆盖 327 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
561
+ 覆盖 339 项:首次建 key 与惰性补选、鉴权、模型勾选与清单投影、重名后缀(区域 / 昵称 /
562
562
  非 ASCII 序号)、跨区同名、按名字路由、推理档透传、**固定监听端口与占用提示**、**局域网分享与接入**、**两种角色模式**、
563
563
  并行工具调用按 index 分组、
564
564
  Responses 流的规范校验(`sequence_number`、part 一致性、terminal 的 output 顺序)、
package/index.js CHANGED
@@ -207,10 +207,10 @@ export function apply(ctx, config) {
207
207
  * **client 模式:把已接入的网关注册成 DSH 的模型来源。**
208
208
  *
209
209
  * 这是「装上插件就能在会话里用那台机器的模型」的落点。只存 peers 是不够的 ——
210
- * 宿主要先认识那个 provider,模型选择器里才会出现它。
210
+ * 宿主要先认识那个 provider,模型选择器里才会出现它,会话里才选得到。
211
211
  *
212
- * 用的是鸭子类型的 adapter(见 src/lan-adapter.js):不继承 `LlmAdapter`,
213
- * 因为那个类所在的包插件解析不到。注册表只调那几个方法,这样就够了。
212
+ * 不需要 import `LlmAdapter`:那个包在运行时解析不到(见 src/lan-adapter.js
213
+ * 文件头),而基类唯一有逻辑的方法 `prepareCall` 我们已经自己实现了。
214
214
  */
215
215
  if (settings.mode === 'client') {
216
216
  ctx.effect(() => {
@@ -225,15 +225,15 @@ export function apply(ctx, config) {
225
225
  getPeers: readPeers,
226
226
  logger: ctx.logger,
227
227
  }))
228
+ ctx.logger.info(`workbuddy-gateway: registered provider "${LAN_PROVIDER}" for shared models`)
228
229
  } catch (error) {
229
230
  /*
230
- * 重复注册(例如插件被热重载两次)不该把整个插件搞崩 —— 那只意味着
231
- * 这个 provider 已经有人服务了。
231
+ * 重复注册(插件被热重载两次)只意味着这个 provider 已经有人服务;
232
+ * 不该把插件搞崩。
232
233
  */
233
234
  ctx.logger.warn(`workbuddy-gateway: could not register the LAN provider: ${error instanceof Error ? error.message : String(error)}`)
234
235
  return () => {}
235
236
  }
236
- ctx.logger.info(`workbuddy-gateway: registered provider "${LAN_PROVIDER}" for shared models`)
237
237
  return () => {
238
238
  try {
239
239
  handle()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-connect-workbuddy-gateway",
3
- "version": "1.5.0",
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",
@@ -57,39 +57,69 @@ export function decodeModelId(value) {
57
57
  /**
58
58
  * 造一个 adapter:把 DSH 的调用转到远端网关。
59
59
  *
60
- * ## 为什么不继承 `LlmAdapter`
60
+ * ## 为什么不用 `extends LlmAdapter`
61
61
  *
62
- * 宿主约定 `registerAdapter(providers, adapter)` 收一个 `LlmAdapter`,但那是个
63
- * **带默认实现的抽象类**,而它所在的包(`@deepseek-ai/dsh-llm-pi-ai`)打在
64
- * `app.asar` 里,插件从 profile 的 node_modules 解析不到 —— 上游插件能 import 是
65
- * 因为它装在能看见宿主依赖的位置。
62
+ * 理论上该继承它,但**那个包在运行时分母解析不到**:
66
63
  *
67
- * 所以这里用**鸭子类型**:提供一个同名方法的普通对象。注册表只调这些方法,
68
- * 不需要真的 `instanceof`。少一层继承,也少一个「安装位置变了就炸」的依赖。
64
+ * ```
65
+ * import('@deepseek-ai/dsh-llm')
66
+ * -> ERR_MODULE_NOT_FOUND
67
+ * ```
68
+ *
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
+ * ## 教训
85
+ *
86
+ * 早先这里是个「只有同名方法的普通对象」,注册和列表都正常、模型也出现在选择器
87
+ * 里,但第一次对话就报:
88
+ *
89
+ * ```
90
+ * registration.adapter.prepareCall is not a function
91
+ * ```
92
+ *
93
+ * 宿主**不只调你实现的那几个方法**。所以这里把基类的八个方法全部提供,一个不落。
69
94
  *
70
95
  * @param options 配置
71
96
  * @param options.getPeers 返回当前 peers 的函数(每次现读,接入/断开立刻生效)
72
97
  * @param options.logger 日志
73
98
  */
74
99
  export function createLanAdapter({ getPeers, logger }) {
75
- return {
100
+ const adapter = {
76
101
  /** 宿主要显示的 provider 名字。 */
77
102
  providerInfo(provider) {
78
103
  return { id: provider, name: 'WorkBuddy(局域网接入)' }
79
104
  },
80
105
 
81
- /** 重试策略交给宿主默认(不返回自定义策略)。 */
106
+ /** 没有自定义重试策略,交给宿主默认。 */
82
107
  providerRetryPolicy() {
83
108
  return undefined
84
109
  },
85
110
 
111
+ /** 远端投影会丢掉图片,所以没有图片定价。 */
86
112
  imageRequestPricing() {
87
113
  return undefined
88
114
  },
89
115
 
90
- /** 远端投影会把图片丢掉,所以给一个「不接受图片」的兜底尺寸。 */
116
+ /** 同上:给一个不放大图片的兜底尺寸。 */
91
117
  imageRequestTarget(_provider, _model, image) {
92
- return { width: image?.width ?? 0, height: image?.height ?? 0, maxBytes: image?.bytes ?? 0 }
118
+ return {
119
+ width: image?.width ?? 0,
120
+ height: image?.height ?? 0,
121
+ maxBytes: image?.bytes ?? 0,
122
+ }
93
123
  },
94
124
 
95
125
  /**
@@ -134,73 +164,91 @@ export function createLanAdapter({ getPeers, logger }) {
134
164
  },
135
165
 
136
166
  /**
137
- * 起一条流。
167
+ * 准备一次调用 —— **这是宿主真正走的那条路**。
168
+ *
169
+ * 基类的默认实现就是「解析模型 + 交出绑定当前注册的 stream」;这里自己写,
170
+ * 因为基类解析不到(见文件头)。返回值形状必须带 `model` 与 `stream`。
138
171
  *
139
- * 把 DSH 的 `GenerateOptions` 翻成 OpenAI Chat 请求发给远端网关,再把回来的
140
- * SSE 翻成 `StreamChunk`。**失败也走 chunk 通道**(terminal error finish),
141
- * 不在生成器里抛 —— 与 host-backend.js 同一个理由:调用方先 `break` 时,
142
- * 生成器里的 throw 会被吞掉,表现为「流正常结束、错误消失」。
172
+ * `signal` 透传给远端请求:用户在 DSH 里点停止时,那条 HTTP 流要一起断。
143
173
  */
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
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 }) }),
167
179
  }
180
+ },
181
+ }
168
182
 
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
- }
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
198
+
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
+ }
179
215
 
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))
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' } } }
191
235
  return
192
236
  }
237
+ yield finishError(describeFetchFailure(error))
238
+ return
239
+ }
193
240
 
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
- },
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' } }
203
249
  }
250
+
251
+ return adapter
204
252
  }
205
253
 
206
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` 吗、它现在能列出哪些模型。