dsh-qwenwork-connect 0.2.2 → 0.3.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/lib/index.js CHANGED
@@ -27,8 +27,11 @@ import {
27
27
  } from './models.js';
28
28
  import {
29
29
  getAccountContext,
30
+ getValidCredential,
30
31
  isWired,
31
32
  } from './credentials-seam.js';
33
+ import { CATALOG_TTL_MS, createCatalogStore } from './catalog.js';
34
+ import { relaxTlsForVpc, resolveGatewayEndpoint } from './endpoint.js';
32
35
  import { registerQwenWorkStatusRoute } from './web-status.js';
33
36
  import { registerDeviceLoginRoute } from './login-route.js';
34
37
  import { perfSummary } from './perf.js';
@@ -78,7 +81,7 @@ const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
78
81
  *
79
82
  * `baseUrl` 现在指向**本插件的环回 shim**(`./chat-shim.js`)。shim 负责:
80
83
  * 1. 把 pi-ai 的 OpenAI 协议请求转成 QwenWork 的推理请求;
81
- * 2. 用官方 WASM 生成签名(`Authorization: Bearer COSY.<...>`)并加密 body;
84
+ * 2. 用 COSY 信封签名(`Authorization: Bearer COSY.<...>`)并编码 body;
82
85
  * 3. 把上游的双层信封 SSE 转回标准 OpenAI SSE。
83
86
  *
84
87
  * ⚠️ `baseUrl` 在 shim 真正监听成功前是 `null`;此时 `createProvider` 会
@@ -90,6 +93,42 @@ const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
90
93
  */
91
94
  const SHIM_UNAVAILABLE_BASE_URL = 'http://127.0.0.1:1/qwenwork-shim-unavailable';
92
95
 
96
+ /**
97
+ * 单次请求的图片预算(聚合 base64 字节数 / 张数)。
98
+ *
99
+ * 取值依据(dsh-qwenwork-connector issue #4 的实测):
100
+ * · 6.3 MB 原图(base64 约 8.4 MB)→ 正常返回;
101
+ * · 15.7 MB 原图(50 张)→ 网关 NGHTTP2_ENHANCE_YOUR_CALM 掐断;
102
+ * · 实际长跑在上下文约 12.8 MB 图片时开始每轮必死。
103
+ *
104
+ * 这里取 6 MB / 32 张,给文本 body 和协议开销留余量。超过时 pi-ai 抛
105
+ * `IMAGE_OFFLOAD_REQUIRED`,宿主的 dsh-compaction-image-offload 会把最旧的
106
+ * 图片标记为 offloaded 后重试——不会再出现「整轮 UNKNOWN」。
107
+ */
108
+ const MAX_REQUEST_IMAGE_BYTES = 6 * 1024 * 1024;
109
+ const MAX_REQUEST_IMAGES = 32;
110
+
111
+ /**
112
+ * 取宿主附件服务(每次调用都现取)。
113
+ *
114
+ * ⚠️ 不能在插件启动时取一次就缓存(issue #1/#5 的根因):第三方 bundle 的
115
+ * 加载早于宿主 provision `attachments`,启动那一枪经常打空;一旦把
116
+ * `undefined` 固定进闭包,整个进程周期里图片都读不出来,只能重启赌时序。
117
+ *
118
+ * @param {any} ctx DSH 插件上下文
119
+ * @returns {any | undefined} 附件服务;未就绪或接口不合时返回 undefined
120
+ */
121
+ function readAttachments(ctx) {
122
+ try {
123
+ if (typeof ctx?.get !== 'function') return undefined;
124
+ const attachments = ctx.get('attachments');
125
+ if (attachments === null || attachments === undefined) return undefined;
126
+ return typeof attachments.readImageRequest === 'function' ? attachments : undefined;
127
+ } catch {
128
+ return undefined;
129
+ }
130
+ }
131
+
93
132
  /**
94
133
  * 从 DSH 上下文取图片链路所需的服务。
95
134
  *
@@ -97,34 +136,27 @@ const SHIM_UNAVAILABLE_BASE_URL = 'http://127.0.0.1:1/qwenwork-shim-unavailable'
97
136
  * - `ctx.get('attachments')` → 持久化附件服务
98
137
  * - `resolveImageAttachmentAccess(...)` → 把附件引用映射成可读文本
99
138
  *
100
- * 任何一步取不到都**返回空对象**(而不是半套配置)——
101
- * 这样 `createQwenWorkAdapter` 不会注册 `resolveAttachments`,
102
- * 模型描述符也就不会声明 image,避免「声明支持却一用就抛
103
- * `pi-ai image input requires the durable attachment service`」。
139
+ * `resolveAttachments` 是**惰性解析器**:pi-ai 在真正发图时才会调用它,
140
+ * 这时附件服务通常已经就绪。服务始终不存在时,pi-ai 会抛
141
+ * `pi-ai image input requires the durable attachment service`——只影响
142
+ * 带图请求,纯文本对话不受牵连。
104
143
  *
105
144
  * @param {any} ctx DSH 插件上下文
106
- * @returns {{ resolveAttachments?: () => any, resolveImageAccess?: Function }}
145
+ * @returns {{ resolveAttachments: () => any, resolveImageAccess: Function }}
107
146
  */
