dsh-qwenwork-connect 0.2.2 → 0.3.1

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,10 +27,14 @@ 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';
37
+ import { registerLogoutRoute } from './logout-route.js';
34
38
  import { perfSummary } from './perf.js';
35
39
  import { installStallGuard } from './stall-guard.js';
36
40
 
@@ -78,7 +82,7 @@ const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
78
82
  *
79
83
  * `baseUrl` 现在指向**本插件的环回 shim**(`./chat-shim.js`)。shim 负责:
80
84
  * 1. 把 pi-ai 的 OpenAI 协议请求转成 QwenWork 的推理请求;
81
- * 2. 用官方 WASM 生成签名(`Authorization: Bearer COSY.<...>`)并加密 body;
85
+ * 2. 用 COSY 信封签名(`Authorization: Bearer COSY.<...>`)并编码 body;
82
86
  * 3. 把上游的双层信封 SSE 转回标准 OpenAI SSE。
83
87
  *
84
88
  * ⚠️ `baseUrl` 在 shim 真正监听成功前是 `null`;此时 `createProvider` 会
@@ -90,6 +94,42 @@ const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
90
94
  */
91
95
  const SHIM_UNAVAILABLE_BASE_URL = 'http://127.0.0.1:1/qwenwork-shim-unavailable';
92
96
 
97
+ /**
98
+ * 单次请求的图片预算(聚合 base64 字节数 / 张数)。
99
+ *
100
+ * 取值依据(dsh-qwenwork-connector issue #4 的实测):
101
+ * · 6.3 MB 原图(base64 约 8.4 MB)→ 正常返回;
102
+ * · 15.7 MB 原图(50 张)→ 网关 NGHTTP2_ENHANCE_YOUR_CALM 掐断;
103
+ * · 实际长跑在上下文约 12.8 MB 图片时开始每轮必死。
104
+ *
105
+ * 这里取 6 MB / 32 张,给文本 body 和协议开销留余量。超过时 pi-ai 抛
106
+ * `IMAGE_OFFLOAD_REQUIRED`,宿主的 dsh-compaction-image-offload 会把最旧的
107
+ * 图片标记为 offloaded 后重试——不会再出现「整轮 UNKNOWN」。
108
+ */
109
+ const MAX_REQUEST_IMAGE_BYTES = 6 * 1024 * 1024;
110
+ const MAX_REQUEST_IMAGES = 32;
111
+
112
+ /**
113
+ * 取宿主附件服务(每次调用都现取)。
114
+ *
115
+ * ⚠️ 不能在插件启动时取一次就缓存(issue #1/#5 的根因):第三方 bundle 的
116
+ * 加载早于宿主 provision `attachments`,启动那一枪经常打空;一旦把
117
+ * `undefined` 固定进闭包,整个进程周期里图片都读不出来,只能重启赌时序。
118
+ *
119
+ * @param {any} ctx DSH 插件上下文
120
+ * @returns {any | undefined} 附件服务;未就绪或接口不合时返回 undefined
121
+ */
122
+ function readAttachments(ctx) {
123
+ try {
124
+ if (typeof ctx?.get !== 'function') return undefined;
125
+ const attachments = ctx.get('attachments');
126
+ if (attachments === null || attachments === undefined) return undefined;
127
+ return typeof attachments.readImageRequest === 'function' ? attachments : undefined;
128
+ } catch {
129
+ return undefined;
130
+ }
131
+ }
132
+
93
133
  /**
94
134
  * 从 DSH 上下文取图片链路所需的服务。
95
135
  *
@@ -97,34 +137,27 @@ const SHIM_UNAVAILABLE_BASE_URL = 'http://127.0.0.1:1/qwenwork-shim-unavailable'
97
137
  * - `ctx.get('attachments')` → 持久化附件服务
98
138
  * - `resolveImageAttachmentAccess(...)` → 把附件引用映射成可读文本
99
139
  *
100
- * 任何一步取不到都**返回空对象**(而不是半套配置)——
101
- * 这样 `createQwenWorkAdapter` 不会注册 `resolveAttachments`,
102
- * 模型描述符也就不会声明 image,避免「声明支持却一用就抛
103
- * `pi-ai image input requires the durable attachment service`」。
140
+ * `resolveAttachments` 是**惰性解析器**:pi-ai 在真正发图时才会调用它,
141
+ * 这时附件服务通常已经就绪。服务始终不存在时,pi-ai 会抛
142
+ * `pi-ai image input requires the durable attachment service`——只影响
143
+ * 带图请求,纯文本对话不受牵连。
104
144
  *
105
145
  * @param {any} ctx DSH 插件上下文
106
- * @returns {{ resolveAttachments?: () => any, resolveImageAccess?: Function }}
146
+ * @returns {{ resolveAttachments: () => any, resolveImageAccess: Function }}
107
147
  */
