dsh-opendesign-corouter 0.1.16 → 0.1.17

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/config.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import Schema from '@deepseek-ai/schemastery';
2
2
  import { type ApiProtocol } from './protocol-options.js';
3
3
  import { type ModelSettingsMap } from './model-settings.js';
4
+ import { type ModelCatalogSnapshot } from './model-catalog-snapshot.js';
4
5
  export { DEFAULT_MAX_REQUEST_IMAGE_BYTES } from './image-budget.js';
5
6
  export declare const SETTINGS_NS = "llm-opendesign-corouter";
6
7
  export declare const PLAN_PROVIDER = "opendesign-corouter-plan";
@@ -11,6 +12,7 @@ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
11
12
  baseURL: Schema<string, string, "volatile-defined">;
12
13
  apiProtocol: Schema<"chat-completions" | "responses" | "messages", "chat-completions" | "responses" | "messages", "volatile-defined">;
13
14
  modelSettings: Schema<NoInfer<import("@deepseek-ai/cosmokit").Dict<unknown, string>>, NoInfer<ModelSettingsMap>, "volatile-defined">;
15
+ modelCatalog: Schema<unknown, NoInfer<ModelCatalogSnapshot | undefined>, "volatile">;
14
16
  useDesktopCredential: Schema<boolean, boolean, "volatile-defined">;
15
17
  emptyTurnGuard: Schema<boolean, boolean, "volatile-defined">;
16
18
  turnCompletionReview: Schema<boolean, boolean, "volatile-defined">;
@@ -25,6 +27,7 @@ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
25
27
  baseURL: Schema<string, string, "volatile-defined">;
26
28
  apiProtocol: Schema<"chat-completions" | "responses" | "messages", "chat-completions" | "responses" | "messages", "volatile-defined">;
27
29
  modelSettings: Schema<NoInfer<import("@deepseek-ai/cosmokit").Dict<unknown, string>>, NoInfer<ModelSettingsMap>, "volatile-defined">;
30
+ modelCatalog: Schema<unknown, NoInfer<ModelCatalogSnapshot | undefined>, "volatile">;
28
31
  useDesktopCredential: Schema<boolean, boolean, "volatile-defined">;
29
32
  emptyTurnGuard: Schema<boolean, boolean, "volatile-defined">;
30
33
  turnCompletionReview: Schema<boolean, boolean, "volatile-defined">;
