dsh-aperture 0.3.2 → 0.4.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
@@ -1,4 +1,12 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, IMAGE_OFFLOAD_REQUIRED_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, ToolCallId, assertUsableApiKey, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload } from "@deepseek-ai/dsh-llm";
3
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
+ import { idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
5
+ import { requestImageDimensions } from "@deepseek-ai/dsh-attachment";
6
+ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
7
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
8
+ import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
9
+ import { isContextOverflow } from "@earendil-works/pi-ai/utils/overflow";
2
10
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
3
11
  //#region src/metadata/utils.ts
4
12
  /**
@@ -9,7 +17,7 @@ import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
9
17
  * @module dsh-aperture/metadata/utils
10
18
  */
11
19
  /** 读取普通 JSON 对象,拒绝数组与原始值。 */
12
- function asRecord$1(value) {
20
+ function asRecord$2(value) {
13
21
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
14
22
  }
15
23
  /** 读取非空且已去除首尾空白的字符串。 */
@@ -198,11 +206,11 @@ async function fetchModelsListing(instanceRoot, options = {}) {
198
206
  * @throws 当响应体不是可识别的清单时抛出 Error。
199
207
  */
200
208
  function readEntries$1(body, endpoint) {
201
- const record = asRecord$1(body);
209
+ const record = asRecord$2(body);
202
210
  if (!record) throw new Error(`${endpoint} 没有应答 JSON 对象`);
203
211
  if (Array.isArray(record.data)) return record.data;
204
- const models = asRecord$1(record.models);
205
- if (models) return Object.values(models).filter((value) => asRecord$1(value) !== void 0);
212
+ const models = asRecord$2(record.models);
213
+ if (models) return Object.values(models).filter((value) => asRecord$2(value) !== void 0);
206
214
  throw new Error(`${endpoint} 既没有应答 "data" 数组,也没有应答 "models" 对象`);
207
215
  }
208
216
  /** 读取错误响应体的一小段,用于诊断。 */
@@ -306,9 +314,9 @@ function providerHintsOf(model) {
306
314
  }
307
315
  /** 从一份清单文档中读取每一个可用条目。 */
308
316
  function readEntries(document) {
309
- const root = asRecord$1(document);
317
+ const root = asRecord$2(document);
310
318
  if (!root) return [];
311
- return readContainer(asRecord$1(root.providers) ?? asRecord$1(root.models) ?? root);
319
+ return readContainer(asRecord$2(root.providers) ?? asRecord$2(root.models) ?? root);
312
320
  }
313
321
  /**
314
322
  * 读取一层容器。
@@ -317,14 +325,14 @@ function readEntries(document) {
317
325
  * models.dev 实际发布的扁平文档是第二种形态,而旧式文档把第一种直接铺在根上。
318
326
  */
319
327
  function readContainer(map) {
320
- return Object.values(map).some((value) => asRecord$1(asRecord$1(value)?.models) !== void 0) ? readProviderMap(map) : readModelMap(map);
328
+ return Object.values(map).some((value) => asRecord$2(asRecord$2(value)?.models) !== void 0) ? readProviderMap(map) : readModelMap(map);
321
329
  }
322
330
  /** 读取以 provider 为键的映射,并从其 provider 推导每个模型的别名。 */
323
331
  function readProviderMap(providers) {
324
332
  const entries = [];
325
333
  for (const [providerKey, providerValue] of Object.entries(providers)) {
326
- const provider = asRecord$1(providerValue);
327
- const models = asRecord$1(provider?.models);
334
+ const provider = asRecord$2(providerValue);
335
+ const models = asRecord$2(provider?.models);
328
336
  if (!provider || !models) continue;
329
337
  const aliases = providerAliases(providerKey, stringValue(provider.id), stringValue(provider.name));
330
338
  for (const [modelKey, modelValue] of Object.entries(models)) {
@@ -338,7 +346,7 @@ function readProviderMap(providers) {
338
346
  function readModelMap(models) {
339
347
  const entries = [];
340
348
  for (const [modelKey, modelValue] of Object.entries(models)) {
341
- const model = asRecord$1(modelValue);
349
+ const model = asRecord$2(modelValue);
342
350
  if (!model) continue;
343
351
  const modelId = firstString([model.id, modelKey]) ?? modelKey;
344
352
  const entry = readModelEntry(modelKey, model, providerAliases(modelId.includes("/") ? modelId.split("/")[0] ?? "" : ""));
@@ -348,7 +356,7 @@ function readModelMap(models) {
348
356
  }
349
357
  /** 读取一个清单条目;未给出任何可用信息时为 `undefined`。 */
350
358
  function readModelEntry(modelKey, value, aliases) {
351
- const model = asRecord$1(value);
359
+ const model = asRecord$2(value);
352
360
  if (!model) return;
353
361
  const metadata = readModelMetadata(model);
354
362
  if (metadata === void 0) return;
@@ -363,9 +371,9 @@ function readModelEntry(modelKey, value, aliases) {
363
371
  }
364
372
  /** 读取一个 models.dev 条目所贡献的元数据。 */
365
373
  function readModelMetadata(model) {
366
- const limit = asRecord$1(model.limit);
367
- const topProvider = asRecord$1(model.top_provider);
368
- const modalities = asRecord$1(model.modalities);
374
+ const limit = asRecord$2(model.limit);
375
+ const topProvider = asRecord$2(model.top_provider);
376
+ const modalities = asRecord$2(model.modalities);
369
377
  const contextWindow = firstPositiveInteger([
370
378
  model.contextWindow,
371
379
  model.context_window,
@@ -562,21 +570,68 @@ function countEntries(document) {
562
570
  return Object.keys(root).length;
563
571
  }
564
572
  //#endregion
565
- //#region src/config.ts
573
+ //#region src/routes.ts
574
+ /**
575
+ * 三条路由的词汇与顺序。
576
+ *
577
+ * 顺序就是它们在报告、注册与界面上出现的顺序:Chat Completions 最常见,因此排在最前。
578
+ */
579
+ const VOCABULARY = [
580
+ {
581
+ protocol: "openai-completions",
582
+ label: "OpenAI Chat Completions"
583
+ },
584
+ {
585
+ protocol: "openai-responses",
586
+ label: "OpenAI Responses"
587
+ },
588
+ {
589
+ protocol: "anthropic-messages",
590
+ label: "Anthropic Messages"
591
+ }
592
+ ];
593
+ /** 把显示名括号里的协议名写成路由键能用的形状:`OpenAI Chat Completions` → `openai-chat-completions`。 */
594
+ function routeSuffix(label) {
595
+ return label.toLowerCase().replaceAll(" ", "-");
596
+ }
566
597
  /**
567
- * 配置 schema 与解析。
598
+ * 由前缀解析出这一代的三条路由。
568
599
  *
569
- * 本插件拥有自己的 entry(`aperture`,用户层就是 profile patch 里那一行的 `config`),
570
- * 但发布出去的一切都写进**另一个** entry `llm-pi-ai`:本插件决定有哪些模型,那个适配器
571
- * 决定怎么跟它们说话。
600
+ * 一个部署要换的从来只是前缀(`aperture` → 自己的名字):三条路由键都由它加协议名的小写写法拼
601
+ * 出来,三个显示名由它的标题写法加协议名拼出来。让它们互相矛盾因此变成不可能,而不是要校验出来的
602
+ * 错误。
572
603
  *
573
- * 整份 schema 都是 volatile 的:设置接缝**只**暴露 volatile 字段(没有 volatile 节点的
574
- * entry 不出现在 `describe()` 里,界面就无从编辑),而这里每个字段都只影响下一轮发现、
575
- * 没有一项需要重启——于是配置改动被 Loader 当作就地换引用的活更新,插件不重新挂载,
576
- * 正在跑的那轮刷新也不会被掐断。
604
+ * @param prefix - 已经过文法校验的路由名前缀。
605
+ * @returns 三条路由,顺序与 {@link VOCABULARY} 一致。
606
+ */
607
+ function resolveRoutes(prefix) {
608
+ const base = prefix.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
609
+ return VOCABULARY.map((route) => ({
610
+ ...route,
611
+ id: `${prefix}-${routeSuffix(route.label)}`,
612
+ displayName: `${base} (${route.label})`
613
+ }));
614
+ }
615
+ //#endregion
616
+ //#region src/types.ts
617
+ /**
618
+ * pi-ai 认得的推理档位,也是模型 `reasoningEfforts` 允许写下的键。
577
619
  *
578
- * @module dsh-aperture/config
620
+ * 这份名单是 pi-ai 的 `ModelThinkingLevel` 的镜像:多写一个键只会落进它不认识的字典项,
621
+ * 少写一个键则让部署无法声明它其实支持的档位。它住在词汇表这一层,因为配置 schema 与 profile
622
+ * 都要用它,而两者分处依赖链的两端。
579
623
  */
624
+ const REASONING_LEVELS = [
625
+ "off",
626
+ "minimal",
627
+ "low",
628
+ "medium",
629
+ "high",
630
+ "xhigh",
631
+ "max"
632
+ ];
633
+ //#endregion
634
+ //#region src/config.ts
580
635
  /** 本插件拥有、并可通过它配置的设置命名空间。 */
581
636
  const APERTURE_NAMESPACE = "aperture";
582
637
  /** 默认清单地址;参考实现用的是同一份文档。 */
@@ -585,8 +640,21 @@ const DEFAULT_MODEL_METADATA_URL = "https://models.dev/models.json";
585
640
  const DEFAULT_CONTEXT_WINDOW = 128e3;
586
641
  /** 访问网关与清单的单次请求超时。没有哪个部署需要为此改一次配置。 */
587
642
  const DEFAULT_TIMEOUT_MS = 2e4;
588
- /** provider 路由键的文法,与 Models 页面自身的规则一致。 */
589
- const ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
643
+ /**
644
+ * 路由名前缀的文法,与 Models 页面自身的规则一致。
645
+ *
646
+ * 前缀还要与协议名拼得起来(`${prefix}-openai-chat-completions` 等),因此它必须先满足路由键本身
647
+ * 的文法。
648
+ */
649
+ const ROUTE_PREFIX_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
650
+ /**
651
+ * 推理档位的键,故意声明成 `string` 而不是字面量联合。
652
+ *
653
+ * 运行期校验用的是同一份值(`z.union` 逐个比对),但 schemastery 的字典类型是
654
+ * `{ [key in K]: V }`:键写成字面量联合时它变成「每个档位都必须出现」的必填类型,于是任何一份
655
+ * 只声明了两三个档位的配置在类型上都成了错的——而配置面正是「只写用得到的档位」。
656
+ */
657
+ const EFFORT_KEYS = REASONING_LEVELS;
590
658
  /** 一个配置好的模型:对已发现模型的覆盖,或者一个额外的模型。 */
591
659
  const modelConfig = z.object({
592
660
  /** 模型 id;与已发现的 id 对应,或者新增一个网关没有列出的模型。 */
@@ -594,7 +662,7 @@ const modelConfig = z.object({
594
662
  /** 选择器里显示的名字。 */
595
663
  name: z.string(),
596
664
  /** 协议覆盖:OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages。 */
597
- api: z.string(),
665
+ protocol: z.string(),
598
666
  /** 上下文容量(token 数)。 */
599
667
  contextWindow: z.number().step(1).min(1),
600
668
  /** 输出能力(token 数)。 */
@@ -603,8 +671,8 @@ const modelConfig = z.object({
603
671
  input: z.array(z.union([z.const("text"), z.const("image")])),
604
672
  /** 强制打开或关闭推理能力。 */
605
673
  thinking: z.boolean(),
606
- /** 提供的推理档位:键 = 档位,值 = 协议里的写法。 */
607
- reasoningEfforts: z.dict(z.union([z.string(), z.const(null)]))
674
+ /** 提供的推理档位:键 = 档位,值 = 协议里的写法;只有 `off` 可以留空。 */
675
+ reasoningEfforts: z.dict(z.union([z.string(), z.const(null)]), z.union(EFFORT_KEYS))
608
676
  });
609
677
  /**
610
678
  * {@link Config} 的运行时 schema。
@@ -615,7 +683,7 @@ const modelConfig = z.object({
615
683
  */
616
684
  const Config = z.object({
617
685
  baseUrl: z.string().default(""),
618
- route: z.string().default("aperture"),
686
+ routePrefix: z.string().default("aperture"),
619
687
  apiKeyEnv: z.string().default(""),
620
688
  headers: z.dict(z.string()).default({}),
621
689
  enabledModelIds: z.array(z.string()).default([]),
@@ -640,26 +708,6 @@ function configValue(ref) {
640
708
  return ref.get() ?? {};
641
709
  }
642
710
  /**
643
- * 从一个路由键推出这一对路由的名字与显示名。
644
- *
645
- * 这三条事实曾经是三个可写字段,但一个部署要换的从来只是前缀:Anthropic 那条加
646
- * `-anthropic` 后缀,显示名是路由键的标题写法(`aperture` → `Aperture`)。让它们互相
647
- * 矛盾因此变成不可能,而不是要校验出来的错误。
648
- *
649
- * @param route - 已经过文法校验的 OpenAI 兼容路由键。
650
- * @returns 五个推导出来的路由与显示名。
651
- */
652
- function derivedNames(route) {
653
- const displayName = route.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
654
- return {
655
- responsesRoute: `${route}-responses`,
656
- anthropicRoute: `${route}-anthropic`,
657
- displayName,
658
- responsesDisplayName: `${displayName} (Responses)`,
659
- anthropicDisplayName: `${displayName} (Anthropic)`
660
- };
661
- }
662
- /**
663
711
  * 解析一段配置,只拒绝那些自身就矛盾的错误。
664
712
  *
665
713
  * `baseUrl` 缺失或不可用**不**算错误:插件照常挂载但处于休眠,这样 profile 可以在还没人
@@ -673,8 +721,8 @@ function derivedNames(route) {
673
721
  function resolveConfig(config) {
674
722
  const rawBaseUrl = (config.baseUrl ?? "").trim();
675
723
  const instanceRoot = normalizeBaseUrl(rawBaseUrl);
676
- const route = (config.route ?? "").trim();
677
- if (!ROUTE_PATTERN.test(route)) throw new Error(`route "${route}" 必须是小写连字符形式的 provider 路由名(需匹配 ${String(ROUTE_PATTERN)})`);
724
+ const routePrefix = (config.routePrefix ?? "").trim();
725
+ if (!ROUTE_PREFIX_PATTERN.test(routePrefix)) throw new Error(`routePrefix "${routePrefix}" 必须是小写连字符形式的路由名前缀(需匹配 ${String(ROUTE_PREFIX_PATTERN)})`);
678
726
  const models = config.models ?? [];
679
727
  const seen = /* @__PURE__ */ new Set();
680
728
  for (const model of models) {
@@ -682,14 +730,15 @@ function resolveConfig(config) {
682
730
  if (id.length === 0) throw new Error("models[].id 不能为空");
683
731
  if (seen.has(id)) throw new Error(`models 里重复列出了 "${id}"`);
684
732
  seen.add(id);
685
- if (model.api !== void 0 && model.api !== "openai-completions" && model.api !== "openai-responses" && model.api !== "anthropic-messages") throw new Error(`models["${id}"].api "${model.api}" 无法服务;请使用 openai-completions、openai-responses 或 anthropic-messages`);
733
+ assertEfforts(id, model.reasoningEfforts);
734
+ if (model.protocol !== void 0 && model.protocol !== "openai-completions" && model.protocol !== "openai-responses" && model.protocol !== "anthropic-messages") throw new Error(`models["${id}"].protocol "${model.protocol}" 无法服务;请使用 openai-completions、openai-responses 或 anthropic-messages`);
686
735
  }
687
736
  const apiKeyEnv = (config.apiKeyEnv ?? "").trim();
688
737
  return {
689
738
  instanceRoot,
690
739
  rawBaseUrl,
691
- route,
692
- ...derivedNames(route),
740
+ routePrefix,
741
+ routes: resolveRoutes(routePrefix),
693
742
  apiKeyEnv: apiKeyEnv.length === 0 ? void 0 : apiKeyEnv,
694
743
  headers: config.headers ?? {},
695
744
  enabledModelIds: config.enabledModelIds ?? [],
@@ -703,6 +752,23 @@ function resolveConfig(config) {
703
752
  };
704
753
  }
705
754
  /**
755
+ * 校验一条模型声明的推理档位。
756
+ *
757
+ * 键的名字由 schema 挡住(写错的档位名进不了这一步),这里挡的是值:除 `off` 之外的档位都必须在
758
+ * 协议里有一个非空写法,否则这一档声明了却发不出去,而发出去的东西是空串只会得到一次 400。
759
+ *
760
+ * @param id - 模型 id,用来把错误指到具体那一行。
761
+ * @param efforts - 用户写下的档位;没写时什么也不查。
762
+ * @throws Error 当某个档位没有可用的线缆写法时抛出。
763
+ */
764
+ function assertEfforts(id, efforts) {
765
+ for (const [level, wire] of Object.entries(efforts ?? {})) {
766
+ if (level === "off") continue;
767
+ if (wire === null) throw new Error(`models["${id}"].reasoningEfforts.${level} 不能为 null;只有 off 可以留空`);
768
+ if (wire.trim().length === 0) throw new Error(`models["${id}"].reasoningEfforts.${level} 不能是空串`);
769
+ }
770
+ }
771
+ /**
706
772
  * 把「解析当前的配置段」包成一个按源缓存的 thunk。
707
773
  *
708
774
  * 配置活引用的 `.get()` 只在值真的变了之后才换快照,没变就还是同一个对象,因此返回值可以
@@ -743,9 +809,9 @@ function buildReport(outcome, config, declared = {}) {
743
809
  }
744
810
  for (const id of declared.aliasIds ?? []) keys.set(id, [...keys.get(id) ?? [], "alias"]);
745
811
  const routes = (outcome?.routes ?? []).map((route) => ({
746
- provider: route.provider,
747
- ...route.profile.api === void 0 ? {} : { api: route.profile.api },
748
- ...route.profile.baseURL === void 0 ? {} : { baseURL: route.profile.baseURL },
812
+ id: route.route.id,
813
+ protocol: route.provider.protocol,
814
+ baseURL: route.provider.baseURL,
749
815
  models: route.models.length
750
816
  }));
751
817
  const models = [];
@@ -769,7 +835,7 @@ function buildReport(outcome, config, declared = {}) {
769
835
  ...alias === void 0 ? {} : { alias }
770
836
  };
771
837
  };
772
- for (const route of outcome?.routes ?? []) for (const model of route.models) models.push(describe(model, route.provider));
838
+ for (const route of outcome?.routes ?? []) for (const model of route.models) models.push(describe(model, route.route.id));
773
839
  for (const model of outcome?.models ?? []) if (!routed.has(model.id)) models.push(describe(model));
774
840
  return {
775
841
  place: config.instanceRoot ?? config.rawBaseUrl,
@@ -786,7 +852,7 @@ function buildReport(outcome, config, declared = {}) {
786
852
  */
787
853
  function refresh(outcome) {
788
854
  const catalog = outcome.catalog;
789
- const sync = outcome.sync;
855
+ const publish = outcome.publish;
790
856
  return {
791
857
  trigger: outcome.trigger,
792
858
  at: outcome.at.toISOString(),
@@ -802,11 +868,9 @@ function refresh(outcome) {
802
868
  url: outcome.endpoint,
803
869
  listed: outcome.listed
804
870
  } },
805
- ...sync === void 0 ? {} : { sync: {
806
- applied: sync.applied,
807
- ops: sync.ops,
808
- routes: sync.routes,
809
- ...sync.reason === void 0 ? {} : { reason: sync.reason }
871
+ ...publish === void 0 ? {} : { publish: {
872
+ routes: publish.routes,
873
+ ...publish.reason === void 0 ? {} : { reason: publish.reason }
810
874
  } }
811
875
  };
812
876
  }
@@ -814,14 +878,14 @@ function refresh(outcome) {
814
878
  //#region src/metadata/extract.ts
815
879
  /** 每个 Aperture 条目可能用来藏匿其事实的嵌套容器。 */
816
880
  function containers(record) {
817
- const metadata = asRecord$1(record.metadata);
881
+ const metadata = asRecord$2(record.metadata);
818
882
  return {
819
883
  metadata,
820
- capabilities: asRecord$1(record.capabilities),
821
- metadataCapabilities: asRecord$1(metadata?.capabilities),
822
- limit: asRecord$1(record.limit),
823
- limits: asRecord$1(record.limits),
824
- modalities: asRecord$1(record.modalities)
884
+ capabilities: asRecord$2(record.capabilities),
885
+ metadataCapabilities: asRecord$2(metadata?.capabilities),
886
+ limit: asRecord$2(record.limit),
887
+ limits: asRecord$2(record.limits),
888
+ modalities: asRecord$2(record.modalities)
825
889
  };
826
890
  }
827
891
  /**
@@ -831,11 +895,11 @@ function containers(record) {
831
895
  * @returns 所述的容量;两者都未给出时为 `undefined`。
832
896
  */
833
897
  function extractLimits(value) {
834
- const record = asRecord$1(value);
898
+ const record = asRecord$2(value);
835
899
  if (!record) return;
836
900
  const { metadata, limit, limits } = containers(record);
837
- const metadataLimit = asRecord$1(metadata?.limit);
838
- const metadataLimits = asRecord$1(metadata?.limits);
901
+ const metadataLimit = asRecord$2(metadata?.limit);
902
+ const metadataLimits = asRecord$2(metadata?.limits);
839
903
  const contextWindow = firstPositiveInteger([
840
904
  record.context_window_tokens,
841
905
  record.max_context_tokens,
@@ -884,9 +948,9 @@ function extractLimits(value) {
884
948
  }
885
949
  /** 读取条目所述的显示名(`display_name` 是 Aperture 的写法)。 */
886
950
  function extractDisplayName(value) {
887
- const record = asRecord$1(value);
951
+ const record = asRecord$2(value);
888
952
  if (!record) return;
889
- const metadata = asRecord$1(record.metadata);
953
+ const metadata = asRecord$2(record.metadata);
890
954
  return firstString([
891
955
  record.display_name,
892
956
  record.displayName,
@@ -897,7 +961,7 @@ function extractDisplayName(value) {
897
961
  }
898
962
  /** 读取条目公布的端点路径。 */
899
963
  function extractEndpoints(value) {
900
- const raw = asRecord$1(value)?.supported_endpoints;
964
+ const raw = asRecord$2(value)?.supported_endpoints;
901
965
  if (!Array.isArray(raw)) return [];
902
966
  return raw.flatMap((entry) => {
903
967
  const path = stringValue(entry);
@@ -906,10 +970,10 @@ function extractEndpoints(value) {
906
970
  }
907
971
  /** 读取条目上报的上游 provider 身份。 */
908
972
  function extractProvider(value) {
909
- const record = asRecord$1(value);
973
+ const record = asRecord$2(value);
910
974
  if (!record) return;
911
- const metadata = asRecord$1(record.metadata);
912
- const provider = asRecord$1(metadata?.provider);
975
+ const metadata = asRecord$2(record.metadata);
976
+ const provider = asRecord$2(metadata?.provider);
913
977
  const id = firstString([
914
978
  provider?.id,
915
979
  record.owned_by,
@@ -932,7 +996,7 @@ function extractProvider(value) {
932
996
  * @returns 所述的能力;未给出任何能力时为 `undefined`。
933
997
  */
934
998
  function extractCapabilities(value) {
935
- const record = asRecord$1(value);
999
+ const record = asRecord$2(value);
936
1000
  if (!record) return;
937
1001
  const { metadata, capabilities, metadataCapabilities, modalities } = containers(record);
938
1002
  const reasoning = firstBoolean([
@@ -969,7 +1033,7 @@ function extractInput(record, metadata, capabilities, metadataCapabilities, moda
969
1033
  record.input,
970
1034
  record.input_modalities,
971
1035
  modalities?.input,
972
- asRecord$1(metadata?.modalities)?.input,
1036
+ asRecord$2(metadata?.modalities)?.input,
973
1037
  metadata?.input,
974
1038
  metadata?.input_modalities
975
1039
  ];
@@ -997,7 +1061,7 @@ function extractInput(record, metadata, capabilities, metadataCapabilities, moda
997
1061
  }
998
1062
  /** 一个条目究竟是不是可用的模型行。 */
999
1063
  function extractModelId(value) {
1000
- const record = asRecord$1(value);
1064
+ const record = asRecord$2(value);
1001
1065
  return record === void 0 ? void 0 : stringValue(record.id);
1002
1066
  }
1003
1067
  //#endregion
@@ -1164,9 +1228,9 @@ function factsSource(apertureFact, catalogFact) {
1164
1228
  if (apertureFact !== void 0) return "aperture";
1165
1229
  return catalogFact !== void 0 ? "models.dev" : "default";
1166
1230
  }
1167
- /** 把配置里的一种 `api` 写法映射到可服务的协议。 */
1231
+ /** 把配置里的一种 `protocol` 写法映射到可服务的协议。 */
1168
1232
  function protocolFromConfigured(configured) {
1169
- switch (configured.api?.trim()) {
1233
+ switch (configured.protocol?.trim()) {
1170
1234
  case "openai-completions": return "openai-completions";
1171
1235
  case "openai-responses": return "openai-responses";
1172
1236
  case "anthropic-messages": return "anthropic-messages";
@@ -1198,74 +1262,60 @@ function isDeepSeekFamily(model) {
1198
1262
  return `${model.id} ${model.name} ${model.provider ?? ""}`.toLowerCase().includes("deepseek");
1199
1263
  }
1200
1264
  //#endregion
1201
- //#region src/profile.ts
1202
- /** 无凭据路由发送的占位凭据的默认值。 */
1203
- const DEFAULT_PLACEHOLDER_CREDENTIAL = "dsh-aperture";
1204
- /** 为 DeepSeek 方言模型提供的推理档位。 */
1205
- const DEEPSEEK_EFFORTS = {
1206
- off: "disabled",
1207
- high: "high",
1208
- max: "max"
1209
- };
1265
+ //#region src/plan.ts
1210
1266
  /**
1211
- * 为其他所有推理模型提供的推理档位。
1267
+ * 发布阶段:把发现的模型变成本插件自己服务的一条 provider 路由。
1212
1268
  *
1213
- * `off` 无值——适配器把它映射为「什么都不发」,对 OpenAI 兼容端点而言这就是把思考交给
1214
- * 模型自行决定。它之上的那一档是 Aperture 在它所代理的全部模型上都能接受的最宽写法;
1215
- * `minimal`、`xhigh`、`max` 都至少被某个上游以 400 拒绝过,因此发现的模型绝不提供,
1216
- * 更了解的部署可以在 `models` 里逐模型声明。
1269
+ * 这一层造的是**要注册出去的路由**,不是 dsh 的 profile(那份 profile patch 文档),因此名字一律
1270
+ * 说 route:{@link ProviderRoute} 是一条路由在 pi-ai 侧的事实,{@link PlannedRoute} 把它与它承载
1271
+ * 的模型绑在一起,{@link RoutePlan} 是一整代。
1272
+ *
1273
+ * 这里不做任何负载转换:三种协议都由 pi-ai 实现,剩下的工作只是逐模型陈述它无法从一个
1274
+ * 无法识别的网关 URL 推断出的事实——模型有多大、接受什么,以及它的推理控制在协议上如何
1275
+ * 传输。
1276
+ *
1277
+ * 两件网关事实塑造了本模块:pi-ai 的 OpenAI 兼容路径在既无凭据、又无非空 `authorization`
1278
+ * 头时拒绝派发,所以没有配 `apiKeyEnv` 的路由会带上一个占位头;pi-ai 的 `Model.maxTokens`
1279
+ * 是必填的,而没有谁声明过输出上限的模型不该被钉上一个凭空的数字,因此缺省值只作为
1280
+ * pi-ai 侧的请求上限,同时**不**作为本插件向宿主声明的默认值(见 `defaultMaxTokens`)。
1281
+ *
1282
+ * @module dsh-aperture/plan
1217
1283
  */
1218
- const GENERIC_EFFORTS = {
1219
- off: null,
1220
- high: "high"
1221
- };
1284
+ /** 无凭据路由发送的占位凭据的默认值。 */
1285
+ const DEFAULT_PLACEHOLDER_CREDENTIAL = "dsh-aperture";
1222
1286
  /**
1223
- * 把归一化后的注册表变成 provider profile。
1287
+ * 把归一化后的注册表变成 provider 路由。
1224
1288
  *
1225
1289
  * @param models - 所有已发现的模型。
1226
1290
  * @param options - 路由与凭据配置。
1227
1291
  * @returns 要发布的路由,以及未能被服务的模型。
1228
1292
  */
1229
- function buildProfilePlan(models, options) {
1230
- const completions = models.filter((model) => model.protocol === "openai-completions");
1231
- const responses = models.filter((model) => model.protocol === "openai-responses");
1232
- const anthropic = models.filter((model) => model.protocol === "anthropic-messages");
1293
+ function planRoutes(models, options) {
1233
1294
  const routes = [];
1234
- if (completions.length > 0) routes.push({
1235
- provider: options.route,
1236
- profile: buildProfile("openai-completions", completions, options),
1237
- models: completions
1238
- });
1239
- if (responses.length > 0) routes.push({
1240
- provider: options.responsesRoute,
1241
- profile: buildProfile("openai-responses", responses, options),
1242
- models: responses
1243
- });
1244
- if (anthropic.length > 0) routes.push({
1245
- provider: options.anthropicRoute,
1246
- profile: buildProfile("anthropic-messages", anthropic, options),
1247
- models: anthropic
1248
- });
1295
+ for (const route of options.routes) {
1296
+ const carrying = models.filter((model) => model.protocol === route.protocol);
1297
+ if (carrying.length === 0) continue;
1298
+ routes.push({
1299
+ route,
1300
+ provider: buildProviderRoute(route, carrying, options),
1301
+ models: carrying
1302
+ });
1303
+ }
1249
1304
  return {
1250
1305
  routes,
1251
- unserved: models.filter((model) => model.protocol === void 0),
1252
- ownedRoutes: [
1253
- options.route,
1254
- options.responsesRoute,
1255
- options.anthropicRoute
1256
- ]
1306
+ unserved: models.filter((model) => model.protocol === void 0)
1257
1307
  };
1258
1308
  }
1259
- /** 构建一种协议的路由 profile。 */
1260
- function buildProfile(protocol, models, options) {
1261
- const headers = routeHeaders(protocol, options);
1309
+ /** 构建一条路由在 pi-ai 侧的事实。 */
1310
+ function buildProviderRoute(route, models, options) {
1311
+ const headers = routeHeaders(route.protocol, options);
1262
1312
  return {
1263
- displayName: protocol === "openai-completions" ? options.displayName : protocol === "openai-responses" ? options.responsesDisplayName : options.anthropicDisplayName,
1264
- api: protocol,
1265
- baseURL: buildRouteBaseUrl(options.instanceRoot, protocol),
1266
- ...options.apiKeyEnv === void 0 ? {} : { apiKeyEnv: options.apiKeyEnv },
1313
+ displayName: route.displayName,
1314
+ protocol: route.protocol,
1315
+ baseURL: buildRouteBaseUrl(options.instanceRoot, route.protocol),
1267
1316
  ...headers === void 0 ? {} : { headers },
1268
- models: models.map((model) => buildModelEntry(model, protocol, options))
1317
+ ...options.apiKeyEnv === void 0 ? {} : { apiKeyEnv: options.apiKeyEnv },
1318
+ models: models.map((model) => buildModelEntry(model, route.protocol, options))
1269
1319
  };
1270
1320
  }
1271
1321
  /**
@@ -1320,173 +1370,32 @@ function resolveReasoning(model, protocol, configured) {
1320
1370
  ...compatFor(model, protocol)
1321
1371
  };
1322
1372
  }
1323
- /**
1324
- * 推理模型所需的 compat 块。
1325
- *
1326
- * pi-ai 从 provider id 与 base URL 推断协议格式兼容性,而 Aperture 的 URL 对它说明不了
1327
- * 什么,因此 DeepSeek 方言必须直接声明。`supportsReasoningEffort` 也要声明:URL 无法被
1328
- * pi-ai 归位的网关目前默认为 true,但真正让 `reasoning_effort` 传输出去的是这个开关。
1329
- *
1330
- * @param model - 被描述的模型。
1331
- * @param protocol - 该路由的协议。
1332
- * @returns compat 块,或空对象。
1333
- */
1373
+ /** 始终声明 `supportsReasoningEffort`:真正让 `reasoning_effort` 传输出去的是这个开关。 */
1334
1374
  function compatFor(model, protocol) {
1335
1375
  if (protocol !== "openai-completions") return {};
1336
- const compat = { supportsReasoningEffort: true };
1337
- if (isDeepSeekFamily(model)) compat.thinkingFormat = "deepseek";
1338
- return { compat };
1339
- }
1340
- //#endregion
1341
- //#region src/sync.ts
1342
- /** pi-ai 适配器注册的设置命名空间,也是本插件写入的那一个。 */
1343
- const PI_AI_NAMESPACE = "llm-pi-ai";
1344
- /**
1345
- * 找一个 entry 的 descriptor。
1346
- *
1347
- * 设置接缝没有「按命名空间取值」这种读法:`describe()` 是唯一入口,它按 Loader 里的 entry
1348
- * 逐个报告(`ns` 就是 entry id)。目标 entry 不存在时(比如 pi-ai 适配器没挂载)读不到。
1349
- *
1350
- * @param settings - 设置服务。
1351
- * @param ns - 目标 entry id。
1352
- * @returns 该 entry 的 descriptor;没有这个 entry 时为 `undefined`。
1353
- */
1354
- function sectionDescriptor(settings, ns) {
1355
- try {
1356
- return settings.describe().find((descriptor) => descriptor.ns === ns);
1357
- } catch {
1358
- return;
1359
- }
1360
- }
1361
- /**
1362
- * 读一个 entry 的生效值。
1363
- *
1364
- * @param settings - 设置服务。
1365
- * @param ns - 目标 entry id。
1366
- * @returns 该 entry 的生效值(深冻结快照);没有这个 entry 时为 `undefined`。
1367
- */
1368
- function sectionValue(settings, ns) {
1369
- return sectionDescriptor(settings, ns)?.value;
1370
- }
1371
- /**
1372
- * 计算使某个配置段与方案一致的路径 op。
1373
- *
1374
- * @param current - 已解析的 `llm-pi-ai` 值;命名空间未注册时为 `undefined`。
1375
- * @param routes - 方案希望存在的路由。
1376
- * @param ownedRoutes - 本插件拥有的每个路由键,因此不再有模型的路由会被移除,而不是
1377
- * 继续服务一份陈旧的清单。
1378
- * @returns 要应用的 op;配置段已经匹配时为空数组。
1379
- */
1380
- function planSync(current, routes, ownedRoutes) {
1381
- const providers = readProviders(current);
1382
- if (providers === void 0) return [];
1383
- const ops = [];
1384
- const desired = new Map(routes.map((route) => [route.provider, route.profile]));
1385
- for (const provider of ownedRoutes) {
1386
- const profile = desired.get(provider);
1387
- if (profile === void 0) {
1388
- if (provider in providers) ops.push({
1389
- op: "unset",
1390
- path: ["providers", provider]
1391
- });
1392
- continue;
1393
- }
1394
- if (deepEqualJson(providers[provider], profile)) continue;
1395
- ops.push({
1396
- op: "set",
1397
- path: ["providers", provider],
1398
- value: profile
1399
- });
1400
- }
1401
- return ops;
1402
- }
1403
- /**
1404
- * 把一个方案发布到 `llm-pi-ai` 配置段。
1405
- *
1406
- * @param settings - 设置服务。
1407
- * @param routes - 要发布的路由。
1408
- * @param ownedRoutes - 本插件拥有的每个路由键。
1409
- * @returns 发生了什么;未写入任何内容时包含原因。
1410
- */
1411
- async function applySync(settings, routes, ownedRoutes) {
1412
- const current = sectionValue(settings, PI_AI_NAMESPACE);
1413
- if (current === void 0) return {
1414
- applied: false,
1415
- ops: 0,
1416
- routes: [],
1417
- reason: `设置命名空间 "${PI_AI_NAMESPACE}" 未注册;@deepseek-ai/dsh-llm-pi-ai 是否已挂载?`
1418
- };
1419
- if (readProviders(current) === void 0) return {
1420
- applied: false,
1421
- ops: 0,
1422
- routes: [],
1423
- reason: `"${PI_AI_NAMESPACE}" 配置段不是 provider 字典`
1424
- };
1425
- const ops = planSync(current, routes, ownedRoutes);
1426
- if (ops.length === 0) return {
1427
- applied: false,
1428
- ops: 0,
1429
- routes: routes.map((route) => route.provider),
1430
- reason: "已处于同步状态"
1431
- };
1432
- try {
1433
- await settings.mutate(PI_AI_NAMESPACE, ops, currentRevision(settings));
1434
- } catch (error) {
1435
- if (!isConflict(error)) throw error;
1436
- const retryOps = planSync(sectionValue(settings, PI_AI_NAMESPACE), routes, ownedRoutes);
1437
- if (retryOps.length === 0) return {
1438
- applied: false,
1439
- ops: 0,
1440
- routes: routes.map((route) => route.provider),
1441
- reason: "已处于同步状态"
1442
- };
1443
- await settings.mutate(PI_AI_NAMESPACE, retryOps, currentRevision(settings));
1444
- }
1445
- return {
1446
- applied: true,
1447
- ops: ops.length,
1448
- routes: routes.map((route) => route.provider)
1449
- };
1450
- }
1451
- /** 从已解析的配置段值中读出 provider 字典。 */
1452
- function readProviders(current) {
1453
- if (current === null || typeof current !== "object") return;
1454
- const providers = current.providers;
1455
- if (providers === void 0) return {};
1456
- return providers !== null && typeof providers === "object" && !Array.isArray(providers) ? providers : void 0;
1457
- }
1458
- /** pi-ai 配置段的当前版本号;provider 未暴露时为空。 */
1459
- function currentRevision(settings) {
1460
- return sectionDescriptor(settings, PI_AI_NAMESPACE)?.revision;
1461
- }
1462
- /** 判断某个可抛出对象是否为设置接缝的陈旧版本号冲突。 */
1463
- function isConflict(error) {
1464
- return error instanceof Error && error.code === "SETTINGS_CONFLICT";
1376
+ return { compat: isDeepSeekFamily(model) ? {
1377
+ supportsReasoningEffort: true,
1378
+ thinkingFormat: "deepseek"
1379
+ } : { supportsReasoningEffort: true } };
1465
1380
  }
1381
+ /** 为 DeepSeek 方言模型提供的推理档位。 */
1382
+ const DEEPSEEK_EFFORTS = {
1383
+ off: "disabled",
1384
+ high: "high",
1385
+ max: "max"
1386
+ };
1466
1387
  /**
1467
- * 结构化 JSON 相等性。
1468
- *
1469
- * 之所以自己写而不导入,是因为这里比较的值恰好都是 JSON:本插件生成的 profile,以及设置
1470
- * 接缝从文档里解析回来的 profile。键顺序不属于这种同一性,因此被归一化掉。
1388
+ * 为其他所有推理模型提供的推理档位。
1471
1389
  *
1472
- * @param left - 一个 JSON 值。
1473
- * @param right - 另一个。
1474
- * @returns 两者是否结构相等。
1390
+ * `off` 无值——pi-ai 把它映射为「什么都不发」,对 OpenAI 兼容端点而言这就是把思考交给
1391
+ * 模型自行决定。它之上的那一档是 Aperture 在它所代理的全部模型上都能接受的最宽写法;
1392
+ * `minimal`、`xhigh`、`max` 都至少被某个上游以 400 拒绝过,因此发现的模型绝不提供,
1393
+ * 更了解的部署可以在 `models` 里逐模型声明。
1475
1394
  */
1476
- function deepEqualJson(left, right) {
1477
- if (left === right) return true;
1478
- if (Array.isArray(left) || Array.isArray(right)) {
1479
- if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
1480
- return left.every((value, index) => deepEqualJson(value, right[index]));
1481
- }
1482
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
1483
- const leftRecord = left;
1484
- const rightRecord = right;
1485
- const leftKeys = Object.keys(leftRecord).filter((key) => leftRecord[key] !== void 0);
1486
- const rightKeys = Object.keys(rightRecord).filter((key) => rightRecord[key] !== void 0);
1487
- if (leftKeys.length !== rightKeys.length) return false;
1488
- return leftKeys.every((key) => key in rightRecord && deepEqualJson(leftRecord[key], rightRecord[key]));
1489
- }
1395
+ const GENERIC_EFFORTS = {
1396
+ off: null,
1397
+ high: "high"
1398
+ };
1490
1399
  //#endregion
1491
1400
  //#region src/runtime.ts
1492
1401
  /** 单飞(single-flight)的发现与发布。 */
@@ -1613,19 +1522,14 @@ var ApertureRuntime = class {
1613
1522
  images: config.images,
1614
1523
  reasoning: config.reasoning
1615
1524
  }, catalog.lookup);
1616
- const plan = buildProfilePlan(registry.models, {
1525
+ const plan = planRoutes(registry.models, {
1617
1526
  instanceRoot: config.instanceRoot,
1618
- route: config.route,
1619
- responsesRoute: config.responsesRoute,
1620
- anthropicRoute: config.anthropicRoute,
1621
- displayName: config.displayName,
1622
- responsesDisplayName: config.responsesDisplayName,
1623
- anthropicDisplayName: config.anthropicDisplayName,
1527
+ routes: config.routes,
1624
1528
  ...config.apiKeyEnv === void 0 ? {} : { apiKeyEnv: config.apiKeyEnv },
1625
1529
  headers: config.headers,
1626
1530
  configured: config.models
1627
1531
  });
1628
- const sync = await this.publish(config, plan);
1532
+ const published = await this.publish(config, plan);
1629
1533
  const outcome = {
1630
1534
  trigger,
1631
1535
  ok: true,
@@ -1637,26 +1541,28 @@ var ApertureRuntime = class {
1637
1541
  routes: plan.routes,
1638
1542
  unserved: plan.unserved,
1639
1543
  catalog,
1640
- sync
1544
+ publish: published
1641
1545
  };
1642
1546
  this.latest = outcome;
1643
- this.deps.logger.info("发现 %d 个模型(来自 %s);已发布 %d 条路由%s", registry.models.length, endpoint, plan.routes.length, sync.applied ? "" : ` (${sync.reason ?? "未写入"})`);
1547
+ this.deps.logger.info("发现 %d 个模型(来自 %s);已注册 %d 条路由%s", registry.models.length, endpoint, published.routes.length, published.reason === void 0 ? "" : `(${published.reason})`);
1644
1548
  return outcome;
1645
1549
  }
1646
- /** 写入方案,或说明为什么没有写入任何内容。 */
1550
+ /**
1551
+ * 把方案交给注册层,或说明为什么没有注册任何内容。
1552
+ *
1553
+ * 关掉 `sync` 是「撤下本插件的路由」而不是「什么都不做」:适配器换成零条路由,于是配置里
1554
+ * 这些模型不再可选,界面上也不会留下一份谁也说不清归属的清单。
1555
+ */
1647
1556
  async publish(config, plan) {
1648
1557
  const routes = config.sync ? plan.routes : [];
1649
1558
  try {
1650
- const outcome = await applySync(this.deps.settings, routes, plan.ownedRoutes);
1651
- return config.sync || outcome.applied ? outcome : {
1652
- ...outcome,
1653
- reason: "同步已关闭,本插件没有发布过路由"
1654
- };
1559
+ return await this.deps.provider.publish({
1560
+ ...plan,
1561
+ routes
1562
+ });
1655
1563
  } catch (error) {
1656
- this.deps.logger.warn("发布发现的清单失败:%s", message(error));
1564
+ this.deps.logger.warn("注册发现的路由失败:%s", message(error));
1657
1565
  return {
1658
- applied: false,
1659
- ops: 0,
1660
1566
  routes: [],
1661
1567
  reason: message(error)
1662
1568
  };
@@ -1670,7 +1576,7 @@ function message(error) {
1670
1576
  //#endregion
1671
1577
  //#region src/panel.ts
1672
1578
  /** 把未知值当成一个普通对象;数组与 `null` 都不算。 */
1673
- function asRecord(input) {
1579
+ function asRecord$1(input) {
1674
1580
  return typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
1675
1581
  }
1676
1582
  /** 一个值是不是「没写」:空串、空数组、空字典都算。 */
@@ -1704,8 +1610,8 @@ function prune(entry) {
1704
1610
  function declaredOverrides(settings) {
1705
1611
  const user = readSection(settings).user;
1706
1612
  return {
1707
- models: (Array.isArray(user.models) ? user.models : []).map(asRecord),
1708
- aliasIds: Object.keys(asRecord(user.modelAliases))
1613
+ models: (Array.isArray(user.models) ? user.models : []).map(asRecord$1),
1614
+ aliasIds: Object.keys(asRecord$1(user.modelAliases))
1709
1615
  };
1710
1616
  }
1711
1617
  /**
@@ -1725,8 +1631,8 @@ function readSection(settings) {
1725
1631
  descriptor = void 0;
1726
1632
  }
1727
1633
  return {
1728
- value: asRecord(descriptor?.value),
1729
- user: asRecord(descriptor?.user),
1634
+ value: asRecord$1(descriptor?.value),
1635
+ user: asRecord$1(descriptor?.user),
1730
1636
  revision: descriptor?.revision
1731
1637
  };
1732
1638
  }
@@ -1747,11 +1653,11 @@ function mergeEntry(base, patch) {
1747
1653
  if (name.length === 0) delete entry.name;
1748
1654
  else entry.name = name;
1749
1655
  }
1750
- if (patch.api !== void 0) {
1751
- const api = patch.api === null ? "" : patch.api.trim();
1752
- if (api.length === 0) delete entry.api;
1753
- else if (api !== "openai-completions" && api !== "openai-responses" && api !== "anthropic-messages") return { error: `api "${api}" 无法服务;只能是 openai-completions、openai-responses 或 anthropic-messages` };
1754
- else entry.api = api;
1656
+ if (patch.protocol !== void 0) {
1657
+ const protocol = patch.protocol === null ? "" : patch.protocol.trim();
1658
+ if (protocol.length === 0) delete entry.protocol;
1659
+ else if (protocol !== "openai-completions" && protocol !== "openai-responses" && protocol !== "anthropic-messages") return { error: `protocol "${protocol}" 无法服务;只能是 openai-completions、openai-responses 或 anthropic-messages` };
1660
+ else entry.protocol = protocol;
1755
1661
  }
1756
1662
  for (const field of ["contextWindow", "maxTokens"]) {
1757
1663
  const value = patch[field];
@@ -1806,9 +1712,9 @@ function createPanelOps(deps) {
1806
1712
  summary: "缺少要写入的参数。"
1807
1713
  };
1808
1714
  const section = readSection(deps.settings);
1809
- const before = (Array.isArray(section.value.models) ? section.value.models : []).map((entry) => prune(asRecord(entry)));
1810
- const aliases = asRecord(section.value.modelAliases);
1811
- const owned = asRecord(section.user.modelAliases);
1715
+ const before = (Array.isArray(section.value.models) ? section.value.models : []).map((entry) => prune(asRecord$1(entry)));
1716
+ const aliases = asRecord$1(section.value.modelAliases);
1717
+ const owned = asRecord$1(section.user.modelAliases);
1812
1718
  const index = before.findIndex((entry) => entry.id === modelId);
1813
1719
  const currentAlias = typeof aliases[modelId] === "string" ? aliases[modelId] : "";
1814
1720
  let models = before;
@@ -1875,6 +1781,1121 @@ function createPanelOps(deps) {
1875
1781
  };
1876
1782
  }
1877
1783
  //#endregion
1784
+ //#region src/adapter/replay.ts
1785
+ /**
1786
+ * 重放信封:把 pi-ai 响应里那些「下一次请求必须原样带回去」的原生元数据存进行会话日志。
1787
+ *
1788
+ * pi-ai 的 replay 是**无状态全量历史**:Anthropic 的思考签名、OpenAI Responses 的消息 id 与
1789
+ * reasoning item 都活在 assistant 消息的内容块字段上,下一次请求把整条历史重新物化时再写回去。
1790
+ * 宿主的日志不存这些字段,因此本模块把「响应级」与「块级」两半分开放进 `ReplayEnvelope`,
1791
+ * 并在读回来时**先证明它确实是自己写的**。
1792
+ *
1793
+ * 证明这件事不能省:历史里可能有本插件之外的适配器(升级前的 `llm-pi-ai`)写下的信封,而宿主
1794
+ * 只在「历史路由与目标路由属于同一个适配器实例」时才把信封交回来——升级后的第一次对话正好满足
1795
+ * 这个条件,却带着别人的形状。读不出来就降级成 provider 中立的内容,而不是拿别人的字段硬套。
1796
+ *
1797
+ * @module dsh-aperture/adapter/replay
1798
+ */
1799
+ /** 本插件信封的类型标记;与任何别的适配器都不共享。 */
1800
+ const REPLAY_KIND = "aperture";
1801
+ /**
1802
+ * 把一次成功的响应收成重放信封。
1803
+ *
1804
+ * `blocks` 由调用方按**实际发出的块顺序**给出:宿主在装配时会按同样顺序对齐,数量不符就整封
1805
+ * 丢弃。因此这里不自己去数消息里的块,而是照抄流式转换记下来的那一份。
1806
+ *
1807
+ * @param message - pi-ai 的终态助手消息。
1808
+ * @param provider - provider 路由键。
1809
+ * @param model - 请求里的模型 id。
1810
+ * @param blocks - 每个已发出块的原生元数据,按首次出现的顺序。
1811
+ * @returns 宿主可以存进消息来源的信封。
1812
+ */
1813
+ function toReplayState(message, provider, model, blocks) {
1814
+ return {
1815
+ response: {
1816
+ kind: REPLAY_KIND,
1817
+ version: 1,
1818
+ api: message.api,
1819
+ provider,
1820
+ model,
1821
+ ...message.responseId === void 0 ? {} : { responseId: message.responseId },
1822
+ ...message.responseModel === void 0 ? {} : { responseModel: message.responseModel },
1823
+ ...message.providerThinkingLevel === void 0 ? {} : { providerThinkingLevel: message.providerThinkingLevel },
1824
+ stopReason: message.stopReason
1825
+ },
1826
+ blocks: [...blocks]
1827
+ };
1828
+ }
1829
+ /**
1830
+ * 读回一份重放状态。
1831
+ *
1832
+ * @param value - 会话日志里携带的原生元数据。
1833
+ * @returns 本插件写下的状态;不是本插件的(例如升级前由 `llm-pi-ai` 写下的)时为 `undefined`。
1834
+ * @throws LlmError 类型标记与版本都是自己的、字段却不成形时——那是记录损坏,不是别人的信封。
1835
+ */
1836
+ function readReplayState(value) {
1837
+ const envelope = asRecord(value);
1838
+ if (envelope === void 0) return void 0;
1839
+ const response = asRecord(envelope.response);
1840
+ if (response === void 0) return void 0;
1841
+ if (response.kind !== "aperture") return void 0;
1842
+ if (response.version !== 1) throw new LlmError(`dsh-aperture: 重放信封的版本 ${String(response.version)} 不是本适配器认得的 1`, "INVALID_REPLAY_STATE");
1843
+ for (const key of [
1844
+ "api",
1845
+ "provider",
1846
+ "model",
1847
+ "stopReason"
1848
+ ]) if (!isNonEmptyString(response[key])) throw new LlmError(`dsh-aperture: 重放信封缺少 ${key}`, "INVALID_REPLAY_STATE");
1849
+ const blocks = envelope.blocks === void 0 ? void 0 : readBlocks(envelope.blocks);
1850
+ return {
1851
+ response: {
1852
+ kind: REPLAY_KIND,
1853
+ version: 1,
1854
+ api: response.api,
1855
+ provider: response.provider,
1856
+ model: response.model,
1857
+ stopReason: response.stopReason,
1858
+ ...optionalString(response, "responseId"),
1859
+ ...optionalString(response, "responseModel"),
1860
+ ...optionalString(response, "providerThinkingLevel")
1861
+ },
1862
+ ...blocks === void 0 ? {} : { blocks }
1863
+ };
1864
+ }
1865
+ /** 校验块级元数据。 */
1866
+ function readBlocks(value) {
1867
+ if (!Array.isArray(value)) throw new LlmError("dsh-aperture: 重放信封的 blocks 不是数组", "INVALID_REPLAY_STATE");
1868
+ return value.map((entry) => {
1869
+ const block = asRecord(entry);
1870
+ if (block === void 0) throw new LlmError("dsh-aperture: 重放信封的块不是对象", "INVALID_REPLAY_STATE");
1871
+ if (block.redacted !== void 0 && typeof block.redacted !== "boolean") throw new LlmError("dsh-aperture: 重放信封的 redacted 不是布尔值", "INVALID_REPLAY_STATE");
1872
+ return {
1873
+ ...optionalString(block, "textSignature"),
1874
+ ...optionalString(block, "thinkingSignature"),
1875
+ ...optionalString(block, "thoughtSignature"),
1876
+ ...optionalString(block, "namespace"),
1877
+ ...block.redacted === void 0 ? {} : { redacted: block.redacted }
1878
+ };
1879
+ });
1880
+ }
1881
+ /** 取一个自有字段。 */
1882
+ function optionalString(source, key) {
1883
+ const value = source[key];
1884
+ if (value === void 0) return {};
1885
+ if (typeof value !== "string") throw new LlmError(`dsh-aperture: 重放信封的 ${key} 不是字符串`, "INVALID_REPLAY_STATE");
1886
+ return { [key]: value };
1887
+ }
1888
+ /** 把一个未知值当成普通对象;数组与 `null` 都不算。 */
1889
+ function asRecord(value) {
1890
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1891
+ }
1892
+ /** 一个未知值是不是非空字符串。 */
1893
+ function isNonEmptyString(value) {
1894
+ return typeof value === "string" && value.length > 0;
1895
+ }
1896
+ //#endregion
1897
+ //#region src/adapter/context.ts
1898
+ /**
1899
+ * 请求转换:宿主的消息词汇 → pi-ai 的 `Context`。
1900
+ *
1901
+ * 这里只做结构搬运,不做语义翻译:两边的消息词汇本来就是同一套(谁先有这套词汇不重要,
1902
+ * 重要的是三种协议的线缆形状由 pi-ai 的 API 实现负责)。真正需要判断的只有四件事——
1903
+ * system 提示落在哪里、工具结果怎么认领它的工具名、推理块携带的原生签名怎么回填,以及
1904
+ * 图片怎么变成网关收得下的字节。
1905
+ *
1906
+ * 宿主在本模块之前已经替所有路由做掉了两件投影:文件块 → 文本句柄、只声明文本的模型上的
1907
+ * 图片 → 稳定的占位文本(`LlmRuntime` 的 dispatch 路径)。因此这里看到的 `file` 块只可能
1908
+ * 是宿主自己也没投影的路径,遇到就响亮拒绝,而不是悄悄丢掉。
1909
+ *
1910
+ * @module dsh-aperture/adapter/context
1911
+ */
1912
+ /**
1913
+ * 一张图片在请求里的目标版本。
1914
+ *
1915
+ * 与 `dsh-llm-pi-ai` 自己的默认值一致:4 Mi 像素的上限(等价于 2048×2048)与 1 MiB 的
1916
+ * 单张编码字节上限。网关不通过任何接口声明它接受什么,而这两个数字是当前发布物里已经被
1917
+ * 验证过的那一组。
1918
+ */
1919
+ const REQUEST_IMAGE_POLICY = {
1920
+ maxPixels: 4194304,
1921
+ maxBytes: 1048576
1922
+ };
1923
+ /** 一次请求里图片累积后的 base64 字节上限;超过就要求上层先卸载最旧的几张。 */
1924
+ const MAX_REQUEST_IMAGE_BYTES = 20971520;
1925
+ /**
1926
+ * 把一次请求的历史转成 pi-ai 的 `Context`。
1927
+ *
1928
+ * @param options - 完整请求。
1929
+ * @param images - 图片转换所需的附件服务;缺失时任何图片都按不可用处理。
1930
+ * @param onDegrade - 观察到一条历史因为重放元数据不可用而降级时调用。
1931
+ * @returns pi-ai 的请求上下文。
1932
+ * @throws LlmError 历史里有无法表示的块、缺附件服务、或图片超出请求预算时。
1933
+ */
1934
+ async function toPiContext(options, images, onDegrade) {
1935
+ assertSupportedHistory(options.messages);
1936
+ const split = splitSystemPrompt(options);
1937
+ const requestImages = images === void 0 ? void 0 : await prepareRequestImages(split.messages, images);
1938
+ if (requestImages !== void 0) {
1939
+ const offloadImages = requiredImageOffload(split.messages, {
1940
+ representation: "base64",
1941
+ maxBytes: MAX_REQUEST_IMAGE_BYTES
1942
+ }, (block) => requestImages.get(block.attachment.attachmentId)?.bytes ?? 0);
1943
+ if (offloadImages > 0) throw new LlmError(`dsh-aperture: 请求里的图片超过 ${MAX_REQUEST_IMAGE_BYTES} 字节的 base64 上限;还需要卸载最旧的 ${offloadImages} 张。`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
1944
+ }
1945
+ const exact = requestImages === void 0 ? split.messages : projectOffloadedImages(split.messages, (ref) => offloadedImageText(ref));
1946
+ const toolNames = /* @__PURE__ */ new Map();
1947
+ const messages = [];
1948
+ for (const message of exact) {
1949
+ if (message.role === "system") {
1950
+ messages.push({
1951
+ role: "user",
1952
+ content: flattenText(message),
1953
+ timestamp: 0
1954
+ });
1955
+ continue;
1956
+ }
1957
+ if (message.role === "assistant") {
1958
+ const assistant = toPiAssistant(message, onDegrade);
1959
+ for (const block of assistant.content) if (block.type === "toolCall") toolNames.set(block.id, block.name);
1960
+ messages.push(assistant);
1961
+ continue;
1962
+ }
1963
+ if (message.role === "tool") {
1964
+ messages.push(toolResultOf(message, toolNames, userContent(message.content, requestImages)));
1965
+ continue;
1966
+ }
1967
+ if (message.role === "developer") throw new LlmError("dsh-aperture: 不支持 developer 消息", "UNSUPPORTED_CONTENT");
1968
+ messages.push({
1969
+ role: "user",
1970
+ content: userContent(message.content, requestImages),
1971
+ timestamp: 0
1972
+ });
1973
+ }
1974
+ const tools = toolsOf(options);
1975
+ return {
1976
+ ...split.systemPrompt === void 0 ? {} : { systemPrompt: split.systemPrompt },
1977
+ messages,
1978
+ ...tools === void 0 ? {} : { tools }
1979
+ };
1980
+ }
1981
+ /** 拒绝任何无法表示的块,而不是把它们悄悄丢掉。 */
1982
+ function assertSupportedHistory(messages) {
1983
+ for (const message of messages) {
1984
+ if (message.content.some((block) => block.type === "tool-addition" || block.type === "tool-removal")) throw new LlmError("dsh-aperture: 工具变更块不在本次请求里表示", "UNSUPPORTED_CONTENT");
1985
+ if (message.role === "developer") throw new LlmError("dsh-aperture: 不支持 developer 消息", "UNSUPPORTED_CONTENT");
1986
+ if (message.role !== "user" && message.role !== "tool" && contentHasImage(message.content)) throw new LlmError(`dsh-aperture: pi-ai 无法表示 ${message.role} 消息里的图片`, "UNSUPPORTED_CONTENT");
1987
+ if (message.content.some((block) => block.type === "file")) throw new LlmError("dsh-aperture: 文件块没有被投影成文本", "UNSUPPORTED_CONTENT");
1988
+ }
1989
+ }
1990
+ /**
1991
+ * 选出 system 提示。
1992
+ *
1993
+ * 一次性调用者把提示放在 `system` 字段里;循环构造的请求把它作为首位 `system` 消息放在历史
1994
+ * 里。两种都在这里归一。`system` 字段一旦存在就由它独占提示位,历史里的 `system` 消息一律
1995
+ * 降级——否则同一段提示会进两次。
1996
+ */
1997
+ function splitSystemPrompt(options) {
1998
+ if (options.system !== void 0) return {
1999
+ systemPrompt: options.system,
2000
+ messages: options.messages
2001
+ };
2002
+ const [first, ...rest] = options.messages;
2003
+ if (first?.role !== "system") return { messages: options.messages };
2004
+ const text = flattenText(first);
2005
+ return {
2006
+ ...text.length === 0 ? {} : { systemPrompt: text },
2007
+ messages: rest
2008
+ };
2009
+ }
2010
+ /** 把一个 harness 消息的文本块拼成一段文本。 */
2011
+ function flattenText(message) {
2012
+ return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
2013
+ }
2014
+ /** 转换一条工具结果消息。 */
2015
+ function toolResultOf(message, toolNames, content) {
2016
+ return {
2017
+ role: "toolResult",
2018
+ toolCallId: message.toolCallId,
2019
+ toolName: toolNames.get(message.toolCallId) ?? "unknown",
2020
+ content: typeof content === "string" ? [{
2021
+ type: "text",
2022
+ text: content || "(no output)"
2023
+ }] : content,
2024
+ isError: message.isError ?? false,
2025
+ timestamp: 0
2026
+ };
2027
+ }
2028
+ /** 把工具声明转成 pi-ai 的形状;没有任何工具时整个字段省略。 */
2029
+ function toolsOf(options) {
2030
+ if (options.tools === void 0 || options.tools.length === 0) return;
2031
+ if (options.tools.some((tool) => tool.deferLoading === true)) throw new LlmError("dsh-aperture: 不支持延迟加载的工具声明", "UNSUPPORTED_CONTENT");
2032
+ return options.tools.map((tool) => ({
2033
+ name: tool.name,
2034
+ description: tool.description,
2035
+ parameters: tool.parameters
2036
+ }));
2037
+ }
2038
+ /**
2039
+ * 转换一条 user/tool 消息的内容。
2040
+ *
2041
+ * 全是文本时给字符串——这是 pi-ai 侧最省事的形状,也让「一条只有文本的用户消息」在请求体里
2042
+ * 与手写的 OpenAI 请求看起来一样。
2043
+ */
2044
+ function userContent(content, requestImages) {
2045
+ const converted = [];
2046
+ for (const block of content) {
2047
+ if (block.type === "text") {
2048
+ if (block.text.length > 0) converted.push({
2049
+ type: "text",
2050
+ text: block.text
2051
+ });
2052
+ continue;
2053
+ }
2054
+ if (block.type !== "image") continue;
2055
+ const version = requestImages?.get(block.attachment.attachmentId);
2056
+ if (version === void 0) throw new LlmError("dsh-aperture: 这条请求带图片,但没有可用的附件服务来转换它们", "UNSUPPORTED_CONTENT");
2057
+ converted.push({
2058
+ type: "text",
2059
+ text: requestImageHandleText(block.attachment, version)
2060
+ });
2061
+ converted.push({
2062
+ type: "image",
2063
+ data: Buffer.from(version.data).toString("base64"),
2064
+ mimeType: version.mediaType
2065
+ });
2066
+ }
2067
+ if (converted.every((block) => block.type === "text")) return converted.map((block) => block.text).join("");
2068
+ return converted;
2069
+ }
2070
+ /** 收集并转换本次请求用到的所有图片。 */
2071
+ async function prepareRequestImages(messages, images) {
2072
+ const refs = /* @__PURE__ */ new Map();
2073
+ for (const message of messages) for (const block of message.content) {
2074
+ if (block.type !== "image") continue;
2075
+ if (block.offloaded === true) continue;
2076
+ refs.set(block.attachment.attachmentId, block.attachment);
2077
+ }
2078
+ const ordered = [...refs.values()];
2079
+ const prepared = await Promise.all(ordered.map((ref) => images.attachments.readImageRequest(ref, requestImageTarget(ref), images.signal)));
2080
+ const versions = /* @__PURE__ */ new Map();
2081
+ for (const [index, ref] of ordered.entries()) versions.set(ref.attachmentId, prepared[index]);
2082
+ return versions;
2083
+ }
2084
+ /** 一张图片在本次请求里的目标尺寸。 */
2085
+ function requestImageTarget(ref) {
2086
+ return {
2087
+ ...requestImageDimensions(ref.width, ref.height, REQUEST_IMAGE_POLICY.maxPixels),
2088
+ maxBytes: REQUEST_IMAGE_POLICY.maxBytes
2089
+ };
2090
+ }
2091
+ /**
2092
+ * 转换一条 assistant 历史消息。
2093
+ *
2094
+ * 原生重放元数据(Anthropic 的 thinking 签名、OpenAI Responses 的 message id 与 reasoning
2095
+ * item)只在本适配器自己生产、且路由与模型都对得上时才回填。版本更早的部署把同一条路由交给
2096
+ * `llm-pi-ai` 服务过,它的重放信封在这里读不出来——那时整条消息降级为 provider 中立的内容:
2097
+ * 思考块丢掉(没有签名的思考块会被 Anthropic 拒绝),文本与工具调用照旧。
2098
+ */
2099
+ function toPiAssistant(message, onDegrade) {
2100
+ const replay = readReplayState(message.source.replayState);
2101
+ if (replay === void 0 && message.source.replayState !== void 0) onDegrade?.("重放元数据不可用");
2102
+ const blocks = replay?.blocks;
2103
+ const content = [];
2104
+ let index = 0;
2105
+ for (const block of message.content) {
2106
+ const signature = blocks?.[index];
2107
+ index += 1;
2108
+ if (block.type === "text") {
2109
+ content.push({
2110
+ type: "text",
2111
+ text: block.text,
2112
+ ...signature?.textSignature === void 0 ? {} : { textSignature: signature.textSignature }
2113
+ });
2114
+ continue;
2115
+ }
2116
+ if (block.type === "reasoning") {
2117
+ if (replay === void 0 || !hasThinkingSignature(signature)) continue;
2118
+ content.push({
2119
+ type: "thinking",
2120
+ thinking: block.text,
2121
+ ...signature.thinkingSignature === void 0 ? {} : { thinkingSignature: signature.thinkingSignature },
2122
+ ...signature.redacted === void 0 ? {} : { redacted: signature.redacted }
2123
+ });
2124
+ continue;
2125
+ }
2126
+ if (block.type === "tool-call") content.push({
2127
+ type: "toolCall",
2128
+ id: block.id,
2129
+ name: block.name,
2130
+ arguments: parseArguments(block.arguments),
2131
+ ...signature?.thoughtSignature === void 0 ? {} : { thoughtSignature: signature.thoughtSignature },
2132
+ ...signature?.namespace === void 0 ? {} : { namespace: signature.namespace }
2133
+ });
2134
+ }
2135
+ return {
2136
+ role: "assistant",
2137
+ content,
2138
+ api: replay?.response.api ?? "dsh-foreign",
2139
+ provider: replay?.response.provider ?? "dsh-foreign",
2140
+ model: replay?.response.model ?? message.source.model,
2141
+ ...replay?.response.responseId === void 0 ? {} : { responseId: replay.response.responseId },
2142
+ ...replay?.response.responseModel === void 0 ? {} : { responseModel: replay.response.responseModel },
2143
+ ...replay?.response.providerThinkingLevel === void 0 ? {} : { providerThinkingLevel: replay.response.providerThinkingLevel },
2144
+ usage: ZERO_USAGE,
2145
+ stopReason: content.some((block) => block.type === "toolCall") ? "toolUse" : "stop",
2146
+ timestamp: 0
2147
+ };
2148
+ }
2149
+ /** 一个块是否带着可回填的思考签名。 */
2150
+ function hasThinkingSignature(block) {
2151
+ return block?.thinkingSignature !== void 0 || block?.redacted === true;
2152
+ }
2153
+ /**
2154
+ * 工具参数是裸 JSON 字符串;pi-ai 的历史消息里要的是对象。
2155
+ *
2156
+ * 解析不了就抛:这条历史是模型自己产出的,解析不了说明记录被改过,静默替换成 `{}` 会把一次
2157
+ * 工具调用悄悄改成另一次。
2158
+ */
2159
+ function parseArguments(raw) {
2160
+ if (raw.trim().length === 0) return {};
2161
+ try {
2162
+ const parsed = JSON.parse(raw);
2163
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
2164
+ } catch (error) {
2165
+ throw new LlmError(`dsh-aperture: 历史里的工具参数不是合法 JSON:${error instanceof Error ? error.message : String(error)}`, "INVALID_REPLAY_STATE");
2166
+ }
2167
+ }
2168
+ /** 历史消息里的用量不参与任何计价,一律清零。 */
2169
+ const ZERO_USAGE = {
2170
+ input: 0,
2171
+ output: 0,
2172
+ cacheRead: 0,
2173
+ cacheWrite: 0,
2174
+ totalTokens: 0,
2175
+ cost: {
2176
+ input: 0,
2177
+ output: 0,
2178
+ cacheRead: 0,
2179
+ cacheWrite: 0,
2180
+ total: 0
2181
+ }
2182
+ };
2183
+ /** 三种协议各自的 pi-ai 实现。 */
2184
+ const PROTOCOLS = {
2185
+ "openai-completions": openAICompletionsApi,
2186
+ "openai-responses": openAIResponsesApi,
2187
+ "anthropic-messages": anthropicMessagesApi
2188
+ };
2189
+ /** 取一种协议的实现。 */
2190
+ function protocolApi(protocol) {
2191
+ return PROTOCOLS[protocol]();
2192
+ }
2193
+ /** 历史消息里的用量不参与任何计价。 */
2194
+ const ZERO_COST = {
2195
+ input: 0,
2196
+ output: 0,
2197
+ cacheRead: 0,
2198
+ cacheWrite: 0
2199
+ };
2200
+ /**
2201
+ * 把一条已发布的模型变成 pi-ai 的 `Model`。
2202
+ *
2203
+ * @param provider - provider 路由键。
2204
+ * @param route - 该路由的协议与地址。
2205
+ * @param model - 已发布的模型。
2206
+ * @returns pi-ai 的模型描述符。
2207
+ */
2208
+ function buildModel(provider, route, model) {
2209
+ return {
2210
+ id: model.id,
2211
+ name: model.name,
2212
+ api: route.protocol,
2213
+ provider,
2214
+ baseUrl: route.baseURL,
2215
+ input: [...model.input],
2216
+ cost: { ...ZERO_COST },
2217
+ contextWindow: model.contextWindow ?? 128e3,
2218
+ maxTokens: model.maxTokens ?? 32768,
2219
+ ...reasoningOf(model.reasoningEfforts),
2220
+ ...model.compat === void 0 ? {} : { compat: model.compat }
2221
+ };
2222
+ }
2223
+ /**
2224
+ * 推理档位 → pi-ai 的 `reasoning` 与 `thinkingLevelMap`。
2225
+ *
2226
+ * 未声明的档位一律**显式钉成不支持**:pi-ai 自己的缺省是不对称的——五个基础档位缺键即视为
2227
+ * 支持,`xhigh` 与 `max` 缺键则视为不支持——而写下这份字典的人只该声明它支持的档位,不该
2228
+ * 需要知道这条规则。唯一例外是「声明了 `off` 却没有线缆写法」:它留在表外,pi-ai 读作
2229
+ * 「支持,但什么都不发」,这正是「不思考」在该协议上的表示。
2230
+ *
2231
+ * @param efforts - 配置里声明的档位;未声明表示该模型不提供任何档位。
2232
+ * @returns pi-ai 模型的推理字段。
2233
+ */
2234
+ function reasoningOf(efforts) {
2235
+ if (efforts === void 0) return { reasoning: false };
2236
+ const map = {};
2237
+ for (const level of REASONING_LEVELS) {
2238
+ const wire = efforts[level];
2239
+ if (wire === void 0) {
2240
+ map[level] = null;
2241
+ continue;
2242
+ }
2243
+ if (wire !== null) map[level] = wire;
2244
+ }
2245
+ return {
2246
+ reasoning: true,
2247
+ thinkingLevelMap: map
2248
+ };
2249
+ }
2250
+ /**
2251
+ * 一个模型可选的全部推理档位。
2252
+ *
2253
+ * 与 pi-ai 的 `getSupportedThinkingLevels` 同义,就地实现是为了不从聚合入口取值:那个入口会
2254
+ * 连带载入本插件用不到的目录与 provider 实现。
2255
+ *
2256
+ * @param model - pi-ai 的模型描述符。
2257
+ * @returns 按升序排列的档位。
2258
+ */
2259
+ function supportedEfforts(model) {
2260
+ if (!model.reasoning) return ["off"];
2261
+ return REASONING_LEVELS.filter((level) => {
2262
+ const mapped = model.thinkingLevelMap?.[level];
2263
+ if (mapped === null) return false;
2264
+ if (level === "xhigh" || level === "max") return mapped !== void 0;
2265
+ return true;
2266
+ });
2267
+ }
2268
+ /**
2269
+ * 宿主选中的推理档位 → pi-ai 的 `reasoning` 选项。
2270
+ *
2271
+ * 调用方**必须先**用 {@link supportedEfforts} 验证过档位;这里只负责最后的映射:`off` 与
2272
+ * 未指定都在协议上等同「不带上思考参数」。
2273
+ *
2274
+ * @param effort - 已通过验证的档位 id。
2275
+ * @returns pi-ai 的档位,或 `undefined`。
2276
+ */
2277
+ function effortOption(effort) {
2278
+ if (effort === void 0 || effort === "off") return void 0;
2279
+ return effort;
2280
+ }
2281
+ //#endregion
2282
+ //#region src/adapter/stream.ts
2283
+ /**
2284
+ * 流式转换:pi-ai 的助手事件 → 宿主的 `StreamChunk`。
2285
+ *
2286
+ * 两处形状差异塑造了本模块。其一,pi-ai 的工具参数在流里以**原始 JSON 片段**出现、在结束时
2287
+ * 给出解析好的对象,而宿主的协议要求参数自始至终是字符串;本模块只转发片段,并在块结束时
2288
+ * 把对象重新串化。其二,pi-ai 把失败当作**流里的终态事件**(不抛),而宿主的协议有两条合法
2289
+ * 错误路径:抛,或者发一个 `finish{kind:'error'|'aborted'}`。这里全部走后者,于是调用方看到的
2290
+ * 永远是一条以 `usage` 与 `finish` 收尾的流。
2291
+ *
2292
+ * @module dsh-aperture/adapter/stream
2293
+ */
2294
+ /**
2295
+ * 把一条 pi-ai 事件流翻成宿主的块序列。
2296
+ *
2297
+ * @param events - 一次助手回合的 pi-ai 事件流。
2298
+ * @param conversion - 路由、模型与容量事实。
2299
+ * @returns 块序列;以 `usage` 与 `finish` 收尾。
2300
+ * @throws LlmError 事件流在没有终态事件的情况下结束(`STREAM_CLOSED`)。
2301
+ */
2302
+ async function* toStreamChunks(events, conversion) {
2303
+ const toolCalls = /* @__PURE__ */ new Map();
2304
+ const slots = [];
2305
+ for await (const event of events) switch (event.type) {
2306
+ case "start": break;
2307
+ case "text_start":
2308
+ slots.push(event.contentIndex);
2309
+ yield {
2310
+ type: "block-start",
2311
+ index: event.contentIndex,
2312
+ blockType: "text"
2313
+ };
2314
+ break;
2315
+ case "text_delta":
2316
+ yield {
2317
+ type: "text-delta",
2318
+ index: event.contentIndex,
2319
+ text: event.delta
2320
+ };
2321
+ break;
2322
+ case "text_end":
2323
+ yield {
2324
+ type: "block-end",
2325
+ index: event.contentIndex,
2326
+ block: {
2327
+ type: "text",
2328
+ text: event.content
2329
+ }
2330
+ };
2331
+ break;
2332
+ case "thinking_start":
2333
+ slots.push(event.contentIndex);
2334
+ yield {
2335
+ type: "block-start",
2336
+ index: event.contentIndex,
2337
+ blockType: "reasoning"
2338
+ };
2339
+ break;
2340
+ case "thinking_delta":
2341
+ yield {
2342
+ type: "reasoning-delta",
2343
+ index: event.contentIndex,
2344
+ text: event.delta
2345
+ };
2346
+ break;
2347
+ case "thinking_end":
2348
+ yield {
2349
+ type: "block-end",
2350
+ index: event.contentIndex,
2351
+ block: {
2352
+ type: "reasoning",
2353
+ text: event.content
2354
+ }
2355
+ };
2356
+ break;
2357
+ case "toolcall_start": {
2358
+ const block = event.partial.content[event.contentIndex];
2359
+ toolCalls.set(event.contentIndex, {
2360
+ id: block?.type === "toolCall" ? block.id : "",
2361
+ name: block?.type === "toolCall" ? block.name : ""
2362
+ });
2363
+ slots.push(event.contentIndex);
2364
+ yield {
2365
+ type: "block-start",
2366
+ index: event.contentIndex,
2367
+ blockType: "tool-call"
2368
+ };
2369
+ break;
2370
+ }
2371
+ case "toolcall_delta": {
2372
+ const known = toolCalls.get(event.contentIndex);
2373
+ yield {
2374
+ type: "tool-call-delta",
2375
+ index: event.contentIndex,
2376
+ id: ToolCallId(known?.id ?? ""),
2377
+ ...known === void 0 || known.name.length === 0 ? {} : { name: known.name },
2378
+ argumentsDelta: event.delta
2379
+ };
2380
+ break;
2381
+ }
2382
+ case "toolcall_end":
2383
+ yield {
2384
+ type: "block-end",
2385
+ index: event.contentIndex,
2386
+ block: {
2387
+ type: "tool-call",
2388
+ id: ToolCallId(event.toolCall.id),
2389
+ name: event.toolCall.name,
2390
+ arguments: JSON.stringify(event.toolCall.arguments)
2391
+ }
2392
+ };
2393
+ break;
2394
+ case "done":
2395
+ yield {
2396
+ type: "usage",
2397
+ usage: mapUsage(event.message.usage)
2398
+ };
2399
+ yield {
2400
+ type: "finish",
2401
+ reason: finishReason(event.message, conversion.contextWindow),
2402
+ replayState: toReplayState(event.message, conversion.provider, conversion.model, replayBlocks(event.message, slots))
2403
+ };
2404
+ return;
2405
+ case "error": {
2406
+ const message = conversion.signal?.aborted === true ? {
2407
+ ...event.error,
2408
+ stopReason: "aborted"
2409
+ } : event.error;
2410
+ yield {
2411
+ type: "usage",
2412
+ usage: mapUsage(message.usage)
2413
+ };
2414
+ yield {
2415
+ type: "finish",
2416
+ reason: finishReason(message, conversion.contextWindow)
2417
+ };
2418
+ return;
2419
+ }
2420
+ }
2421
+ throw new LlmError("dsh-aperture: pi-ai 的事件流没有以 done/error 收尾", "STREAM_CLOSED");
2422
+ }
2423
+ /**
2424
+ * 每个已发出块的原生元数据。
2425
+ *
2426
+ * @param message - 终态助手消息。
2427
+ * @param slots - 已发出块的 contentIndex,按首次出现顺序。
2428
+ * @returns 与已发出块一一对应的条目。
2429
+ */
2430
+ function replayBlocks(message, slots) {
2431
+ return slots.map((index) => {
2432
+ const block = message.content[index];
2433
+ if (block === void 0) return {};
2434
+ if (block.type === "text") return block.textSignature === void 0 ? {} : { textSignature: block.textSignature };
2435
+ if (block.type === "thinking") return {
2436
+ ...block.thinkingSignature === void 0 ? {} : { thinkingSignature: block.thinkingSignature },
2437
+ ...block.redacted === void 0 ? {} : { redacted: block.redacted }
2438
+ };
2439
+ if (block.type === "toolCall") return {
2440
+ ...block.thoughtSignature === void 0 ? {} : { thoughtSignature: block.thoughtSignature },
2441
+ ...block.namespace === void 0 ? {} : { namespace: block.namespace }
2442
+ };
2443
+ return {};
2444
+ });
2445
+ }
2446
+ /**
2447
+ * pi-ai 的用量 → 宿主的用量。
2448
+ *
2449
+ * pi-ai 把推理 token 折进 `output`(`reasoning` 只是它的细分),因此这里不重复上报;
2450
+ * 缓存字段在 pi-ai 里恒为数字,而宿主的口径是「只在真的有缓存时出现」。
2451
+ */
2452
+ function mapUsage(usage) {
2453
+ return {
2454
+ inputTokens: usage.input,
2455
+ outputTokens: usage.output,
2456
+ totalTokens: usage.totalTokens,
2457
+ ...usage.cacheRead > 0 ? { cacheReadTokens: usage.cacheRead } : {},
2458
+ ...usage.cacheWrite > 0 ? { cacheWriteTokens: usage.cacheWrite } : {}
2459
+ };
2460
+ }
2461
+ /**
2462
+ * 终态消息 → 宿主的终止原因。
2463
+ *
2464
+ * 先判溢出:pi-ai 既可能在错误文本里说溢出,也可能**成功返回**一个超出容量的请求(部分兼容
2465
+ * 端会静默接受),后者只能靠用量与容量比出来。空回答是错误而不是成功:宿主的上层会把它当作
2466
+ * 可重试的失败,而 `stop` 加上零内容一旦被当成成功,整轮对话会安静地什么都不产生。
2467
+ */
2468
+ function finishReason(message, contextWindow) {
2469
+ if (isContextOverflow(message, contextWindow)) return {
2470
+ kind: "error",
2471
+ failure: {
2472
+ message: message.errorMessage ?? `dsh-aperture: 模型 "${message.model}" 超过上下文容量`,
2473
+ code: CONTEXT_WINDOW_EXCEEDED_CODE
2474
+ }
2475
+ };
2476
+ if (message.stopReason === "error" && message.errorMessage !== void 0 && isContextWindowExceededError(message.errorMessage)) return {
2477
+ kind: "error",
2478
+ failure: {
2479
+ message: message.errorMessage,
2480
+ code: CONTEXT_WINDOW_EXCEEDED_CODE
2481
+ }
2482
+ };
2483
+ switch (message.stopReason) {
2484
+ case "stop":
2485
+ if (message.content.length === 0) return {
2486
+ kind: "error",
2487
+ failure: {
2488
+ message: `dsh-aperture: 模型 "${message.model}" 正常结束却没有产出任何内容`,
2489
+ code: EMPTY_RESPONSE_CODE
2490
+ }
2491
+ };
2492
+ return { kind: "stop" };
2493
+ case "length": return { kind: "max-tokens" };
2494
+ case "toolUse": return { kind: "tool-calls" };
2495
+ case "aborted": return {
2496
+ kind: "aborted",
2497
+ failure: {
2498
+ message: message.errorMessage ?? "dsh-aperture: 流已中止",
2499
+ code: "ABORTED"
2500
+ }
2501
+ };
2502
+ default: {
2503
+ const text = message.errorMessage ?? `dsh-aperture: pi-ai 的流以 "${message.stopReason}" 收尾`;
2504
+ return {
2505
+ kind: "error",
2506
+ failure: {
2507
+ message: text,
2508
+ code: classifyMessage(text)
2509
+ }
2510
+ };
2511
+ }
2512
+ }
2513
+ }
2514
+ /**
2515
+ * 从错误文本里猜一个稳定的机器码。
2516
+ *
2517
+ * pi-ai 的错误路径只有一个字符串(HTTP 状态被拼进文本,没有结构化字段),而宿主的重试策略
2518
+ * 按码判断该不该重试。猜错的代价是重试策略或诊断分类不准,不是请求正确性;无法归类的都落进
2519
+ * `PI_AI_ERROR`。
2520
+ *
2521
+ * @param message - 终态错误文本。
2522
+ * @returns 稳定的机器码。
2523
+ */
2524
+ function classifyMessage(message) {
2525
+ if (/\b(?:401|403)\b/u.test(message)) return "AUTH";
2526
+ if (isQuotaExceededError(message)) return QUOTA_EXCEEDED_CODE;
2527
+ if (/\b429\b|rate.?limit/iu.test(message)) return "RATE_LIMIT";
2528
+ if (/\b413\b|payload too large|request body too large/iu.test(message)) return "INVALID_REQUEST";
2529
+ if (/\b400\b|invalid.?request/iu.test(message)) return "INVALID_REQUEST";
2530
+ if (/\b5\d\d\b/u.test(message)) return "SERVER";
2531
+ if (/\btime(?:d)?\s*out\b|timeout/iu.test(message)) return "TIMEOUT";
2532
+ if (/\b(?:network|connection|socket|fetch)\b|\bECONN[A-Z]+\b/iu.test(message)) return "TRANSPORT";
2533
+ if (/premature close|terminated|other side closed/iu.test(message)) return "TRANSPORT";
2534
+ return "PI_AI_ERROR";
2535
+ }
2536
+ //#endregion
2537
+ //#region src/adapter/index.ts
2538
+ /**
2539
+ * 适配器本体:把本插件声明的路由交给宿主的 LLM 接缝。
2540
+ *
2541
+ * 与官方 `llm-pi-ai` 适配器相比,这里刻意窄:本插件的路由来自一次刷新(发现)而不是一份
2542
+ * 可编辑的 provider 目录,因此不需要 `Models` 集合、目录条目解析与逐 provider 的 auth 解析;
2543
+ * 三种协议各自一个 `ProviderStreams`,模型描述符在快照里造好,一次请求就是「选模型 → 拼头 →
2544
+ * 转换历史 → 交给 pi-ai → 把事件翻回块」。
2545
+ *
2546
+ * **快照**是这里唯一微妙的地方。刷新会换掉整份路由数组,而一次请求在 `prepareCall` 与真正的
2547
+ * `stream` 之间可能跨越一次刷新:若两次各读一次当前路由,就可能把这一代的模型容量配上下一代
2548
+ * 的端点。因此 `prepareCall` 在**任何 await 之前**抓一份快照,并把派发闭包绑在它上面;
2549
+ * `stream` 直接调用时也只读一次。
2550
+ *
2551
+ * @module dsh-aperture/adapter
2552
+ */
2553
+ /**
2554
+ * 一次流式请求允许的空闲时长。
2555
+ *
2556
+ * pi-ai 自己没有任何 SSE 空闲超时(只有 codex 那条 WebSocket 路自己带一个),而「连接建立了、
2557
+ * 对端随后一声不吭」是网关最常见的失败形态。这个值此前由 `llm-pi-ai` 的 profile 缺省提供,
2558
+ * 本插件接过适配器后自己拿住它。
2559
+ */
2560
+ const STREAM_IDLE_TIMEOUT_MS = 3e5;
2561
+ /** 空闲超时的机器码。 */
2562
+ const IDLE_TIMEOUT_CODE = "LLM_STREAM_IDLE_TIMEOUT";
2563
+ /**
2564
+ * 服务本插件声明的那几条路由。
2565
+ *
2566
+ * 一个实例服务三代路由,`replace()` 只换路由集合、不换实例——这正是宿主那条原子替换契约
2567
+ * 想要的形状。
2568
+ */
2569
+ var ApertureAdapter = class extends LlmAdapter {
2570
+ /**
2571
+ * 外部事实。
2572
+ *
2573
+ * 写成显式字段而不是构造函数参数属性:本插件的源码会被宿主的 Loader 直接装载,而 Node 的
2574
+ * 「只剥类型」模式不支持参数属性——那样加载会在解析期就失败(`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`)。
2575
+ */
2576
+ deps;
2577
+ snapshot;
2578
+ constructor(deps) {
2579
+ super();
2580
+ this.deps = deps;
2581
+ }
2582
+ /** {@inheritDoc LlmAdapter.providerInfo} */
2583
+ providerInfo(provider) {
2584
+ return {
2585
+ id: provider,
2586
+ name: this.findRoute(provider)?.provider.displayName ?? provider
2587
+ };
2588
+ }
2589
+ /** {@inheritDoc LlmAdapter.listModels} */
2590
+ async listModels(provider) {
2591
+ const route = this.findRoute(provider);
2592
+ if (route === void 0) return [];
2593
+ return route.provider.models.map((model) => ({
2594
+ provider,
2595
+ id: model.id,
2596
+ name: model.name,
2597
+ inputModalities: [...model.input]
2598
+ }));
2599
+ }
2600
+ /** {@inheritDoc LlmAdapter.resolveModel} */
2601
+ async resolveModel(provider, model) {
2602
+ return this.describe(this.current(), provider, model);
2603
+ }
2604
+ /** {@inheritDoc LlmAdapter.prepareCall} */
2605
+ async prepareCall(provider, model) {
2606
+ const snapshot = this.current();
2607
+ return {
2608
+ model: this.describe(snapshot, provider, model),
2609
+ stream: (options) => this.dispatch(snapshot, options)
2610
+ };
2611
+ }
2612
+ /** {@inheritDoc LlmAdapter.stream} */
2613
+ stream(options) {
2614
+ return this.dispatch(this.current(), options);
2615
+ }
2616
+ /** 描述一条路由上的模型;未服务的模型只回显身份。 */
2617
+ describe(snapshot, provider, model) {
2618
+ const entry = snapshot.entries.get(entryKey(provider, model));
2619
+ if (entry === void 0) return {
2620
+ provider,
2621
+ id: model,
2622
+ name: model
2623
+ };
2624
+ const efforts = supportedEfforts(entry.pi);
2625
+ return {
2626
+ provider,
2627
+ id: model,
2628
+ name: entry.model.name,
2629
+ inputModalities: [...entry.model.input],
2630
+ context: { contextWindow: entry.pi.contextWindow },
2631
+ ...entry.model.maxTokens === void 0 ? {} : { defaultMaxTokens: entry.model.maxTokens },
2632
+ ...entry.model.reasoningEfforts === void 0 ? {} : { reasoning: { efforts: efforts.map((effort) => ({
2633
+ id: ReasoningEffortId(effort),
2634
+ name: effort
2635
+ })) } }
2636
+ };
2637
+ }
2638
+ /** 找到当前这一代里的某条路由。 */
2639
+ findRoute(provider) {
2640
+ return this.deps.routes().find((route) => route.route.id === provider);
2641
+ }
2642
+ /** 取当前这一代;路由数组换了身份才重建。 */
2643
+ current() {
2644
+ const routes = this.deps.routes();
2645
+ if (this.snapshot !== void 0 && this.snapshot.routes === routes) return this.snapshot;
2646
+ const entries = /* @__PURE__ */ new Map();
2647
+ for (const route of routes) for (const model of route.provider.models) entries.set(entryKey(route.route.id, model.id), {
2648
+ route,
2649
+ model,
2650
+ pi: buildModel(route.route.id, route.provider, model)
2651
+ });
2652
+ this.snapshot = {
2653
+ routes,
2654
+ entries
2655
+ };
2656
+ return this.snapshot;
2657
+ }
2658
+ /** 派发一次请求。 */
2659
+ async *dispatch(snapshot, options) {
2660
+ if (options.stop !== void 0) throw new LlmError("dsh-aperture: 不支持 GenerateOptions.stop", "UNSUPPORTED_OPTION");
2661
+ const entry = snapshot.entries.get(entryKey(options.provider, options.model));
2662
+ if (entry === void 0) throw new LlmError(`dsh-aperture: 路由 "${options.provider}" 上没有模型 "${options.model}"`, "UNKNOWN_MODEL");
2663
+ const { route, model, pi } = entry;
2664
+ const effort = options.reasoningEffort;
2665
+ if (effort !== void 0 && !supportedEfforts(pi).includes(effort)) throw new LlmError(`dsh-aperture: 模型 "${options.model}" 不支持推理档位 "${effort}"`, "UNSUPPORTED_REASONING_EFFORT");
2666
+ const apiKey = await this.deps.resolveApiKey(options.provider, route.provider);
2667
+ const consumer = new AbortController();
2668
+ const upstream = options.signal === void 0 ? consumer.signal : AbortSignal.any([options.signal, consumer.signal]);
2669
+ const watchdog = idleWatchdog(upstream, STREAM_IDLE_TIMEOUT_MS, IDLE_TIMEOUT_CODE);
2670
+ try {
2671
+ const containsImage = options.messages.some((message) => contentHasImage(message.content));
2672
+ if (containsImage && !model.input.includes("image")) throw new LlmError(`dsh-aperture: 模型 "${model.id}" 不接受图片输入`, "UNSUPPORTED_CONTENT");
2673
+ const attachments = containsImage ? this.deps.attachments() : void 0;
2674
+ if (containsImage && attachments === void 0) throw new LlmError("dsh-aperture: 图片输入需要可用的附件服务", "UNSUPPORTED_CONTENT");
2675
+ const context = await toPiContext({
2676
+ ...options,
2677
+ signal: watchdog.signal
2678
+ }, attachments === void 0 ? void 0 : {
2679
+ attachments,
2680
+ signal: watchdog.signal
2681
+ }, (reason) => this.deps.logger.debug(`dsh-aperture: 路由 "${options.provider}" 模型 "${options.model}" 的历史降级:${reason}`));
2682
+ const iterator = toStreamChunks(protocolApi(route.provider.protocol).streamSimple(pi, context, {
2683
+ ...apiKey === void 0 ? {} : { apiKey },
2684
+ headers: requestHeaders(route.provider.headers),
2685
+ ...options.temperature === void 0 ? {} : { temperature: options.temperature },
2686
+ ...options.maxTokens === void 0 ? {} : { maxTokens: options.maxTokens },
2687
+ ...effort === void 0 ? {} : { reasoning: effortOption(effort) },
2688
+ signal: watchdog.signal,
2689
+ maxRetries: 0
2690
+ }), {
2691
+ provider: options.provider,
2692
+ model: options.model,
2693
+ contextWindow: pi.contextWindow,
2694
+ signal: options.signal
2695
+ })[Symbol.asyncIterator]();
2696
+ let exhausted = false;
2697
+ try {
2698
+ for (;;) {
2699
+ const next = await watchdog.next(iterator);
2700
+ const timeout = timeoutOf(watchdog.signal, IDLE_TIMEOUT_CODE);
2701
+ if (timeout !== void 0) throw timeout;
2702
+ if (next.done === true) {
2703
+ exhausted = true;
2704
+ return;
2705
+ }
2706
+ yield next.value;
2707
+ }
2708
+ } finally {
2709
+ if (!exhausted) {
2710
+ consumer.abort("dsh-aperture: 消费者停止读取");
2711
+ try {
2712
+ await iterator.return?.(void 0);
2713
+ } catch {}
2714
+ }
2715
+ }
2716
+ } catch (error) {
2717
+ if (timeoutOf(watchdog.signal, IDLE_TIMEOUT_CODE) !== void 0) throw new LlmError(`dsh-aperture: 模型 "${options.model}" 的响应空闲超过 ${STREAM_IDLE_TIMEOUT_MS}ms`, "TIMEOUT", { cause: error });
2718
+ if (options.signal?.aborted === true) throw new LlmError("dsh-aperture: 请求已被调用方中止", "ABORTED", { cause: error });
2719
+ throw error;
2720
+ } finally {
2721
+ consumer.abort("dsh-aperture: 请求结束");
2722
+ watchdog[Symbol.dispose]();
2723
+ }
2724
+ }
2725
+ };
2726
+ /** 一条路由上一个模型的索引键。 */
2727
+ function entryKey(provider, model) {
2728
+ return `${provider}\u0000${model}`;
2729
+ }
2730
+ /**
2731
+ * 一次请求最终发送的头。
2732
+ *
2733
+ * 归因头(`user-agent`)**覆盖**同名配置项而不是被它覆盖:适配器契约要求每一次请求都带上
2734
+ * 归因,而一份把 `user-agent` 写死的配置不该能让它消失。大小写不敏感的去重交给这里,
2735
+ * 因为 HTTP 头名不区分大小写、而对象键区分。
2736
+ *
2737
+ * @param configured - 配置里为这条路由声明的头。
2738
+ * @returns 合并后的头。
2739
+ */
2740
+ function requestHeaders(configured) {
2741
+ const headers = {};
2742
+ for (const [name, value] of Object.entries(configured ?? {})) headers[name] = value;
2743
+ for (const [name, value] of Object.entries(attributionHeaders())) {
2744
+ for (const existing of Object.keys(headers)) if (existing.toLowerCase() === name.toLowerCase()) delete headers[existing];
2745
+ headers[name] = value;
2746
+ }
2747
+ return headers;
2748
+ }
2749
+ //#endregion
2750
+ //#region src/provider.ts
2751
+ /**
2752
+ * 注册阶段:把一代路由交给宿主的 LLM 接缝。
2753
+ *
2754
+ * 本模块**不写任何配置**。更早的版本把自己的路由写进另一个插件的配置段,现在这条能力整块拿掉:
2755
+ * 配置只由用户与官方界面写,本插件只读。代价是遗留写入不会自动消失——它正好占着本插件要用的
2756
+ * 路由键,于是注册被拒。这时本模块不去替用户清理,而是把「哪个键挡住了、去哪删」写进报告,
2757
+ * 界面上直接可读;用户删掉之后下一次 `llm/adapters-updated` 就会把注册补上。
2758
+ *
2759
+ * 注册本身只有两条性质需要照顾:首次注册用 `registerAdapter`(空数组会被拒),之后用句柄的
2760
+ * `replace`,于是刷新不会让请求观察到「路由消失」的空档;注册失败不会把整轮刷新判为失败——
2761
+ * 发现与报告仍然有结果,用户看到的是「哪条路由没上去、为什么」。
2762
+ *
2763
+ * @module dsh-aperture/provider
2764
+ */
2765
+ /**
2766
+ * 本插件的 provider 身份。
2767
+ *
2768
+ * 一个实例跨代复用同一个适配器对象,只替换它的路由集合。
2769
+ */
2770
+ var ApertureProvider = class {
2771
+ adapter;
2772
+ /** 外部事实;显式字段而非参数属性,理由见 `ApertureAdapter`。 */
2773
+ deps;
2774
+ registration;
2775
+ directory;
2776
+ /** 当前这一代适配器服务的路由。 */
2777
+ routes = [];
2778
+ /** 最近一次想要服务的路由键;冲突重试要用它。 */
2779
+ desired = [];
2780
+ /** 最近一次注册被谁挡住了;没有冲突时为 `undefined`。 */
2781
+ blocked;
2782
+ constructor(deps) {
2783
+ this.deps = deps;
2784
+ this.adapter = new ApertureAdapter({
2785
+ routes: () => this.routes,
2786
+ resolveApiKey: (provider, profile) => this.resolveApiKey(provider, profile),
2787
+ attachments: () => this.deps.attachments(),
2788
+ logger: this.deps.logger
2789
+ });
2790
+ }
2791
+ /**
2792
+ * 发布一代方案。
2793
+ *
2794
+ * @param plan - 本次要服务的路由与未被服务的模型。
2795
+ * @returns 发生了什么。
2796
+ */
2797
+ async publish(plan) {
2798
+ this.routes = plan.routes;
2799
+ this.desired = plan.routes.map((route) => route.route.id);
2800
+ this.registerRoutes();
2801
+ this.registerDirectory(plan.routes);
2802
+ return {
2803
+ routes: this.registration === void 0 ? [] : this.desired,
2804
+ ...this.blocked === void 0 ? {} : { reason: this.conflictReason(this.blocked) }
2805
+ };
2806
+ }
2807
+ /**
2808
+ * 冲突之后重试注册。
2809
+ *
2810
+ * 由 `llm/adapters-updated` 触发:挡住本插件的那一方可能刚刚把自己撤下(例如用户照报告删掉了
2811
+ * 遗留配置)。没有冲突时是空操作,因此本插件自己的注册所触发的那次事件不会变成自激循环。
2812
+ *
2813
+ * @returns 这一轮之后是否已注册。
2814
+ */
2815
+ retry() {
2816
+ if (this.blocked === void 0) return this.registration !== void 0;
2817
+ this.registerRoutes();
2818
+ return this.blocked === void 0 && this.registration !== void 0;
2819
+ }
2820
+ /** 撤下本插件的全部注册。 */
2821
+ dispose() {
2822
+ this.registration?.();
2823
+ this.registration = void 0;
2824
+ this.directory?.();
2825
+ this.directory = void 0;
2826
+ }
2827
+ /** 首次注册或原子替换路由。 */
2828
+ registerRoutes() {
2829
+ if (this.desired.length === 0) {
2830
+ if (this.registration !== void 0) this.registration.replace([]);
2831
+ this.blocked = void 0;
2832
+ return;
2833
+ }
2834
+ const taken = new Set(this.deps.llm.listProviders().map((provider) => provider.id));
2835
+ const blocked = this.registration === void 0 ? this.desired.filter((route) => taken.has(route)) : [];
2836
+ if (blocked.length > 0) {
2837
+ this.blocked = blocked;
2838
+ this.deps.logger.warn("dsh-aperture: 路由 %s 已被别的适配器占用;已跳过注册", blocked.join("、"));
2839
+ return;
2840
+ }
2841
+ try {
2842
+ if (this.registration === void 0) this.registration = this.deps.llm.registerAdapter([...this.desired], this.adapter);
2843
+ else this.registration.replace([...this.desired]);
2844
+ this.blocked = void 0;
2845
+ } catch (error) {
2846
+ this.blocked = [...this.desired];
2847
+ this.deps.logger.warn("dsh-aperture: 路由注册失败:%s", error instanceof Error ? error.message : error);
2848
+ }
2849
+ }
2850
+ /**
2851
+ * 声明本插件的路由可以由哪个配置段激活。
2852
+ *
2853
+ * 声明让官方「模型」页把本插件的路由列成行,并读出它们的凭据引用。那个页面只为
2854
+ * `llm-deepseek` 与 `llm-pi-ai` 准备了编辑布局,因此落到本插件的命名空间时会显示「其余字段在
2855
+ * cordis.patch.yml 中」的提示并禁用保存——本插件的配置面是自己的插件页。
2856
+ *
2857
+ * 只声明**真的有模型**的那些路由:一种协议在这个网关上没有模型时,那一行只会是多出来的空行
2858
+ * (该协议下没有任何可选的东西),而它在这里也声明不了任何事实——本插件不写配置。
2859
+ */
2860
+ registerDirectory(routes) {
2861
+ if (routes.length === 0) {
2862
+ this.directory?.replace([]);
2863
+ return;
2864
+ }
2865
+ const entries = routes.map((route) => ({
2866
+ provider: route.route.id,
2867
+ displayName: route.provider.displayName,
2868
+ settingsNs: APERTURE_NAMESPACE,
2869
+ settingsPath: [],
2870
+ declared: true
2871
+ }));
2872
+ try {
2873
+ if (this.directory === void 0) this.directory = this.deps.llm.registerConfigurableProviders(entries);
2874
+ else this.directory.replace(entries);
2875
+ } catch (error) {
2876
+ this.deps.logger.warn("dsh-aperture: provider 目录注册失败:%s", error instanceof Error ? error.message : error);
2877
+ }
2878
+ }
2879
+ /** 给用户看的冲突说明:点名被占用的键,并说清要手工做什么。 */
2880
+ conflictReason(blocked) {
2881
+ return `路由 ${blocked.join("、")} 已被另一个适配器注册;本插件不写配置,请手工处理:旧版本曾把本插件的路由写进 llm-pi-ai.providers,删掉那里的 ${blocked.join(" / ")} 键即可;若那个路由名是别的插件在用的,请把本插件配置里的 routePrefix 改成另一个名字(三条路由键一起变)。`;
2882
+ }
2883
+ /**
2884
+ * 解析一条路由的凭据。
2885
+ *
2886
+ * 配置了 `apiKeyEnv` 就**必须**解析出可用的值:那是一个明确的声明,悄悄退回占位凭据会让
2887
+ * 一次配错了密钥的部署看起来像一次网关拒绝。
2888
+ */
2889
+ async resolveApiKey(provider, route) {
2890
+ const ref = route.apiKeyEnv;
2891
+ if (ref === void 0) return void 0;
2892
+ const credentials = this.deps.credentials();
2893
+ const resolved = credentials === void 0 ? process.env[ref] : (await credentials.resolve(credentialRef(ref)))?.value;
2894
+ if (resolved !== void 0 && resolved.length > 0) return assertUsableApiKey(resolved, "dsh-aperture", ref);
2895
+ throw new LlmError(`dsh-aperture: 路由 "${provider}" 的 apiKeyEnv 指向 ${ref},但它没有值;请通过凭据服务存入 ${ref}(模型页可写入),或在启动环境里导出它`, "MISSING_CREDENTIAL");
2896
+ }
2897
+ };
2898
+ //#endregion
1878
2899
  //#region src/relay.ts
1879
2900
  /** 邮箱本身在模块求值时就建好,因此不在任何事务里。 */
1880
2901
  const mailbox = {
@@ -2016,33 +3037,43 @@ var AperturePanelService = class extends TypertRemoteService {
2016
3037
  /** 出现在加载器诊断里的插件名。 */
2017
3038
  const name = "dsh-aperture";
2018
3039
  /**
2019
- * settings 是必需依赖:把发现的模型清单发布进 `llm-pi-ai` **就是**本插件的职责,而同一次
2020
- * 注册又让插件自己的 `aperture` 段变得可编辑。声明它意味着框架会把插件挂在 PENDING 直到
2021
- * settings 就绪,provider 被替换时卸载插件、恢复后重新加载——而不是留下一个已加载却无处
2022
- * 发布的实例。
3040
+ * `settings` 是必需依赖:发现报告与配置页都要读它,而插件自己的 `aperture` 段也要由它变成
3041
+ * 可编辑的。`llm` 同样必需:本插件的产出就是那几条 provider 路由,没有 LLM 接缝就没有地方
3042
+ * 可以注册——走到这里却注册不了,用户只会看到模型莫名其妙地不见了。
2023
3043
  *
2024
3044
  * `typert` 则刻意**不**声明:配置页只是顺手提供的便利,没有它的部署(例如 headless profile)
2025
- * 也该照样获得发现能力,因此它在下面按需注入,不在就安静跳过。
3045
+ * 也该照样获得路由,因此它在下面按需注入,不在就安静跳过。
2026
3046
  */
2027
- const inject = ["settings"];
3047
+ const inject = ["settings", "llm"];
2028
3048
  /**
2029
- * 发布网关的模型清单:现在发布,之后有任何变化也发布。
3049
+ * 把网关的模型清单注册成自己的 provider 路由:现在注册,之后有任何变化也重新注册。
2030
3050
  *
2031
- * @param ctx - 插件上下文,其中 `settings` 已就绪。
3051
+ * @param ctx - 插件上下文,其中 `settings` 与 `llm` 已就绪。
2032
3052
  * @param config - 组合层的 `aperture` 段,已按 `Config` schema 校验并带上默认值;根级 volatile
2033
3053
  * 使它成为活引用,读值走 `config.get()`。
2034
- * @throws Error 当配置自身矛盾(路由键不合文法、模型覆盖重复或无法服务),或存储的 `aperture`
2035
- * 段非法时抛出——框架的失败路径正是“坏配置要响亮”的实现方式。
3054
+ * @throws Error 当配置自身矛盾(路由键不合文法、推理档位非法、模型覆盖重复或无法服务)时抛出
3055
+ * ——框架的失败路径正是「坏配置要响亮」的实现方式。
2036
3056
  */
2037
3057
  function apply(ctx, config) {
2038
3058
  const logger = ctx.logger;
2039
3059
  const catalog = new ModelCatalog();
2040
3060
  const readConfig = memoizedConfig(() => configValue(config));
3061
+ const provider = new ApertureProvider({
3062
+ llm: ctx.llm,
3063
+ credentials: () => ctx.get("credentials"),
3064
+ attachments: () => ctx.get("attachments"),
3065
+ logger
3066
+ });
3067
+ ctx.effect(() => () => provider.dispose(), "aperture provider registration");
2041
3068
  const runtime = new ApertureRuntime({
2042
3069
  config: readConfig,
2043
3070
  settings: ctx.settings,
2044
3071
  logger,
2045
- catalog
3072
+ catalog,
3073
+ provider
3074
+ });
3075
+ ctx.on("llm/adapters-updated", () => {
3076
+ if (provider.retry()) logger.info("dsh-aperture: 路由注册的冲突已解除,本插件的路由已就绪");
2046
3077
  });
2047
3078
  let timer;
2048
3079
  const armInterval = () => {
@@ -2084,4 +3115,4 @@ function apply(ctx, config) {
2084
3115
  });
2085
3116
  }
2086
3117
  //#endregion
2087
- export { APERTURE_NAMESPACE, AperturePanelService, Config, DEFAULT_CONTEXT_WINDOW, DEFAULT_MODEL_METADATA_URL, DEFAULT_PLACEHOLDER_CREDENTIAL, ModelCatalog, PANEL_CONTRIBUTION, PANEL_INVOCATIONS, PANEL_NAMESPACE, PANEL_PACKAGE, PI_AI_NAMESPACE, apply, applySync, buildModelsEndpoint, buildProfilePlan, buildRegistry, buildReport, buildRouteBaseUrl, classifyProtocol, configValue, createPanelOps, fetchModelsListing, inject, isDeepSeekFamily, name, normalizeBaseUrl, planSync, resolveConfig };
3118
+ export { APERTURE_NAMESPACE, AperturePanelService, ApertureProvider, ApertureRuntime, Config, DEFAULT_CONTEXT_WINDOW, DEFAULT_MODEL_METADATA_URL, DEFAULT_PLACEHOLDER_CREDENTIAL, ModelCatalog, PANEL_CONTRIBUTION, PANEL_INVOCATIONS, PANEL_NAMESPACE, PANEL_PACKAGE, apply, buildModelsEndpoint, buildRegistry, buildReport, buildRouteBaseUrl, classifyProtocol, configValue, createPanelOps, fetchModelsListing, inject, isDeepSeekFamily, name, normalizeBaseUrl, planRoutes, resolveConfig, resolveRoutes };