108
148
  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
- }
149
+ return {
150
+ resolveAttachments: () => readAttachments(ctx),
151
+ resolveImageAccess: (svc, ref) => {
152
+ // ctx.get('fs') 可能不存在(取决于宿主配置);缺失时只给附件 id,
153
+ // 不影响图片数据本身的读取(readImageRequest 走 attachments)。
154
+ const mapHostPath =
155
+ typeof ctx?.get === 'function'
156
+ ? (hostPath) => ctx.get('fs')?.processPathFromHostPath?.(hostPath)
157
+ : undefined;
158
+ return resolveImageAttachmentAccess(svc, mapHostPath, ref);
159
+ },
160
+ };
128
161
  }
129
162
 
130
163
  /**
@@ -135,18 +168,24 @@ function imageDepsFrom(ctx) {
135
168
  * @param {() => (string | null) | Promise<string | null>} getSharedSecret
136
169
  * 返回 shim 的共享密钥;未就绪时可为 `null`。允许返回 Promise——
137
170
  * 调用方会在未就绪时等待 shim 启动,而不是拿 null 去发无鉴权请求。
138
- * @param {{ resolveAttachments?: () => any, resolveImageAccess?: (attachments: any, ref: any) => string }} [image]
171
+ * @param {{ resolveAttachments: () => any, resolveImageAccess: (attachments: any, ref: any) => string }} [image]
139
172
  * 图片链路接入点。由 apply() 从 ctx 取 DSH 的附件服务后传入
140
173
  * (与官方 provider 的做法一致:`ctx.get('attachments')`)。
141
- * 不传时模型只能收文本——但那时模型描述符也不应声明 image。
174
+ * `resolveAttachments` 是惰性解析器,pi-ai 在发图时才调用。
175
+ * @param {() => Array<any>} [getCatalog] 当前模型目录(动态缓存 + 内置种子)
142
176
  */