@@ -45,6 +48,7 @@ export interface RuntimeConfig {
45
48
  streamIdleTimeoutMs: number;
46
49
  apiProtocol?: ApiProtocol;
47
50
  modelSettings?: ModelSettingsMap;
51
+ modelCatalog?: ModelCatalogSnapshot;
48
52
  quotaRefreshSeconds?: number;
49
53
  maxRequestImageBytes?: number;
50
54
  turnCompletionReview?: boolean;
@@ -3,7 +3,7 @@ export interface DeviceTokens {
3
3
  runtimeKey: string;
4
4
  }
5
5
  export declare const DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
6
- export declare const DEVICE_AUTH_PLUGIN_VERSION = "0.1.16";
6
+ export declare const DEVICE_AUTH_PLUGIN_VERSION = "0.1.17";
7
7
  export declare const DEVICE_REQUEST_TIMEOUT_MS = 20000;
8
8
  /** One bounded launch step of the temporary activation window. */
9
9
  export declare const DEVICE_OPEN_TIMEOUT_MS = 30000;
package/lib/index.d.ts CHANGED
@@ -50,6 +50,8 @@ export declare class OpenDesignCoRouterService extends TypertRemoteService {
50
50
  private _modelsEpoch;
51
51
  private _modelsPending;
52
52
  private _modelsController;
53
+ private _modelsWriteSerial;
54
+ private _modelsWrite;
53
55
  private _prices;
54
56
  private _pricesPending;
55
57
  modelCatalog(): readonly CatalogModel[];
@@ -57,6 +59,16 @@ export declare class OpenDesignCoRouterService extends TypertRemoteService {
57
59
  private _credentials;
58
60
  private _key;
59
61
  resolveApiKey(ref: string, baseURL?: string): Promise<string | undefined>;
62
+ /** Restore the persisted gateway catalog when it belongs to the active gateway. */
63
+ private _restoreModels;
64
+ /**
65
+ * Persist the snapshot through the Host form service.
66
+ * `unsupported` means no settings service is composed (nothing to report);
67
+ * `unavailable` means the service exists but exposes no writable form for this plugin.
68
+ */
69
+ private _persistModels;
70
+ /** Serialize snapshot writes so the newest successful refresh is the last one persisted. */
71
+ private _queueModelsWrite;
60
72
  private _invalidateModels;
61
73
  private _state;
62
74
  private _conflict;
package/lib/index.js CHANGED
@@ -343,6 +343,71 @@ function serializableTransform(callback) {
343
343
  });
344
344
  }
345
345
 
346
+ // src/model-catalog-snapshot.ts
347
+ function parseModelCatalogSnapshot(value) {
348
+ const MODEL_ID4 = /^[A-Za-z0-9._:/-]{1,128}$/u;
349
+ const GROUPS = ["plan", "paid"];
350
+ const KEYS = ["id", "name", "group", "contextWindow", "maxOutputTokens", "inputModalities", "reasoningEfforts"];
351
+ const RESERVED = ["__proto__", "constructor", "prototype"];
352
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
353
+ const snapshot = value;
354
+ if (typeof snapshot.baseURL !== "string" || snapshot.baseURL.length === 0 || snapshot.baseURL.length > 2048) return void 0;
355
+ let base;
356
+ try {
357
+ base = new URL(snapshot.baseURL);
358
+ } catch {
359
+ return void 0;
360
+ }
361
+ if (!["https:", "http:"].includes(base.protocol) || base.username || base.password || base.search || base.hash) return void 0;
362
+ if (base.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)) return void 0;
363
+ const baseURL = base.href.replace(/\/+$/u, "");
364
+ if (baseURL.length === 0 || baseURL.length > 2048) return void 0;
365
+ if (typeof snapshot.updatedAt !== "string" || snapshot.updatedAt.length === 0 || snapshot.updatedAt.length > 64 || !Number.isFinite(Date.parse(snapshot.updatedAt))) return void 0;
366
+ if (!Array.isArray(snapshot.models) || snapshot.models.length === 0 || snapshot.models.length > 512) return void 0;
367
+ const seen = /* @__PURE__ */ new Set();
368
+ const models = [];
369
+ for (const entry of snapshot.models) {
370
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return void 0;
371
+ const item = entry;
372
+ for (const key of Object.keys(item)) if (!KEYS.includes(key)) return void 0;
373
+ const id = item.id, name2 = item.name, group2 = item.group;
374
+ if (typeof id !== "string" || id.length === 0 || id.length > 128 || !MODEL_ID4.test(id) || seen.has(id) || RESERVED.includes(id)) return void 0;
375
+ if (typeof name2 !== "string" || name2.trim().length === 0 || name2.length > 128) return void 0;
376
+ if (typeof group2 !== "string" || !GROUPS.includes(group2)) return void 0;
377
+ const model = { id, name: name2, group: group2 };
378
+ if (item.contextWindow !== void 0) {
379
+ if (!Number.isSafeInteger(item.contextWindow) || item.contextWindow <= 0 || item.contextWindow > 1e8) return void 0;
380
+ model.contextWindow = item.contextWindow;
381
+ }
382
+ if (item.maxOutputTokens !== void 0) {
383
+ if (!Number.isSafeInteger(item.maxOutputTokens) || item.maxOutputTokens <= 0 || item.maxOutputTokens > 1e7) return void 0;
384
+ model.maxOutputTokens = item.maxOutputTokens;
385
+ }
386
+ if (item.inputModalities !== void 0) {
387
+ if (!Array.isArray(item.inputModalities) || item.inputModalities.length < 1 || item.inputModalities.length > 2) return void 0;
388
+ const modalities = [];
389
+ for (const modality of item.inputModalities) {
390
+ if (modality !== "text" && modality !== "image") return void 0;
391
+ modalities.push(modality);
392
+ }
393
+ if (!modalities.includes("text") || new Set(modalities).size !== modalities.length) return void 0;
394
+ model.inputModalities = modalities;
395
+ }
396
+ if (item.reasoningEfforts !== void 0) {
397
+ if (!Array.isArray(item.reasoningEfforts) || item.reasoningEfforts.length > 16) return void 0;
398
+ const efforts = [];
399
+ for (const effort of item.reasoningEfforts) {
400
+ if (typeof effort !== "string" || effort.length === 0 || effort.length > 32) return void 0;
401
+ efforts.push(effort);
402
+ }
403
+ model.reasoningEfforts = efforts;
404
+ }
405
+ seen.add(id);
406
+ models.push(model);
407
+ }
408
+ return { baseURL, updatedAt: snapshot.updatedAt, models };
409
+ }
410
+
346
411
  // src/image-budget.ts
347
412
  var MIN_REQUEST_IMAGE_BYTES = 1024 * 1024;