108
147
  function imageDepsFrom(ctx) {
109
- try {
110
- if (typeof ctx?.get !== 'function') return {};
111
- const attachments = ctx.get('attachments');
112
- if (attachments === undefined || attachments === null) return {};
113
- return {
114
- resolveAttachments: () => attachments,
115
- resolveImageAccess: (svc, ref) => {
116
- // ctx.get('fs') 可能不存在(取决于宿主配置);缺失时只给附件 id,
117
- // 不影响图片数据本身的读取(readImageRequest 走 attachments)。
118
- const mapHostPath =
119
- typeof ctx.get === 'function'
120
- ? (hostPath) => ctx.get('fs')?.processPathFromHostPath?.(hostPath)
121
- : undefined;
122
- return resolveImageAttachmentAccess(svc, mapHostPath, ref);
123
- },
124
- };
125
- } catch {
126
- return {};
127
- }
148
+ return {
149
+ resolveAttachments: () => readAttachments(ctx),
150
+ resolveImageAccess: (svc, ref) => {
151
+ // ctx.get('fs') 可能不存在(取决于宿主配置);缺失时只给附件 id,
152
+ // 不影响图片数据本身的读取(readImageRequest 走 attachments)。
153
+ const mapHostPath =
154
+ typeof ctx?.get === 'function'
155
+ ? (hostPath) => ctx.get('fs')?.processPathFromHostPath?.(hostPath)
156
+ : undefined;
157
+ return resolveImageAttachmentAccess(svc, mapHostPath, ref);
158
+ },
159
+ };
128
160
  }
129
161
 
130
162
  /**
@@ -135,18 +167,24 @@ function imageDepsFrom(ctx) {
135
167
  * @param {() => (string | null) | Promise<string | null>} getSharedSecret
136
168
  * 返回 shim 的共享密钥;未就绪时可为 `null`。允许返回 Promise——
137
169
  * 调用方会在未就绪时等待 shim 启动,而不是拿 null 去发无鉴权请求。
138
- * @param {{ resolveAttachments?: () => any, resolveImageAccess?: (attachments: any, ref: any) => string }} [image]
170
+ * @param {{ resolveAttachments: () => any, resolveImageAccess: (attachments: any, ref: any) => string }} [image]
139
171
  * 图片链路接入点。由 apply() 从 ctx 取 DSH 的附件服务后传入
140
172
  * (与官方 provider 的做法一致:`ctx.get('attachments')`)。
141
- * 不传时模型只能收文本——但那时模型描述符也不应声明 image。
173
+ * `resolveAttachments` 是惰性解析器,pi-ai 在发图时才调用。
174
+ * @param {() => Array<any>} [getCatalog] 当前模型目录(动态缓存 + 内置种子)
142
175
  */