143
- function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
144
- // 图片能力**由附件服务是否可用决定**:只有 pi-ai 拿到了
145
- // `resolveAttachments`,声明 image 才是真的能用;否则声明了也会在
146
- // 发图时抛错。两者必须同步,这是本项目反复出现的「声明与实现一致」原则。
177
+ function createQwenWorkAdapter(
178
+ getBaseUrl,
179
+ getSharedSecret,
180
+ image = {},
181
+ getCatalog = () => FALLBACK_QWENWORK_MODELS,
182
+ ) {
183
+ // 图片能力由**上游模型**决定(catalog 里 is_vl: true);附件服务是否就绪
184
+ // 交给 pi-ai 在发图时调用 `resolveAttachments()` 现取。启动时序不再影响
185
+ // 图片声明——这是 connector issue #1/#5 的教训。
147
186
  const imagesAvailable = typeof image.resolveAttachments === 'function';
148
187
  const buildModels = () =>
149
- FALLBACK_QWENWORK_MODELS.map((info) =>
188
+ getCatalog().map((info) =>
150
189
  toPiModel(info, getBaseUrl(), { supportsImages: imagesAvailable }),
151
190
  );
152
191
 
@@ -188,8 +227,9 @@ function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
188
227
  configuredMaxTokens: new Map(),
189
228
  modelErrors: new Map(),
190
229
  // 图片链路限额:模型声明支持 image 后,pi-ai 会按这些上限决定
191
- // 「原样内联」还是「降级为文本占位符」。取值与官方 provider 一致。
192
- maxRequestImageBytes: 20_971_520,
230
+ // 「原样内联」还是抛出 IMAGE_OFFLOAD_REQUIRED 交给宿主卸载最旧的图。
231
+ maxRequestImageBytes: MAX_REQUEST_IMAGE_BYTES,
232
+ maxRequestImages: MAX_REQUEST_IMAGES,
193
233
  requestImagePixelBudget: 4_194_304,
194
234
  requestImageMaxBytes: 1_048_576,
195
235
  piProvider: provider,
@@ -233,11 +273,11 @@ function createQwenWorkAdapter(getBaseUrl, getSharedSecret, image = {}) {
233
273
  * resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(...)
234
274
  *
235
275
  * 只有**同时**声明模型支持 image,这条链路才会被走到;
236
- * 两者缺一都会出问题(声明 image 但无服务 → 抛错;有服务但不声明 → 走不到)。
276
+ * 声明由上游能力决定,服务在发图时现取——启动时附件服务没就绪不再
277
+ * 导致「整个进程周期都用不了图」。
237
278
  */
238
- ...(typeof image.resolveAttachments === 'function'
239
- ? { resolveAttachments: () => image.resolveAttachments() }
240
- : {}),
279
+ resolveAttachments: () =>
280
+ typeof image.resolveAttachments === 'function' ? image.resolveAttachments() : undefined,
241
281
  ...(typeof image.resolveImageAccess === 'function'
242
282
  ? {
243
283
  resolveImageAccess: (attachments, ref) => image.resolveImageAccess(attachments, ref),
@@ -338,14 +378,77 @@ export function chatShimSharedSecret() {
338
378
  * @param {any} config
339
379
  */
340
380
  export function apply(ctx, config) {
381
+ // ---- 动态模型目录 --------------------------------------------------
382
+ // 目录来自上游 `/algo/api/v2/model/list`(COSY 签名),5 分钟 TTL;
383
+ // 刷新失败保留上一次成功的快照,首次成功前用 models.js 的内置目录。
384
+ const catalogStore = createCatalogStore();
385
+ /** 未登录导致的目录拉取失败只提示一次,避免每 5 分钟刷一条日志。 */
386
+ let catalogAuthNoticed = false;
387
+ const refreshCatalog = async (force = false) => {
388
+ if (!catalogStore.shouldRefresh(force)) return catalogStore.models();
389
+ try {
390
+ if (!(await isWired())) return catalogStore.models();
391
+ const credential = await getValidCredential();
392
+ const endpoint = resolveGatewayEndpoint(credential);
393
+ const models = await catalogStore.refresh({
394
+ credential,
395
+ endpoint,
396
+ fetchImpl: relaxTlsForVpc(endpoint),
397
+ });
398
+ catalogAuthNoticed = false;
399
+ ctx.logger?.info?.(`dsh-qwenwork-connect: 模型目录已刷新(${models.length} 个)`);
400
+ return models;
401
+ } catch (error) {
402
+ const code = /** @type {any} */ (error)?.code;
403
+ const expected =
404
+ code === 'CREDENTIALS_MISSING'
405
+ || code === 'TOKEN_EXPIRED_NO_REFRESH'
406
+ || code === 'REFRESH_REJECTED'
407
+ || code === 'UNSUPPORTED_PLATFORM';
408
+ if (expected) {
409
+ if (!catalogAuthNoticed) {
410
+ catalogAuthNoticed = true;
411
+ ctx.logger?.info?.('dsh-qwenwork-connect: 尚未登录,模型目录先用内置快照');
412
+ }
413
+ } else {
414
+ ctx.logger?.warn?.(
415
+ 'dsh-qwenwork-connect: 模型目录刷新失败,沿用上次快照',
416
+ error instanceof Error ? error.message : String(error),
417
+ );
418
+ }
419
+ return catalogStore.models();
420
+ }
421
+ };
422
+ void refreshCatalog();
423
+ const catalogTimer = setInterval(() => {
424
+ void refreshCatalog();
425
+ }, CATALOG_TTL_MS);
426
+ catalogTimer.unref?.();
427
+ if (typeof ctx.effect === 'function') {
428
+ ctx.effect(
429
+ () => () => clearInterval(catalogTimer),
430
+ 'dsh-qwenwork-connect: model catalog refresh timer',
431
+ );
432
+ }
433
+
341
434
  // ---- 设置卡片数据源 ------------------------------------------------
342
435
  // 无论 provider 是否注册成功,卡片都要能显示——它是阶段 B 的主要可见成果。
343
436
  ctx.inject(['webServer'], (webCtx) => {
344
- registerDeviceLoginRoute(webCtx, { logger: ctx.logger });
437
+ const loginRoutes = registerDeviceLoginRoute(webCtx, {
438
+ logger: ctx.logger,
439
+ onLogin: () => {
440
+ void refreshCatalog(true);
441
+ },
442
+ });
443
+ registerLogoutRoute(webCtx, {
444
+ logger: ctx.logger,
445
+ // 清掉登录页缓存,避免退出后 /login/status 仍回上一次的账号摘要。
446
+ onLogout: () => loginRoutes?.reset?.(),
447
+ });
345
448
  registerQwenWorkStatusRoute(webCtx, {
346
449
  getAccountContext,
347
450
  tokenAvailable: isWired,
348
- models: catalogForCard,
451
+ models: () => catalogForCard(catalogStore.models()),
349
452
  // 上游实测性能(首 token 延迟 / 输出速率)——由 shim 采样累积。
350
453
  perf: perfSummary,
351
454
  provider: QWENWORK_PROVIDER,
@@ -382,7 +485,7 @@ export function apply(ctx, config) {
382
485
  // ---- provider 注册 --------------------------------------------------
383
486
  //
384
487
  // 先启动 shim,再注册 provider:`getModels()` 才能拿到真实 baseUrl。
385
- // 即便 shim 启动失败(例如 wasm.bin 缺失),也照常注册 provider —— 让模型
488
+ // 即便 shim 启动失败,也照常注册 provider —— 让模型
386
489
  // 仍出现在选择器、设置卡片信息完整,同时对话请求给出明确错误。
387
490
  void ensureChatShim({ logger: ctx.logger })
388
491
  .then((baseUrl) => {
@@ -396,6 +499,15 @@ export function apply(ctx, config) {
396
499
  /* ensureChatShim 内部已兜底 */
397
500
  });
398
501
 
502
+ // 图片链路:附件服务按请求现取(issue #1/#5 的启动时序竞态)。
503
+ // 启动时没就绪只记一条 info,不再据此永久关掉图片能力。
504
+ const imageDeps = imageDepsFrom(ctx);
505
+ if (readAttachments(ctx) === undefined) {
506
+ ctx.logger?.info?.(
507
+ 'dsh-qwenwork-connect: 附件服务尚未就绪,图片将在请求时惰性解析',
508
+ );
509
+ }
510
+
399
511
  try {
400
512
  const { adapter } = createQwenWorkAdapter(
401
513
  () => shimBaseUrl ?? SHIM_UNAVAILABLE_BASE_URL,
@@ -407,10 +519,8 @@ export function apply(ctx, config) {
407
519
  await ensureChatShim({ logger: ctx.logger }).catch(() => null);
408
520
  return shimSharedSecret;
409
521
  },
410
- // 图片链路:从 ctx 取 DSH 的附件服务(与官方 provider 同一做法)。
411
- // 服务缺失时 **不** 传 resolveAttachments —— 此时模型描述符也不会声明
412
- // image(见 resolveImageSupport),保证「声明」与「能力」始终一致。
413
- imageDepsFrom(ctx),
522
+ imageDeps,
523
+ () => catalogStore.models(),
414
524
  );
415
525
  let releaseAdapter;
416
526
  let releaseDirectory;
@@ -27,6 +27,23 @@ export const DEVICE_BASE = 'https://gateway.qwenwork.cn';
27
27
  export const DEFAULT_CREDENTIAL_PATH = path.join(os.homedir(), '.dsh', 'qwenwork-desktop.json');
28
28
  export const DEFAULT_MACHINE_ID_PATH = path.join(os.homedir(), '.dsh', 'qwenwork-machine-id');
29
29
 
30
+ /**
31
+ * 凭据文件路径的唯一解析口:显式参数 > `QWENWORK_CREDENTIAL_FILE` > 默认路径。
32
+ *
33
+ * `credentials.js` 的读取侧早就支持这个环境变量;写入侧(登录 / CLI)与
34
+ * 删除侧(退出登录)必须走同一套优先级,否则会出现「登录写 A、读取读 B」
35
+ * 或「退出删 A、实际用的是 B」这种自相矛盾的状态。
36
+ *
37
+ * @param {string | undefined} explicit
38
+ * @returns {string}
39
+ */
40
+ export function resolveCredentialPath(explicit) {
41
+ if (typeof explicit === 'string' && explicit !== '') return explicit;
42
+ const fromEnv = process.env.QWENWORK_CREDENTIAL_FILE;
43
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return fromEnv.trim();
44
+ return DEFAULT_CREDENTIAL_PATH;
45
+ }
46
+
30
47
  export function createPkce() {
31
48
  const verifier = crypto.randomBytes(48).toString('base64url');
32
49
  const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
@@ -134,7 +151,8 @@ function sleep(ms) {
134
151
  * 字段名沿用上游 `normalizeCredentials` 的契约,换实现时不用改契约。
135
152
  */
136
153
  export function writeCredential(payload, options = {}) {
137
- const { machineId, credentialPath = DEFAULT_CREDENTIAL_PATH } = options;
154
+ const { machineId } = options;
155
+ const credentialPath = resolveCredentialPath(options.credentialPath);
138
156
  const claims = decodeJwt(payload.token);
139
157
  const user = {
140
158
  id: payload.user_id ?? claims.user_id ?? claims.sub ?? null,
@@ -162,7 +180,7 @@ export async function startDeviceLogin(options = {}) {
162
180
  const {
163
181
  clientId = DEVICE_CLIENT_ID,
164
182
  base = DEVICE_BASE,
165
- credentialPath = DEFAULT_CREDENTIAL_PATH,
183
+ credentialPath,
166
184
  machineIdPath = DEFAULT_MACHINE_ID_PATH,
167
185
  intervalMs = 2000,
168
186
  timeoutMs = 5 * 60 * 1000,
@@ -13,9 +13,9 @@ import {
13
13
  buildAuthUrl,
14
14
  createPkce,
15
15
  pollDeviceToken,
16
+ resolveCredentialPath,
16
17
  resolveMachineId,
17
18
  writeCredential,
18
- DEFAULT_CREDENTIAL_PATH,
19
19
  } from './login-device-flow.js';
20
20
 
21
21
  export const LOGIN_START_PATH = '/plugins/dsh-qwenwork-connect/login/start';
@@ -33,11 +33,16 @@ 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
- const credentialPath = deps.credentialPath ?? DEFAULT_CREDENTIAL_PATH;
39
+ const credentialPath = resolveCredentialPath(deps.credentialPath);
40
40
  const state = { phase: 'idle', url: null, error: null, account: null, startedAt: null };
41
+ /**
42
+ * 登录轮询的代际号:退出登录时 +1,让尚在途中的 device flow 结果作废。
43
+ * 只改 `state` 不够——旧轮询拿到 token 后仍会写盘,把刚退出的账号又登回去。
44
+ */
45
+ let epoch = 0;
41
46
 
42
47
  const handle = (req, res) => {
43
48
  if (!loopbackRequest(req)) {
@@ -70,8 +75,13 @@ export function registerDeviceLoginRoute(ctx, deps = {}) {
70
75
  state.account = null;
71
76
  state.startedAt = Date.now();
72
77
 
78
+ const loginEpoch = epoch;
73
79
  void pollDeviceToken({ nonce, verifier })
74
80
  .then((payload) => {
81
+ if (loginEpoch !== epoch) {
82
+ // 等待期间用户已退出登录:丢弃这次授权结果,不写回凭据。
83
+ return;
84
+ }
75
85
  const written = writeCredential(payload, { machineId, credentialPath });
76
86
  state.phase = 'ready';
77
87
  state.account = {
@@ -81,8 +91,14 @@ export function registerDeviceLoginRoute(ctx, deps = {}) {
81
91
  email: written.credential.user.email,
82
92
  };
83
93
  deps.logger?.info?.('dsh-qwenwork-connect: device login completed');
94
+ try {
95
+ deps.onLogin?.();
96
+ } catch {
97
+ // 登录后的目录刷新失败不应影响登录结果
98
+ }
84
99
  })
85
100
  .catch((error) => {
101
+ if (loginEpoch !== epoch) return;
86
102
  state.phase = 'failed';
87
103
  state.error = String(error?.message ?? error).slice(0, 300);
88
104
  deps.logger?.warn?.('dsh-qwenwork-connect: device login failed', state.error);
@@ -111,13 +127,24 @@ export function registerDeviceLoginRoute(ctx, deps = {}) {
111
127
  };
112
128
  };
113
129
 
130
+ /** 退出登录时清空登录页状态,并让在途轮询作废。 */
131
+ const reset = () => {
132
+ epoch += 1;
133
+ state.phase = 'idle';
134
+ state.url = null;
135
+ state.error = null;
136
+ state.account = null;
137
+ state.startedAt = null;
138
+ };
139
+
114
140
  if (typeof ctx.effect === 'function') {
115
141
  ctx.effect(() => mount(), 'dsh-qwenwork-connect: device login routes');
116
- return;
142
+ return { reset };
117
143
  }
118
144
  try {
119
145
  mount();
120
146
  } catch (error) {
121
147
  void error;
122
148
  }
149
+ return { reset };
123
150
  }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 退出登录:设置卡片上点「退出登录」走这里。
3
+ *
4
+ * 只做一件事——删掉本机凭据文件,让下一次请求重新回到「未登录」。
5
+ * 不吊销上游 token(千问办公没有公开的吊销接口),但 token 离开本机后
6
+ * 已经无法再被本插件使用;设备标识 `~/.dsh/qwenwork-machine-id` 刻意保留,
7
+ * 这样重新登录不会换设备。
8
+ *
9
+ * 安全边界与登录 / 状态路由一致:只接受环回请求;错误文本不回显凭据内容。
10
+ *
11
+ * @module dsh-qwenwork-connect/logout-route
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import { loopbackRequest } from './loopback.js';
16
+ import { resolveCredentialPath } from './login-device-flow.js';
17
+
18
+ export const LOGOUT_PATH = '/plugins/dsh-qwenwork-connect/logout';
19
+
20
+ function json(res, status, body) {
21
+ const payload = JSON.stringify(body);
22
+ res.writeHead(status, {
23
+ 'Content-Type': 'application/json; charset=utf-8',
24
+ 'Content-Length': Buffer.byteLength(payload),
25
+ 'Cache-Control': 'no-store',
26
+ });
27
+ res.end(payload);
28
+ }
29
+
30
+ /**
31
+ * @param {any} ctx 已注入 webServer 的上下文
32
+ * @param {{ logger?: any, credentialPath?: string, onLogout?: () => void }} [deps]
33
+ */
34
+ export function registerLogoutRoute(ctx, deps = {}) {
35
+ const credentialPath = resolveCredentialPath(deps.credentialPath);
36
+
37
+ const handle = (req, res) => {
38
+ if (!loopbackRequest(req)) {
39
+ json(res, 403, { error: 'loopback only' });
40
+ return;
41
+ }
42
+ if (req.method !== 'POST') {
43
+ json(res, 405, { error: 'POST only' });
44
+ return;
45
+ }
46
+
47
+ try {
48
+ let removed = false;
49
+ try {
50
+ fs.unlinkSync(credentialPath);
51
+ removed = true;
52
+ } catch (error) {
53
+ // 已经退出过 / 从来没登录过:幂等成功,不把「文件不存在」当失败。
54
+ if (/** @type {any} */ (error)?.code !== 'ENOENT') throw error;
55
+ }
56
+
57
+ try {
58
+ deps.onLogout?.();
59
+ } catch {
60
+ // 内存态清理失败不应把「凭据已删除」判成退出失败。
61
+ }
62
+
63
+ deps.logger?.info?.(`dsh-qwenwork-connect: 已退出登录${removed ? '' : '(凭据文件原本不存在)'}`);
64
+ json(res, 200, { ok: true, removed });
65
+ } catch (error) {
66
+ const message = String(/** @type {any} */ (error)?.message ?? error).slice(0, 300);
67
+ deps.logger?.warn?.('dsh-qwenwork-connect: 退出登录失败', message);
68
+ json(res, 500, { error: message });
69
+ }
70
+ };
71
+
72
+ const mount = () => {
73
+ const dispose = ctx.webServer.register({
74
+ kind: 'exact',
75
+ path: LOGOUT_PATH,
76
+ handler: handle,
77
+ });
78
+ return dispose;
79
+ };
80
+
81
+ if (typeof ctx.effect === 'function') {
82
+ ctx.effect(() => mount(), 'dsh-qwenwork-connect: device logout route');
83
+ return;
84
+ }
85
+ try {
86
+ mount();
87
+ } catch (error) {
88
+ void error;
89
+ }
90
+ }
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';