348
413
  var DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
@@ -358,6 +423,7 @@ var Config = Schema.object({
358
423
  baseURL: Schema.transform(Schema.string(), serializableTransform(assertBaseURL)).default(DEFAULT_BASE_URL).description("CoRouter \u7F51\u5173\u5730\u5740\uFF1B\u4E0D\u7528\u4E8E\u63A7\u5236\u53F0\u767B\u5F55\u6216\u989D\u5EA6\u67E5\u8BE2").volatile(),
359
424
  apiProtocol: Schema.union(API_PROTOCOL_IDS).default("chat-completions").description("\u7F51\u5173\u652F\u6301\u7684\u63A8\u7406\u534F\u8BAE\uFF1B\u6A21\u578B\u76EE\u5F55\u901A\u8FC7\u8BE5\u7F51\u5173\u7684\u517C\u5BB9\u63A5\u53E3\u8BFB\u53D6").volatile(),
360
425
  modelSettings: Schema.transform(Schema.dict(Schema.any()), serializableTransform(parseModelSettingsMap)).default({}).description("\u9010\u6A21\u578B\u542F\u7528\u72B6\u6001\u3001\u56FE\u7247\u8F93\u5165\u548C\u8BF7\u6C42\u53C2\u6570").volatile(),
426
+ modelCatalog: Schema.transform(Schema.any(), serializableTransform(parseModelCatalogSnapshot)).description("\u4E0A\u6B21\u6210\u529F\u8BFB\u53D6\u7684\u7F51\u5173\u6A21\u578B\u76EE\u5F55\u5FEB\u7167\uFF1B\u91CD\u542F\u540E\u7EE7\u7EED\u4F7F\u7528\uFF0C\u76F4\u5230\u518D\u6B21\u5237\u65B0").volatile(),
361
427
  useDesktopCredential: Schema.boolean().default(true).description("\u4F18\u5148\u8BFB\u53D6 OpenDesign \u684C\u9762\u7AEF\u767B\u5F55\u6001\u67E5\u8BE2\u989D\u5EA6").volatile(),
362
428
  emptyTurnGuard: Schema.boolean().default(true).description("\u4FDD\u62A4 DeepSeek V4.1 Flash \u5DE5\u5177\u5BF9\u8BDD\uFF1A\u6062\u590D\u7A7A\u56DE\u7B54\u4E0E\u5DF2\u77E5\u534F\u8BAE\u6B8B\u7559\u7ED3\u675F").volatile(),
363
429
  turnCompletionReview: Schema.boolean().default(false).description("\u56DE\u590D\u7ED3\u675F\u540E\u8FFD\u52A0\u6709\u754C\u7684\u7ED3\u6784\u5316\u6536\u5C3E\u6838\u9A8C\uFF0C\u8981\u6C42\u6A21\u578B\u8C03\u7528\u6536\u5C3E\u5DE5\u5177\u62A5\u544A\u72B6\u6001").volatile(),
@@ -383,11 +449,13 @@ function assertBaseURL(raw) {
383
449
  return normalized;
384
450
  }
385
451
  function readConfig(config) {
452
+ const modelCatalog = parseModelCatalogSnapshot(config.modelCatalog.get());
386
453
  return {
387
454
  apiKeyEnv: config.apiKeyEnv.get(),
388
455
  baseURL: assertBaseURL(config.baseURL.get()),
389
456
  apiProtocol: config.apiProtocol.get(),
390
457
  modelSettings: parseModelSettingsMap(config.modelSettings.get()),
458
+ ...modelCatalog === void 0 ? {} : { modelCatalog },
391
459
  quotaRefreshSeconds: config.quotaRefreshSeconds.get(),
392
460
  useDesktopCredential: config.useDesktopCredential.get(),
393
461
  emptyTurnGuard: config.emptyTurnGuard.get(),
@@ -3425,7 +3493,7 @@ import { randomUUID as randomUUID2 } from "node:crypto";
3425
3493
 
3426
3494
  // src/device-auth.ts
3427
3495
  var DEVICE_AUTH_ENDPOINT = "https://amr-api.open-design.ai/api/v1/cli/device-authorizations";
3428
- var DEVICE_AUTH_PLUGIN_VERSION = "0.1.16";
3496
+ var DEVICE_AUTH_PLUGIN_VERSION = "0.1.17";
3429
3497
  var DEVICE_REQUEST_TIMEOUT_MS = 2e4;
3430
3498
  var DEVICE_RESPONSE_MAX_BYTES = 65536;
3431
3499
  var DEVICE_POLL_MIN_MS = 1e3;
@@ -4623,6 +4691,10 @@ var inject = ["llm"];
4623
4691
  var API_KEY = credentialKey2(name, "api-key");
4624
4692
  var SESSION = credentialKey2(name, "console");
4625
4693
  var hash = (value) => createHash2("sha256").update(JSON.stringify(value) ?? "").digest("hex");
4694
+ var stableConfig = (config) => {
4695
+ const { modelCatalog: _snapshot, ...rest } = config;
4696
+ return rest;
4697
+ };
4626
4698
  var needLogin = () => ({ state: "need-login", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: [], balances: {}, note: "\u8BF7\u5728\u8FDE\u63A5\u4E0E\u767B\u5F55\u9875\u5B8C\u6210\u8D26\u53F7\u6388\u6743\u540E\u8BFB\u53D6\u989D\u5EA6\u3002" });
4627
4699
  var unreadQuota = () => ({ state: "partial", updatedAt: (/* @__PURE__ */ new Date()).toISOString(), windows: [], balances: {}, note: "\u989D\u5EA6\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u5237\u65B0\u989D\u5EA6\u3002" });
4628
4700
  function grantOf(value) {
@@ -4659,15 +4731,18 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4659
4731
  __publicField(this, "_modelsEpoch", 0);
4660
4732
  __publicField(this, "_modelsPending");
4661
4733
  __publicField(this, "_modelsController");
4734
+ __publicField(this, "_modelsWriteSerial", 0);
4735
+ __publicField(this, "_modelsWrite", Promise.resolve());
4662
4736
  __publicField(this, "_prices");
4663
4737
  __publicField(this, "_pricesPending");
4664
4738
  this._config = config;
4739
+ this._restoreModels();
4665
4740
  this._login = new ConsoleLogin({
4666
4741
  capture: async (expectedRevision) => {
4667
4742
  const state = await this._state();
4668
4743
  this._expect(expectedRevision);
4669
4744
  this._credentials();
4670
- return { revision: expectedRevision, sessionHash: hash(state.sessionRecord), configHash: hash(state.config) };
4745
+ return { revision: expectedRevision, sessionHash: hash(state.sessionRecord), configHash: hash(stableConfig(state.config)) };
4671
4746
  },
4672
4747
  commit: async (tokens, captured, signal) => {
4673
4748
  if (!record(captured) || typeof captured.revision !== "string" || typeof captured.sessionHash !== "string" || typeof captured.configHash !== "string") throw this._conflict();
@@ -4676,7 +4751,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4676
4751
  signal.throwIfAborted();
4677
4752
  await this._credentials().modifyRecord(SESSION, async (current) => {
4678
4753
  signal.throwIfAborted();
4679
- if (hash(current) !== captured.sessionHash || hash(this._config()) !== captured.configHash) throw this._conflict();
4754
+ if (hash(current) !== captured.sessionHash || hash(stableConfig(this._config())) !== captured.configHash) throw this._conflict();
4680
4755
  const grant = deviceGrant({ kind: "device", ...tokens });
4681
4756
  if (!grant) throw new ConsoleError("auth");
4682
4757
  return { kind: "grant", payload: { ...grant, savedAt: (/* @__PURE__ */ new Date()).toISOString() } };
@@ -4722,6 +4797,51 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4722
4797
  const [apiRecord, sessionRecord] = await Promise.all([credentials?.readRecord(API_KEY), credentials?.readRecord(SESSION)]);
4723
4798
  return (await this._key(ref, baseURL, apiRecord, sessionRecord))?.key;
4724
4799
  }
4800
+ /** Restore the persisted gateway catalog when it belongs to the active gateway. */
4801
+ _restoreModels() {
4802
+ const config = this._config();
4803
+ const snapshot = config.modelCatalog;
4804
+ if (!snapshot || snapshot.baseURL !== config.baseURL) return;
4805
+ this._models = snapshot.models;
4806
+ this._modelsUpdatedAt = snapshot.updatedAt;
4807
+ }
4808
+ /**
4809
+ * Persist the snapshot through the Host form service.
4810
+ * `unsupported` means no settings service is composed (nothing to report);
4811
+ * `unavailable` means the service exists but exposes no writable form for this plugin.
4812
+ */
4813
+ async _persistModels(value) {
4814
+ const settings = this.ctx.get("settings");
4815
+ if (!settings) return "unsupported";
4816
+ for (let attempt = 0; attempt < 2; attempt++) {
4817
+ let descriptor;
4818
+ try {
4819
+ descriptor = settings.describe().find((item) => item.ns === SETTINGS_NS);
4820
+ } catch {
4821
+ return "unavailable";
4822
+ }
4823
+ if (!descriptor) return "unavailable";
4824
+ try {
4825
+ await settings.update(SETTINGS_NS, { modelCatalog: value }, descriptor.revision);
4826
+ return "saved";
4827
+ } catch {
4828
+ }
4829
+ }
4830
+ return "failed";
4831
+ }
4832
+ /** Serialize snapshot writes so the newest successful refresh is the last one persisted. */
4833
+ _queueModelsWrite(snapshot, epoch) {
4834
+ const serial = ++this._modelsWriteSerial;
4835
+ this._modelsWrite = this._modelsWrite.then(async () => {
4836
+ const result = await this._persistModels(snapshot);
4837
+ if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
4838
+ if (result === "unavailable") this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u5F53\u524D\u914D\u7F6E\u670D\u52A1\u4E0D\u53EF\u5199\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
4839
+ else if (result === "failed") this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
4840
+ }).catch(() => {
4841
+ if (serial !== this._modelsWriteSerial || epoch !== this._modelsEpoch) return;
4842
+ this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u66F4\u65B0\uFF0C\u4F46\u4FDD\u5B58\u5931\u8D25\uFF1B\u91CD\u542F\u540E\u9700\u8981\u91CD\u65B0\u5237\u65B0\u3002";
4843
+ });
4844
+ }
4725
4845
  _invalidateModels() {
4726
4846
  const changed = this._modelsUpdatedAt !== void 0;
4727
4847
  this._modelsEpoch++;
@@ -4730,7 +4850,8 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4730
4850
  this._models = MODELS;
4731
4851
  this._modelsUpdatedAt = void 0;
4732
4852
  this._modelsError = void 0;
4733
- if (changed) {
4853
+ this._restoreModels();
4854
+ if (changed || this._modelsUpdatedAt !== void 0) {
4734
4855
  try {
4735
4856
  this.dependencies.modelsChanged?.();
4736
4857
  } catch {
@@ -4748,7 +4869,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4748
4869
  this._modelsFingerprint = modelsFingerprint;
4749
4870
  this._invalidateModels();
4750
4871
  }
4751
- const fingerprint = hash(state);
4872
+ const fingerprint = hash({ ...state, config: stableConfig(state.config) });
4752
4873
  if (fingerprint !== this._fingerprint) {
4753
4874
  this._fingerprint = fingerprint;
4754
4875
  this._revision = randomUUID3();
@@ -4824,16 +4945,20 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
4824
4945
  if (signal.aborted || epoch !== this._modelsEpoch) return this.status();
4825
4946
  const previousModels = this._models;
4826
4947
  const previousUpdatedAt = this._modelsUpdatedAt;
4948
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4827
4949
  this._models = models;
4828
- this._modelsUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
4950
+ this._modelsUpdatedAt = updatedAt;
4829
4951
  this._modelsError = void 0;
4952
+ let accepted = true;
4830
4953
  try {
4831
4954
  this.dependencies.modelsChanged?.();
4832
4955
  } catch {
4956
+ accepted = false;
4833
4957
  this._models = previousModels;
4834
4958
  this._modelsUpdatedAt = previousUpdatedAt;
4835
4959
  this._modelsError = "\u6A21\u578B\u76EE\u5F55\u5DF2\u8BFB\u53D6\uFF0C\u4F46\u6A21\u578B\u9009\u62E9\u5668\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002";
4836
4960
  }
4961
+ if (accepted) this._queueModelsWrite({ baseURL: state.config.baseURL, updatedAt, models }, epoch);
4837
4962
  } catch (error) {
4838
4963
  if (!signal.aborted && epoch === this._modelsEpoch) this._modelsError = error instanceof ModelDiscoveryError ? error.message : "\u6A21\u578B\u5217\u8868\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002";
4839
4964
  }
@@ -5001,7 +5126,7 @@ var OpenDesignCoRouterService = class extends (_a = TypertRemoteService, _status
5001
5126
  this._expect(request.expectedRevision);
5002
5127
  const expected = hash(state.apiRecord);
5003
5128
  await this._credentials().modifyRecord(API_KEY, async (current) => {
5004
- if (hash(current) !== expected || hash(this._config()) !== hash(state.config)) throw this._conflict();
5129
+ if (hash(current) !== expected || hash(stableConfig(this._config())) !== hash(stableConfig(state.config))) throw this._conflict();
5005
5130
  return { kind: "api-key", key: request.value };
5006
5131
  });
5007
5132
  return this.status();