143
- function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
144
- // 图片能力**由附件服务是否可用决定**:只有 pi-ai 拿到了
145
- // `resolveAttachments`,声明 image 才是真的能用;否则声明了也会在
146
- // 发图时抛错。两者必须同步,这是本项目反复出现的「声明与实现一致」原则。
176
+ function createQwenWorkAdapter(
177
+ getBaseUrl,
178
+ getSharedSecret,
179
+ image = {},
180
+ getCatalog = () => FALLBACK_QWENWORK_MODELS,
181
+ ) {
182
+ // 图片能力由**上游模型**决定(catalog 里 is_vl: true);附件服务是否就绪
183
+ // 交给 pi-ai 在发图时调用 `resolveAttachments()` 现取。启动时序不再影响
184
+ // 图片声明——这是 connector issue #1/#5 的教训。
147
185
  const imagesAvailable = typeof image.resolveAttachments === 'function';
148
186
  const buildModels = () =>
149
- FALLBACK_QWENWORK_MODELS.map((info) =>
187
+ getCatalog().map((info) =>
150
188
  toPiModel(info, getBaseUrl(), { supportsImages: imagesAvailable }),
151
189
  );
152
190
 
@@ -188,8 +226,9 @@ function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
188
226
  configuredMaxTokens: new Map(),
189
227
  modelErrors: new Map(),
190
228
  // 图片链路限额:模型声明支持 image 后,pi-ai 会按这些上限决定
191
- // 「原样内联」还是「降级为文本占位符」。取值与官方 provider 一致。
192
- maxRequestImageBytes: 20_971_520,
229
+ // 「原样内联」还是抛出 IMAGE_OFFLOAD_REQUIRED 交给宿主卸载最旧的图。
230
+ maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
231
+ maxRequestImages: MAX_REQUEST_IMAGES,
193
232
  requestImagePixelBudget: 4_194_304,
194
233
  requestImageMaxBytes: 1_048_576,
195
234
  piProvider: provider,
@@ -233,11 +272,11 @@ function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
233
272
  * resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(...)
234
273
  *
235
274
  * 只有**同时**声明模型支持 image,这条链路才会被走到;
236
- * 两者缺一都会出问题(声明 image 但无服务 → 抛错;有服务但不声明 → 走不到)。
275
+ * 声明由上游能力决定,服务在发图时现取——启动时附件服务没就绪不再
276
+ * 导致「整个进程周期都用不了图」。
237
277
  */
238
- ...(typeof image.resolveAttachments === 'function'
239
- ? { resolveAttachments: () => image.resolveAttachments() }
240
- : {}),
278
+ resolveAttachments: () =>
279
+ typeof image.resolveAttachments === 'function' ? image.resolveAttachments() : undefined,
241
280
  ...(typeof image.resolveImageAccess === 'function'
242
281
  ? {
243
282
  resolveImageAccess: (attachments, ref) => image.resolveImageAccess(attachments, ref),
@@ -338,14 +377,72 @@ export function chatShimSharedSecret() {
338
377
  * @param {any} config
339
378
  */
340
379
  export function apply(ctx, config) {
380
+ // ---- 动态模型目录 --------------------------------------------------
381
+ // 目录来自上游 `/algo/api/v2/model/list`(COSY 签名),5 分钟 TTL;
382
+ // 刷新失败保留上一次成功的快照,首次成功前用 models.js 的内置目录。
383
+ const catalogStore = createCatalogStore();
384
+ /** 未登录导致的目录拉取失败只提示一次,避免每 5 分钟刷一条日志。 */
385
+ let catalogAuthNoticed = false;
386
+ const refreshCatalog = async (force = false) => {
387
+ if (!catalogStore.shouldRefresh(force)) return catalogStore.models();
388
+ try {
389
+ if (!(await isWired())) return catalogStore.models();
390
+ const credential = await getValidCredential();
391
+ const endpoint = resolveGatewayEndpoint(credential);
392
+ const models = await catalogStore.refresh({
393
+ credential,
394
+ endpoint,
395
+ fetchImpl: relaxTlsForVpc(endpoint),
396
+ });
397
+ catalogAuthNoticed = false;
398
+ ctx.logger?.info?.(`dsh-qwenwork-connect: 模型目录已刷新(${models.length} 个)`);
399
+ return models;
400
+ } catch (error) {
401
+ const code = /** @type {any} */ (error)?.code;
402
+ const expected =
403
+ code === 'CREDENTIALS_MISSING'
404
+ || code === 'TOKEN_EXPIRED_NO_REFRESH'
405
+ || code === 'REFRESH_REJECTED'
406
+ || code === 'UNSUPPORTED_PLATFORM';
407
+ if (expected) {
408
+ if (!catalogAuthNoticed) {
409
+ catalogAuthNoticed = true;
410
+ ctx.logger?.info?.('dsh-qwenwork-connect: 尚未登录,模型目录先用内置快照');
411
+ }
412
+ } else {
413
+ ctx.logger?.warn?.(
414
+ 'dsh-qwenwork-connect: 模型目录刷新失败,沿用上次快照',
415
+ error instanceof Error ? error.message : String(error),
416
+ );
417
+ }
418
+ return catalogStore.models();
419
+ }
420
+ };
421
+ void refreshCatalog();
422
+ const catalogTimer = setInterval(() => {
423
+ void refreshCatalog();
424
+ }, CATALOG_TTL_MS);
425
+ catalogTimer.unref?.();
426
+ if (typeof ctx.effect === 'function') {
427
+ ctx.effect(
428
+ () => () => clearInterval(catalogTimer),
429
+ 'dsh-qwenwork-connect: model catalog refresh timer',
430
+ );
431
+ }
432
+
341
433
  // ---- 设置卡片数据源 ------------------------------------------------
342
434
  // 无论 provider 是否注册成功,卡片都要能显示——它是阶段 B 的主要可见成果。
343
435
  ctx.inject(['webServer'], (webCtx) => {
344
- registerDeviceLoginRoute(webCtx, { logger: ctx.logger });
436
+ registerDeviceLoginRoute(webCtx, {
437
+ logger: ctx.logger,
438
+ onLogin: () => {
439
+ void refreshCatalog(true);
440
+ },
441
+ });
345
442
  registerQwenWorkStatusRoute(webCtx, {
346
443
  getAccountContext,
347
444
  tokenAvailable: isWired,
348
- models: catalogForCard,
445
+ models: () => catalogForCard(catalogStore.models()),
349
446
  // 上游实测性能(首 token 延迟 / 输出速率)——由 shim 采样累积。
350
447
  perf: perfSummary,
351
448
  provider: QWENWORK_PROVIDER,
@@ -382,7 +479,7 @@ export function apply(ctx, config) {
382
479
  // ---- provider 注册 --------------------------------------------------
383
480
  //
384
481
  // 先启动 shim,再注册 provider:`getModels()` 才能拿到真实 baseUrl。
385
- // 即便 shim 启动失败(例如 wasm.bin 缺失),也照常注册 provider —— 让模型
482
+ // 即便 shim 启动失败,也照常注册 provider —— 让模型
386
483
  // 仍出现在选择器、设置卡片信息完整,同时对话请求给出明确错误。
387
484
  void ensureChatShim({ logger: ctx.logger })
388
485
  .then((baseUrl) => {
@@ -396,6 +493,15 @@ export function apply(ctx, config) {
396
493
  /* ensureChatShim 内部已兜底 */
397
494
  });
398
495
 
496
+ // 图片链路:附件服务按请求现取(issue #1/#5 的启动时序竞态)。
497
+ // 启动时没就绪只记一条 info,不再据此永久关掉图片能力。
498
+ const imageDeps = imageDepsFrom(ctx);
499
+ if (readAttachments(ctx) === undefined) {
500
+ ctx.logger?.info?.(
501
+ 'dsh-qwenwork-connect: 附件服务尚未就绪,图片将在请求时惰性解析',
502
+ );
503
+ }
504
+
399
505
  try {
400
506
  const { adapter } = createQwenWorkAdapter(
401
507
  () => shimBaseUrl ?? SHIM_UNAVAILABLE_BASE_URL,
@@ -407,10 +513,8 @@ export function apply(ctx, config) {
407
513
  await ensureChatShim({ logger: ctx.logger }).catch(() => null);
408
514
  return shimSharedSecret;
409
515
  },
410
- // 图片链路:从 ctx 取 DSH 的附件服务(与官方 provider 同一做法)。
411
- // 服务缺失时 **不** 传 resolveAttachments —— 此时模型描述符也不会声明
412
- // image(见 resolveImageSupport),保证「声明」与「能力」始终一致。
413
- imageDepsFrom(ctx),
516
+ imageDeps,
517
+ () => catalogStore.models(),
414
518
  );
415
519
  let releaseAdapter;
416
520
  let releaseDirectory;
@@ -33,7 +33,7 @@ function json(res, status, body) {
33
33
 
34
34
  /**
35
35
  * @param {any} ctx 已注入 webServer 的上下文
36
- * @param {{ logger?: any, credentialPath?: string }} [deps]
36
+ * @param {{ logger?: any, credentialPath?: string, onLogin?: () => void }} [deps]
37
37
  */
38
38
  export function registerDeviceLoginRoute(ctx, deps = {}) {
39
39
  const credentialPath = deps.credentialPath ?? DEFAULT_CREDENTIAL_PATH;
@@ -81,6 +81,11 @@ export function registerDeviceLoginRoute(ctx, deps = {}) {
81
81
  email: written.credential.user.email,
82
82
  };
83
83
  deps.logger?.info?.('dsh-qwenwork-connect: device login completed');
84
+ try {
85
+ deps.onLogin?.();
86
+ } catch {
87
+ // 登录后的目录刷新失败不应影响登录结果
88
+ }
84
89
  })
85
90
  .catch((error) => {
86
91
  state.phase = 'failed';
package/lib/models.js CHANGED
@@ -41,8 +41,7 @@ export const MAX_OUTPUT_TOKENS = 32000;
41
41
  *
42
42
  * 每条都直接取自 App 日志的 `rawModels`,未臆造任何字段:
43
43
  * `priceFactor` → `billingRate`,`isVl` → `supportsImages`,
44
- * `defaultContextWindow` → `contextWindow`,
45
- * `availableContextWindows` → 原样保留(三档:200K / 400K / 1M)。
44
+ * `defaultContextWindow` → `contextWindow`。
46
45
  *
47
46
  * @type {Array<{
48
47
  * id: string,
@@ -51,7 +50,6 @@ export const MAX_OUTPUT_TOKENS = 32000;
51
50
  * billingRate: number,
52
51
  * supportsImages: boolean,
53
52
  * contextWindow: number,
54
- * availableContextWindows: number[],
55
53
  * maxTokens: number,
56
54
  * isDefault?: boolean,
57
55
  * isRecommended?: boolean,
@@ -81,7 +79,6 @@ export const FALLBACK_QWENWORK_MODELS = [
81
79
  billingRate: 1,
82
80
  supportsImages: true,
83
81
  contextWindow: MAX_INPUT_TOKENS,
84
- availableContextWindows: [MAX_INPUT_TOKENS],
85
82
  maxTokens: MAX_OUTPUT_TOKENS,
86
83
  isDefault: true,
87
84
  },
@@ -96,7 +93,6 @@ export const FALLBACK_QWENWORK_MODELS = [
96
93
  billingRate: 0.1,
97
94
  supportsImages: true,
98
95
  contextWindow: MAX_INPUT_TOKENS,
99
- availableContextWindows: [MAX_INPUT_TOKENS],
100
96
  maxTokens: MAX_OUTPUT_TOKENS,
101
97
  isRecommended: true,
102
98
  },
@@ -106,7 +102,6 @@ export const FALLBACK_QWENWORK_MODELS = [
106
102
  billingRate: 0.4,
107
103
  supportsImages: true,
108
104
  contextWindow: MAX_INPUT_TOKENS,
109
- availableContextWindows: [MAX_INPUT_TOKENS],
110
105
  maxTokens: MAX_OUTPUT_TOKENS,
111
106
  isNew: true,
112
107
  },
@@ -116,7 +111,6 @@ export const FALLBACK_QWENWORK_MODELS = [
116
111
  billingRate: 1.1,
117
112
  supportsImages: true,
118
113
  contextWindow: MAX_INPUT_TOKENS,
119
- availableContextWindows: [MAX_INPUT_TOKENS],
120
114
  maxTokens: MAX_OUTPUT_TOKENS,
121
115
  isNew: true,
122
116
  },
@@ -189,14 +183,18 @@ export function displayName(info) {
189
183
  function describeModel(info) {
190
184
  const rate = formatRate(info.billingRate);
191
185
  const ctx = info.contextWindow >= 1000000 ? '1M' : `${Math.round(info.contextWindow / 1000)}K`;
192
- return [`仅文本`, ctx, rate === '' ? undefined : rate === '免费' ? '免费' : rate]
186
+ return [
187
+ info.supportsImages === true ? '视觉' : '仅文本',
188
+ ctx,
189
+ rate === '' ? undefined : rate === '免费' ? '免费' : rate,
190
+ ]
193
191
  .filter(Boolean)
194
192
  .join(' · ');
195
193
  }
196
194
 
197
195
  /** 供卡片展示的精简模型行。 */
198
- export function catalogForCard() {
199
- return FALLBACK_QWENWORK_MODELS.map((model) => ({
196
+ export function catalogForCard(models = FALLBACK_QWENWORK_MODELS) {
197
+ return models.map((model) => ({
200
198
  id: model.id,
201
199
  // 卡片显示短名(倍率已单独成列),选择器则用带倍率的长名。
202
200
  name: model.shortName ?? model.id,
package/lib/rest.js CHANGED
@@ -9,8 +9,8 @@
9
9
  * GET /api/v1/adapter/auth/identities 身份
10
10
  * GET /algo/api/v1/ping 连通性
11
11
  *
12
- * 注意:/api/v2/model/list 与 /api/v2/service/pro/sse/* 需要 WASM 签名,403,
13
- * 不属于本模块职责(阶段 A 的 wasm 逆向负责)。
12
+ * 注意:/api/v2/model/list 与 /api/v2/service/pro/sse/* 需要 COSY 签名,403,
13
+ * 不属于本模块职责(签名由 signer-session.js 负责)。
14
14
  */
15
15
 
16
16
  import { QwenAuthError, ErrorCode } from './errors.js';