dsh-aperture 0.3.1 → 0.3.3

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.
Files changed (51) hide show
  1. package/README.en.md +11 -10
  2. package/README.md +11 -10
  3. package/lib/client.js +1463 -0
  4. package/lib/client.js.map +1 -0
  5. package/lib/index.js +2084 -131
  6. package/lib/{aperture.d.ts → types/aperture.d.ts} +12 -10
  7. package/lib/types/catalog.d.ts +25 -0
  8. package/lib/types/config.d.ts +204 -0
  9. package/lib/types/index.d.ts +37 -0
  10. package/lib/{metadata → types/metadata}/extract.d.ts +15 -24
  11. package/lib/types/metadata/modelsdev.d.ts +40 -0
  12. package/lib/{metadata → types/metadata}/utils.d.ts +2 -0
  13. package/lib/types/panel.d.ts +71 -0
  14. package/lib/types/profile.d.ts +55 -0
  15. package/lib/types/registry.d.ts +31 -0
  16. package/lib/{relay.d.ts → types/relay.d.ts} +2 -0
  17. package/lib/types/remote.d.ts +54 -0
  18. package/lib/types/report.d.ts +115 -0
  19. package/lib/types/runtime.d.ts +87 -0
  20. package/lib/{sync.d.ts → types/sync.d.ts} +12 -23
  21. package/lib/types/types.d.ts +118 -0
  22. package/lib/{url.d.ts → types/url.d.ts} +5 -3
  23. package/package.json +44 -22
  24. package/client/aperture.js +0 -1566
  25. package/lib/aperture.js +0 -107
  26. package/lib/catalog.d.ts +0 -35
  27. package/lib/catalog.js +0 -74
  28. package/lib/config.d.ts +0 -214
  29. package/lib/config.js +0 -168
  30. package/lib/index.d.ts +0 -70
  31. package/lib/metadata/extract.js +0 -217
  32. package/lib/metadata/modelsdev.d.ts +0 -53
  33. package/lib/metadata/modelsdev.js +0 -302
  34. package/lib/metadata/utils.js +0 -86
  35. package/lib/panel.d.ts +0 -86
  36. package/lib/panel.js +0 -263
  37. package/lib/profile.d.ts +0 -62
  38. package/lib/profile.js +0 -158
  39. package/lib/registry.d.ts +0 -48
  40. package/lib/registry.js +0 -234
  41. package/lib/relay.js +0 -63
  42. package/lib/remote.d.ts +0 -64
  43. package/lib/remote.js +0 -96
  44. package/lib/report.d.ts +0 -123
  45. package/lib/report.js +0 -109
  46. package/lib/runtime.d.ts +0 -97
  47. package/lib/runtime.js +0 -194
  48. package/lib/sync.js +0 -176
  49. package/lib/types.d.ts +0 -116
  50. package/lib/types.js +0 -10
  51. package/lib/url.js +0 -67
package/lib/aperture.js DELETED
@@ -1,107 +0,0 @@
1
- /**
2
- * 端点问询:`GET {instance}/v1/models`。
3
- *
4
- * 这是插件为发现过程发出的唯一网络调用。它与 `dsh-llm-pi-ai` 自己的 "fetch available
5
- * models" 动作读的是同一个端点——区别在于那个动作一次只采纳一份草稿,而本插件才是让
6
- * 清单自行刷新的东西。
7
- *
8
- * @module dsh-aperture/aperture
9
- */
10
- import { asRecord } from "./metadata/utils.js";
11
- import { buildModelsEndpoint } from "./url.js";
12
- /** 有界读取:远超此值的模型清单不是模型清单。 */
13
- const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
14
- /**
15
- * 问询一个 Aperture 实例,获取它服务的模型。
16
- *
17
- * @param instanceRoot - 一个已归一化的实例根。
18
- * @param options - 请求头、超时与调用方取消信号。
19
- * @returns 按端点顺序排列的原始条目。
20
- * @throws 当请求失败、端点拒绝、应答过大,或响应体不是模型清单时,抛出带端点名的 Error。
21
- */
22
- export async function fetchModelsListing(instanceRoot, options = {}) {
23
- const endpoint = buildModelsEndpoint(instanceRoot);
24
- const timeoutMs = options.timeoutMs ?? 20_000;
25
- const timeout = AbortSignal.timeout(timeoutMs);
26
- const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout]);
27
- let response;
28
- try {
29
- response = await fetch(endpoint, {
30
- method: 'GET',
31
- headers: {
32
- accept: 'application/json',
33
- ...options.headers,
34
- },
35
- signal,
36
- });
37
- }
38
- catch (error) {
39
- throw new Error(`${endpoint} 无法访问:${describeError(error)}`, { cause: error });
40
- }
41
- if (!response.ok) {
42
- const detail = await readErrorDetail(response);
43
- throw new Error(`${endpoint} 应答 HTTP ${response.status}${detail === undefined ? '' : `: ${detail}`}`);
44
- }
45
- const declaredLength = Number(response.headers.get('content-length') ?? '');
46
- if (Number.isFinite(declaredLength) && declaredLength > MAX_RESPONSE_BYTES) {
47
- throw new Error(`${endpoint} 应答了 ${declaredLength} 字节,超出 ${MAX_RESPONSE_BYTES} 字节的清单上限`);
48
- }
49
- const text = await response.text();
50
- if (text.length > MAX_RESPONSE_BYTES) {
51
- throw new Error(`${endpoint} 应答了 ${text.length} 字节,超出 ${MAX_RESPONSE_BYTES} 字节的清单上限`);
52
- }
53
- let body;
54
- try {
55
- body = JSON.parse(text);
56
- }
57
- catch (error) {
58
- throw new Error(`${endpoint} 没有应答 JSON:${describeError(error)}`, { cause: error });
59
- }
60
- return { entries: readEntries(body, endpoint), endpoint };
61
- }
62
- /**
63
- * 从清单响应体中读取出模型行。
64
- *
65
- * 存在 `data` 数组时以它为准;否则读取 `models` 对象,且只有值为对象的属性才算模型。
66
- * 其他形状一律拒绝而不是当作空清单——空清单会覆盖掉一份可用的清单。
67
- *
68
- * @param body - 已解析的响应。
69
- * @param endpoint - 应答的 URL,用于诊断。
70
- * @returns 按端点顺序排列的原始模型行。
71
- * @throws 当响应体不是可识别的清单时抛出 Error。
72
- */
73
- export function readEntries(body, endpoint) {
74
- const record = asRecord(body);
75
- if (!record) {
76
- throw new Error(`${endpoint} 没有应答 JSON 对象`);
77
- }
78
- if (Array.isArray(record.data)) {
79
- return record.data;
80
- }
81
- const models = asRecord(record.models);
82
- if (models) {
83
- return Object.values(models).filter((value) => asRecord(value) !== undefined);
84
- }
85
- throw new Error(`${endpoint} 既没有应答 "data" 数组,也没有应答 "models" 对象`);
86
- }
87
- /** 读取错误响应体的一小段,用于诊断。 */
88
- async function readErrorDetail(response) {
89
- try {
90
- const text = await response.text();
91
- const trimmed = text.trim();
92
- return trimmed.length === 0 ? undefined : trimmed.slice(0, 500);
93
- }
94
- catch {
95
- return undefined;
96
- }
97
- }
98
- /** 把一个未知的可抛出对象渲染成单行原因。 */
99
- function describeError(error) {
100
- if (error instanceof Error) {
101
- const cause = error.cause;
102
- return cause instanceof Error && cause.message !== error.message
103
- ? `${error.message} (${cause.message})`
104
- : error.message;
105
- }
106
- return String(error);
107
- }
package/lib/catalog.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * 可选的第二来源:models.dev。
3
- *
4
- * Aperture 会设定模型的容量,但很少说明某个模型是否会推理,对输入模态则完全不
5
- * 提。models.dev 会为同一批模型回答这两个问题,只是 id 有时才对得上,因此该文档
6
- * 只索引一次,之后按评分查询(见 `metadata/modelsdev.ts`)。
7
- *
8
- * 这次抓取在任何意义上都是可选的:把 `modelMetadataUrl` 留空的部署,或者清单不
9
- * 可达的部署,得到的是仅来自网关的清单,而不是一次失败的刷新。
10
- *
11
- * @module dsh-aperture/catalog
12
- */
13
- import type { CatalogLookup } from './types.ts';
14
- /** 一次清单加载的结果,用于诊断报告。 */
15
- export interface CatalogLoad {
16
- /** 查找器,在加载到可用文档时提供。 */
17
- readonly lookup?: CatalogLookup;
18
- /** 已索引条目的数量,在加载成功时提供。 */
19
- readonly entries: number;
20
- /** 没有可用查找器的原因,在不可用时提供。 */
21
- readonly reason?: string;
22
- }
23
- /** 一个清单 URL 的进程生命周期缓存。 */
24
- export declare class ModelCatalog {
25
- private loaded;
26
- /**
27
- * 加载(或复用)某个 URL 上的清单。
28
- * @param url - 清单 URL;为空则禁用查找。
29
- * @param timeoutMs - 每次请求的超时时间。
30
- * @returns 加载结果;从不抛出。
31
- */
32
- load(url: string, timeoutMs: number): Promise<CatalogLoad>;
33
- /** 抓取、解析并索引一份清单文档。 */
34
- private fetchCatalog;
35
- }
package/lib/catalog.js DELETED
@@ -1,74 +0,0 @@
1
- /**
2
- * 可选的第二来源:models.dev。
3
- *
4
- * Aperture 会设定模型的容量,但很少说明某个模型是否会推理,对输入模态则完全不
5
- * 提。models.dev 会为同一批模型回答这两个问题,只是 id 有时才对得上,因此该文档
6
- * 只索引一次,之后按评分查询(见 `metadata/modelsdev.ts`)。
7
- *
8
- * 这次抓取在任何意义上都是可选的:把 `modelMetadataUrl` 留空的部署,或者清单不
9
- * 可达的部署,得到的是仅来自网关的清单,而不是一次失败的刷新。
10
- *
11
- * @module dsh-aperture/catalog
12
- */
13
- import { buildCatalogLookup } from "./metadata/modelsdev.js";
14
- /** 有界读取:清单远小于此值,而重定向到巨大的东西则不是清单。 */
15
- const MAX_CATALOG_BYTES = 16 * 1024 * 1024;
16
- /** 一个清单 URL 的进程生命周期缓存。 */
17
- export class ModelCatalog {
18
- loaded;
19
- /**
20
- * 加载(或复用)某个 URL 上的清单。
21
- * @param url - 清单 URL;为空则禁用查找。
22
- * @param timeoutMs - 每次请求的超时时间。
23
- * @returns 加载结果;从不抛出。
24
- */
25
- async load(url, timeoutMs) {
26
- if (url.length === 0) {
27
- return { entries: 0, reason: '未配置清单 URL' };
28
- }
29
- if (this.loaded?.url === url) {
30
- return this.loaded.value;
31
- }
32
- const value = await this.fetchCatalog(url, timeoutMs);
33
- this.loaded = { url, value };
34
- return value;
35
- }
36
- /** 抓取、解析并索引一份清单文档。 */
37
- async fetchCatalog(url, timeoutMs) {
38
- let body;
39
- try {
40
- const response = await fetch(url, {
41
- headers: { accept: 'application/json' },
42
- signal: AbortSignal.timeout(timeoutMs),
43
- });
44
- if (!response.ok) {
45
- return { entries: 0, reason: `${url} 应答 HTTP ${response.status}` };
46
- }
47
- const text = await response.text();
48
- if (text.length > MAX_CATALOG_BYTES) {
49
- return { entries: 0, reason: `${url} 应答了 ${text.length} 字节,超出清单上限` };
50
- }
51
- body = JSON.parse(text);
52
- }
53
- catch (error) {
54
- return { entries: 0, reason: `${url} 无法读取:${error instanceof Error ? error.message : String(error)}` };
55
- }
56
- const lookup = buildCatalogLookup(body);
57
- if (lookup === undefined) {
58
- return { entries: 0, reason: `${url} 中没有可用的模型元数据` };
59
- }
60
- return { lookup, entries: countEntries(body) };
61
- }
62
- }
63
- /** 统计一份清单文档包含的模型条目数,仅用于报告。 */
64
- function countEntries(document) {
65
- if (document === null || typeof document !== 'object') {
66
- return 0;
67
- }
68
- const root = document;
69
- const wrapped = root.providers ?? root.models;
70
- if (wrapped !== null && typeof wrapped === 'object') {
71
- return Object.keys(wrapped).length;
72
- }
73
- return Object.keys(root).length;
74
- }
package/lib/config.d.ts DELETED
@@ -1,214 +0,0 @@
1
- /**
2
- * 配置 schema 与解析。
3
- *
4
- * 本插件拥有自己的 entry(`aperture`,用户层就是 profile patch 里那一行的 `config`),
5
- * 但发布出去的一切都写进**另一个** entry `llm-pi-ai`:本插件决定有哪些模型,那个适配器
6
- * 决定怎么跟它们说话。
7
- *
8
- * 整份 schema 都是 volatile 的:设置接缝**只**暴露 volatile 字段(没有 volatile 节点的
9
- * entry 不出现在 `describe()` 里,界面就无从编辑),而这里每个字段都只影响下一轮发现、
10
- * 没有一项需要重启——于是配置改动被 Loader 当作就地换引用的活更新,插件不重新挂载,
11
- * 正在跑的那轮刷新也不会被掐断。
12
- *
13
- * @module dsh-aperture/config
14
- */
15
- import z from '@deepseek-ai/schemastery';
16
- /** 本插件拥有、并可通过它配置的设置命名空间。 */
17
- export declare const APERTURE_NAMESPACE = "aperture";
18
- /** 默认清单地址;参考实现用的是同一份文档。 */
19
- export declare const DEFAULT_MODEL_METADATA_URL = "https://models.dev/models.json";
20
- /** 当 Aperture 与清单都没给出容量时,为模型假定的上下文容量。 */
21
- export declare const DEFAULT_CONTEXT_WINDOW = 128000;
22
- /** 访问网关与清单的单次请求超时。没有哪个部署需要为此改一次配置。 */
23
- export declare const DEFAULT_TIMEOUT_MS = 20000;
24
- /** 插件配置。 */
25
- export interface Config {
26
- /** Aperture 实例根地址,例如 `https://ai.example.ts.net`。留空则关闭发现。 */
27
- baseUrl?: string;
28
- /** 承载 OpenAI 兼容模型的路由键;Anthropic 那条路由与两者的显示名都从它推出来({@link derivedNames})。 */
29
- route?: string;
30
- /** 按请求解析的凭据引用;留空则改为发布一个占位请求头。 */
31
- apiKeyEnv?: string;
32
- /** 每条路由的请求都会带上的额外请求头;它们优先于占位凭据。 */
33
- headers?: Record<string, string>;
34
- /** 非空时,只发现这些模型 id。 */
35
- enabledModelIds?: string[];
36
- /** 网关模型 id → models.dev 模型 id,用于两边写法不同的 id。 */
37
- modelAliases?: Record<string, string>;
38
- /** 覆盖与追加,按 id 合并。 */
39
- models?: Array<{
40
- id: string;
41
- name?: string;
42
- api?: string;
43
- contextWindow?: number;
44
- maxTokens?: number;
45
- input?: Array<'text' | 'image'>;
46
- thinking?: boolean;
47
- reasoningEfforts?: Record<string, string | null>;
48
- }>;
49
- /** models.dev 清单地址;留空则关闭这次补齐。 */
50
- modelMetadataUrl?: string;
51
- /** `metadata` 接受清单里的输入模态;`ignore` 声明为纯文本。 */
52
- images?: 'ignore' | 'metadata';
53
- /** `auto` 映射模型的推理能力;`off` 声明所有模型都不推理。 */
54
- reasoning?: 'auto' | 'off';
55
- /** 是否把发现的模型清单写进 `llm-pi-ai` 段。 */
56
- sync?: boolean;
57
- /** 自动刷新间隔(分钟);`0` 表示只在加载时与配置变更时刷新。 */
58
- refreshIntervalMinutes?: number;
59
- }
60
- /**
61
- * {@link Config} 的运行时 schema。
62
- *
63
- * 根节点上的 `.volatile()` 让整份配置成为活引用:`apply` 拿到的是 `Ref`,读值走
64
- * `.get()`,每次变更都是对同一引用的 `updateVolatile`。校验与默认值照旧——volatile
65
- * 只改变结果如何被持有。
66
- */
67
- export declare const Config: z<NoInfer<Schemastery.ObjectS<NoInfer<{
68
- baseUrl: z<string, string, "defined">;
69
- route: z<string, string, "defined">;
70
- apiKeyEnv: z<string, string, "defined">;
71
- headers: z<import("@deepseek-ai/cosmokit").Dict<string, string>, import("@deepseek-ai/cosmokit").Dict<string, string>, "defined">;
72
- enabledModelIds: z<string[], string[], "defined">;
73
- modelAliases: z<import("@deepseek-ai/cosmokit").Dict<string, string>, import("@deepseek-ai/cosmokit").Dict<string, string>, "defined">;
74
- models: z<({
75
- id?: string | null | undefined;
76
- name?: string | null | undefined;
77
- api?: string | null | undefined;
78
- contextWindow?: number | null | undefined;
79
- maxTokens?: number | null | undefined;
80
- input?: ("text" | "image")[] | null | undefined;
81
- thinking?: boolean | null | undefined;
82
- reasoningEfforts?: import("@deepseek-ai/cosmokit").Dict<string | null, string> | null | undefined;
83
- } & import("@deepseek-ai/cosmokit").Dict)[], Schemastery.ObjectT<NoInfer<{
84
- /** 模型 id;与已发现的 id 对应,或者新增一个网关没有列出的模型。 */
85
- id: z<string, string, "defined">;
86
- /** 选择器里显示的名字。 */
87
- name: z<string, string, "plain">;
88
- /** 协议覆盖:`openai-completions` 或 `anthropic-messages`。 */
89
- api: z<string, string, "plain">;
90
- /** 上下文容量(token 数)。 */
91
- contextWindow: z<number, number, "plain">;
92
- /** 输出能力(token 数)。 */
93
- maxTokens: z<number, number, "plain">;
94
- /** 请求模态。 */
95
- input: z<("text" | "image")[], ("text" | "image")[], "plain">;
96
- /** 强制打开或关闭推理能力。 */
97
- thinking: z<boolean, boolean, "plain">;
98
- /** 提供的推理档位:键 = 档位,值 = 协议里的写法。 */
99
- reasoningEfforts: z<import("@deepseek-ai/cosmokit").Dict<string | null, string>, import("@deepseek-ai/cosmokit").Dict<string | null, string>, "plain">;
100
- }>>[], "defined">;
101
- modelMetadataUrl: z<string, string, "defined">;
102
- images: z<"ignore" | "metadata", "ignore" | "metadata", "defined">;
103
- reasoning: z<"auto" | "off", "auto" | "off", "defined">;
104
- sync: z<boolean, boolean, "defined">;
105
- refreshIntervalMinutes: z<number, number, "defined">;
106
- }>>>, NoInfer<Schemastery.ObjectT<NoInfer<{
107
- baseUrl: z<string, string, "defined">;
108
- route: z<string, string, "defined">;
109
- apiKeyEnv: z<string, string, "defined">;
110
- headers: z<import("@deepseek-ai/cosmokit").Dict<string, string>, import("@deepseek-ai/cosmokit").Dict<string, string>, "defined">;
111
- enabledModelIds: z<string[], string[], "defined">;
112
- modelAliases: z<import("@deepseek-ai/cosmokit").Dict<string, string>, import("@deepseek-ai/cosmokit").Dict<string, string>, "defined">;
113
- models: z<({
114
- id?: string | null | undefined;
115
- name?: string | null | undefined;
116
- api?: string | null | undefined;
117
- contextWindow?: number | null | undefined;
118
- maxTokens?: number | null | undefined;
119
- input?: ("text" | "image")[] | null | undefined;
120
- thinking?: boolean | null | undefined;
121
- reasoningEfforts?: import("@deepseek-ai/cosmokit").Dict<string | null, string> | null | undefined;
122
- } & import("@deepseek-ai/cosmokit").Dict)[], Schemastery.ObjectT<NoInfer<{
123
- /** 模型 id;与已发现的 id 对应,或者新增一个网关没有列出的模型。 */
124
- id: z<string, string, "defined">;
125
- /** 选择器里显示的名字。 */
126
- name: z<string, string, "plain">;
127
- /** 协议覆盖:`openai-completions` 或 `anthropic-messages`。 */
128
- api: z<string, string, "plain">;
129
- /** 上下文容量(token 数)。 */
130
- contextWindow: z<number, number, "plain">;
131
- /** 输出能力(token 数)。 */
132
- maxTokens: z<number, number, "plain">;
133
- /** 请求模态。 */
134
- input: z<("text" | "image")[], ("text" | "image")[], "plain">;
135
- /** 强制打开或关闭推理能力。 */
136
- thinking: z<boolean, boolean, "plain">;
137
- /** 提供的推理档位:键 = 档位,值 = 协议里的写法。 */
138
- reasoningEfforts: z<import("@deepseek-ai/cosmokit").Dict<string | null, string>, import("@deepseek-ai/cosmokit").Dict<string | null, string>, "plain">;
139
- }>>[], "defined">;
140
- modelMetadataUrl: z<string, string, "defined">;
141
- images: z<"ignore" | "metadata", "ignore" | "metadata", "defined">;
142
- reasoning: z<"auto" | "off", "auto" | "off", "defined">;
143
- sync: z<boolean, boolean, "defined">;
144
- refreshIntervalMinutes: z<number, number, "defined">;
145
- }>>>, "volatile">;
146
- /**
147
- * Loader 交到 `apply` 手里的配置活引用。
148
- *
149
- * `.get()` 返回深冻结快照,且只在值真的变了之后才换引用——这正是 {@link memoizedConfig}
150
- * 与运行时单飞判定所依赖的「配置版本」。
151
- */
152
- export type ConfigRef = ReturnType<typeof Config>;
153
- /**
154
- * 取活引用里的那份普通配置值。
155
- *
156
- * 根级 volatile 只改变配置**怎么被持有**,解析与校验照旧(非法值仍在 `Config(raw)` 当场
157
- * 抛出,默认值也已补齐),所以这里只把活引用读成一份快照,交给不关心「活」的那几层。
158
- *
159
- * @param ref - Loader 交到 `apply` 手里的配置活引用。
160
- * @returns 当前那份深冻结的普通配置值。
161
- */
162
- export declare function configValue(ref: ConfigRef): FilledConfig;
163
- /**
164
- * 默认值补齐之后的配置。
165
- *
166
- * {@link Config} 是**用户可写**的形状(每个键可选);schema 输出的那份不是——每个字段
167
- * 都带 `.default()`。把这个事实写进类型,调用方就不必对着一堆必然存在的字段写 `??`。
168
- */
169
- export type FilledConfig = Required<Config>;
170
- /** 校验过的配置:默认值已全部补齐,根地址已归一化。 */
171
- export interface ResolvedConfig {
172
- /** 归一化后的实例根地址;关闭发现时为 `undefined`。 */
173
- readonly instanceRoot: string | undefined;
174
- /** 原样保留的配置值,供诊断使用。 */
175
- readonly rawBaseUrl: string;
176
- readonly route: string;
177
- readonly anthropicRoute: string;
178
- readonly displayName: string;
179
- readonly anthropicDisplayName: string;
180
- /** 凭据引用;未配置时为 `undefined`。 */
181
- readonly apiKeyEnv: string | undefined;
182
- readonly headers: Readonly<Record<string, string>>;
183
- readonly enabledModelIds: readonly string[];
184
- readonly modelAliases: Readonly<Record<string, string>>;
185
- readonly models: NonNullable<Config['models']>;
186
- readonly modelMetadataUrl: string;
187
- readonly images: 'ignore' | 'metadata';
188
- readonly reasoning: 'auto' | 'off';
189
- readonly sync: boolean;
190
- readonly refreshIntervalMinutes: number;
191
- }
192
- /**
193
- * 解析一段配置,只拒绝那些自身就矛盾的错误。
194
- *
195
- * `baseUrl` 缺失或不可用**不**算错误:插件照常挂载但处于休眠,这样 profile 可以在还没人
196
- * 填地址时就先带着这一行。路由键则必须拒绝——写错的路由键无法靠后续写入补救,插件会静默地
197
- * 什么都不发布。
198
- *
199
- * @param config - 已补齐默认值的 `aperture` 段(`configValue` 的返回值,不是活引用)。
200
- * @returns 校验过的配置。
201
- * @throws Error 当路由键不合文法、或模型覆盖自身重复/无法服务时抛出,并在消息里点名字段。
202
- */
203
- export declare function resolveConfig(config: Config): ResolvedConfig;
204
- /**
205
- * 把「解析当前的配置段」包成一个按源缓存的 thunk。
206
- *
207
- * 配置活引用的 `.get()` 只在值真的变了之后才换快照,没变就还是同一个对象,因此返回值可以
208
- * 直接当**配置版本**用。不缓存的话每次调用都是新对象,运行时的版本判断永远不成立,于是每次
209
- * 刷新都会多排一轮。
210
- *
211
- * @param source - 生效配置段的活引用(每次编辑都就地换掉它的内容)。
212
- * @returns 解析后的配置;源没换时返回同一个对象。
213
- */
214
- export declare function memoizedConfig(source: () => Config): () => ResolvedConfig;
package/lib/config.js DELETED
@@ -1,168 +0,0 @@
1
- /**
2
- * 配置 schema 与解析。
3
- *
4
- * 本插件拥有自己的 entry(`aperture`,用户层就是 profile patch 里那一行的 `config`),
5
- * 但发布出去的一切都写进**另一个** entry `llm-pi-ai`:本插件决定有哪些模型,那个适配器
6
- * 决定怎么跟它们说话。
7
- *
8
- * 整份 schema 都是 volatile 的:设置接缝**只**暴露 volatile 字段(没有 volatile 节点的
9
- * entry 不出现在 `describe()` 里,界面就无从编辑),而这里每个字段都只影响下一轮发现、
10
- * 没有一项需要重启——于是配置改动被 Loader 当作就地换引用的活更新,插件不重新挂载,
11
- * 正在跑的那轮刷新也不会被掐断。
12
- *
13
- * @module dsh-aperture/config
14
- */
15
- import z from '@deepseek-ai/schemastery';
16
- import { normalizeBaseUrl } from "./url.js";
17
- /** 本插件拥有、并可通过它配置的设置命名空间。 */
18
- export const APERTURE_NAMESPACE = 'aperture';
19
- /** 默认清单地址;参考实现用的是同一份文档。 */
20
- export const DEFAULT_MODEL_METADATA_URL = 'https://models.dev/models.json';
21
- /** 当 Aperture 与清单都没给出容量时,为模型假定的上下文容量。 */
22
- export const DEFAULT_CONTEXT_WINDOW = 128_000;
23
- /** 访问网关与清单的单次请求超时。没有哪个部署需要为此改一次配置。 */
24
- export const DEFAULT_TIMEOUT_MS = 20_000;
25
- /** provider 路由键的文法,与 Models 页面自身的规则一致。 */
26
- const ROUTE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
27
- /** 一个配置好的模型:对已发现模型的覆盖,或者一个额外的模型。 */
28
- const modelConfig = z.object({
29
- /** 模型 id;与已发现的 id 对应,或者新增一个网关没有列出的模型。 */
30
- id: z.string().required(),
31
- /** 选择器里显示的名字。 */
32
- name: z.string(),
33
- /** 协议覆盖:`openai-completions` 或 `anthropic-messages`。 */
34
- api: z.string(),
35
- /** 上下文容量(token 数)。 */
36
- contextWindow: z.number().step(1).min(1),
37
- /** 输出能力(token 数)。 */
38
- maxTokens: z.number().step(1).min(1),
39
- /** 请求模态。 */
40
- input: z.array(z.union([z.const('text'), z.const('image')])),
41
- /** 强制打开或关闭推理能力。 */
42
- thinking: z.boolean(),
43
- /** 提供的推理档位:键 = 档位,值 = 协议里的写法。 */
44
- reasoningEfforts: z.dict(z.union([z.string(), z.const(null)])),
45
- });
46
- /**
47
- * {@link Config} 的运行时 schema。
48
- *
49
- * 根节点上的 `.volatile()` 让整份配置成为活引用:`apply` 拿到的是 `Ref`,读值走
50
- * `.get()`,每次变更都是对同一引用的 `updateVolatile`。校验与默认值照旧——volatile
51
- * 只改变结果如何被持有。
52
- */
53
- export const Config = z.object({
54
- baseUrl: z.string().default(''),
55
- route: z.string().default('aperture'),
56
- apiKeyEnv: z.string().default(''),
57
- headers: z.dict(z.string()).default({}),
58
- enabledModelIds: z.array(z.string()).default([]),
59
- modelAliases: z.dict(z.string()).default({}),
60
- models: z.array(modelConfig).default([]),
61
- modelMetadataUrl: z.string().default(DEFAULT_MODEL_METADATA_URL),
62
- images: z.union([z.const('ignore'), z.const('metadata')]).default('ignore'),
63
- reasoning: z.union([z.const('auto'), z.const('off')]).default('auto'),
64
- sync: z.boolean().default(true),
65
- refreshIntervalMinutes: z.number().min(0).max(24 * 60).default(0),
66
- }).volatile();
67
- /**
68
- * 取活引用里的那份普通配置值。
69
- *
70
- * 根级 volatile 只改变配置**怎么被持有**,解析与校验照旧(非法值仍在 `Config(raw)` 当场
71
- * 抛出,默认值也已补齐),所以这里只把活引用读成一份快照,交给不关心「活」的那几层。
72
- *
73
- * @param ref - Loader 交到 `apply` 手里的配置活引用。
74
- * @returns 当前那份深冻结的普通配置值。
75
- */
76
- export function configValue(ref) {
77
- return (ref.get() ?? {});
78
- }
79
- /**
80
- * 从一个路由键推出这一对路由的名字与显示名。
81
- *
82
- * 这三条事实曾经是三个可写字段,但一个部署要换的从来只是前缀:Anthropic 那条加
83
- * `-anthropic` 后缀,显示名是路由键的标题写法(`aperture` → `Aperture`)。让它们互相
84
- * 矛盾因此变成不可能,而不是要校验出来的错误。
85
- *
86
- * @param route - 已经过文法校验的 OpenAI 兼容路由键。
87
- * @returns 三条推导出来的名字。
88
- */
89
- function derivedNames(route) {
90
- const displayName = route
91
- .split('-')
92
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
93
- .join(' ');
94
- return { anthropicRoute: `${route}-anthropic`, displayName, anthropicDisplayName: `${displayName} (Anthropic)` };
95
- }
96
- /**
97
- * 解析一段配置,只拒绝那些自身就矛盾的错误。
98
- *
99
- * `baseUrl` 缺失或不可用**不**算错误:插件照常挂载但处于休眠,这样 profile 可以在还没人
100
- * 填地址时就先带着这一行。路由键则必须拒绝——写错的路由键无法靠后续写入补救,插件会静默地
101
- * 什么都不发布。
102
- *
103
- * @param config - 已补齐默认值的 `aperture` 段(`configValue` 的返回值,不是活引用)。
104
- * @returns 校验过的配置。
105
- * @throws Error 当路由键不合文法、或模型覆盖自身重复/无法服务时抛出,并在消息里点名字段。
106
- */
107
- export function resolveConfig(config) {
108
- const rawBaseUrl = (config.baseUrl ?? '').trim();
109
- const instanceRoot = normalizeBaseUrl(rawBaseUrl);
110
- const route = (config.route ?? '').trim();
111
- if (!ROUTE_PATTERN.test(route)) {
112
- throw new Error(`route "${route}" 必须是小写连字符形式的 provider 路由名(需匹配 ${String(ROUTE_PATTERN)})`);
113
- }
114
- const models = config.models ?? [];
115
- const seen = new Set();
116
- for (const model of models) {
117
- const id = model.id.trim();
118
- if (id.length === 0) {
119
- throw new Error('models[].id 不能为空');
120
- }
121
- if (seen.has(id)) {
122
- throw new Error(`models 里重复列出了 "${id}"`);
123
- }
124
- seen.add(id);
125
- if (model.api !== undefined && model.api !== 'openai-completions' && model.api !== 'anthropic-messages') {
126
- throw new Error(`models["${id}"].api "${model.api}" 无法服务;请使用 openai-completions 或 anthropic-messages`);
127
- }
128
- }
129
- const apiKeyEnv = (config.apiKeyEnv ?? '').trim();
130
- return {
131
- instanceRoot,
132
- rawBaseUrl,
133
- route,
134
- ...derivedNames(route),
135
- apiKeyEnv: apiKeyEnv.length === 0 ? undefined : apiKeyEnv,
136
- headers: config.headers ?? {},
137
- enabledModelIds: config.enabledModelIds ?? [],
138
- modelAliases: config.modelAliases ?? {},
139
- models,
140
- modelMetadataUrl: (config.modelMetadataUrl ?? '').trim(),
141
- images: config.images ?? 'ignore',
142
- reasoning: config.reasoning ?? 'auto',
143
- sync: config.sync ?? true,
144
- refreshIntervalMinutes: config.refreshIntervalMinutes ?? 0,
145
- };
146
- }
147
- /**
148
- * 把「解析当前的配置段」包成一个按源缓存的 thunk。
149
- *
150
- * 配置活引用的 `.get()` 只在值真的变了之后才换快照,没变就还是同一个对象,因此返回值可以
151
- * 直接当**配置版本**用。不缓存的话每次调用都是新对象,运行时的版本判断永远不成立,于是每次
152
- * 刷新都会多排一轮。
153
- *
154
- * @param source - 生效配置段的活引用(每次编辑都就地换掉它的内容)。
155
- * @returns 解析后的配置;源没换时返回同一个对象。
156
- */
157
- export function memoizedConfig(source) {
158
- let from;
159
- let resolved;
160
- return () => {
161
- const current = source();
162
- if (resolved === undefined || from !== current) {
163
- from = current;
164
- resolved = resolveConfig(current);
165
- }
166
- return resolved;
167
- };
168
- }
package/lib/index.d.ts DELETED
@@ -1,70 +0,0 @@
1
- /**
2
- * dsh-aperture:发现 Aperture 网关所服务的模型,并把它们作为 `llm-pi-ai` 的
3
- * provider 路由发布给 DeepSeek Harness。
4
- *
5
- * Aperture 是 Tailscale 的集中式 LLM 网关:一个端点挡在团队有权使用的所有上游前面,靠网络
6
- * 身份而不是密钥认证。harness 本来就会跟这样的网关说话——`dsh-llm-pi-ai` 讲 OpenAI 兼容的
7
- * Chat Completions 与 Anthropic Messages,而这正是 Aperture 暴露的全部——但没有东西让模型
8
- * 清单自己刷新:适配器自带的“获取可用模型”只接受一份当时还在编辑的草稿。
9
- *
10
- * 本插件就是缺的那一半:读 `GET {baseUrl}/v1/models`,逐个模型判断网关实际用哪种协议服务它,
11
- * 用网关自己的字段加上 models.dev 定容量、写描述,最后写进 `llm-pi-ai` 的 provider 字典。
12
- * 它不转换任何协议格式——这正是重点。
13
- *
14
- * 界面在「插件」页里:浏览器半边(`client/aperture.js`)把自己注册成插件管理页的**包级**配置页
15
- * (`plugins.bundle.config`,键是包名),用来改实例地址与同步开关(关掉即撤下已发布的路由)、
16
- * 立刻刷新,以及就地改单个模型的参数。除此之外没有别的界面——发现本身发生在插件加载、配置变更
17
- * 与刷新间隔到点上。
18
- *
19
- * ```yaml
20
- * - id: aperture
21
- * name: 'dsh-aperture'
22
- * config:
23
- * baseUrl: https://ai.example.ts.net
24
- * ```
25
- *
26
- * @module dsh-aperture
27
- */
28
- import type { Context } from '@deepseek-ai/cordis';
29
- import { type ConfigRef } from './config.ts';
30
- export { fetchModelsListing } from './aperture.ts';
31
- export type { ModelsListing } from './aperture.ts';
32
- export { ModelCatalog } from './catalog.ts';
33
- export { APERTURE_NAMESPACE, DEFAULT_CONTEXT_WINDOW, DEFAULT_MODEL_METADATA_URL, resolveConfig, } from './config.ts';
34
- export type { Config as ApertureConfig, ConfigRef, ResolvedConfig } from './config.ts';
35
- export { createPanelOps } from './panel.ts';
36
- export type { PanelAction, PanelDeps, PanelModelPatch, PanelOps } from './panel.ts';
37
- export { buildReport } from './report.ts';
38
- export type { DeclaredOverrides, PanelModel, PanelRefresh, PanelReport, PanelRoute } from './report.ts';
39
- export { DEFAULT_PLACEHOLDER_CREDENTIAL, buildProfilePlan } from './profile.ts';
40
- export type { ProfilePlan, ProfileOptions, RoutePlan } from './profile.ts';
41
- export { buildRegistry, classifyProtocol, isDeepSeekFamily } from './registry.ts';
42
- export type { RegistryResult } from './registry.ts';
43
- export { AperturePanelService, PANEL_CONTRIBUTION, PANEL_INVOCATIONS, PANEL_NAMESPACE, PANEL_PACKAGE } from './remote.ts';
44
- export { PI_AI_NAMESPACE, applySync, planSync } from './sync.ts';
45
- export type { SyncOutcome } from './sync.ts';
46
- export type { ConfiguredModel, DiscoveredModel, FactSource, Modality, ModelProvenance } from './types.ts';
47
- export { buildModelsEndpoint, buildRouteBaseUrl, normalizeBaseUrl } from './url.ts';
48
- export { Config, configValue } from './config.ts';
49
- /** 出现在加载器诊断里的插件名。 */
50
- export declare const name = "dsh-aperture";
51
- /**
52
- * settings 是必需依赖:把发现的模型清单发布进 `llm-pi-ai` **就是**本插件的职责,而同一次
53
- * 注册又让插件自己的 `aperture` 段变得可编辑。声明它意味着框架会把插件挂在 PENDING 直到
54
- * settings 就绪,provider 被替换时卸载插件、恢复后重新加载——而不是留下一个已加载却无处
55
- * 发布的实例。
56
- *
57
- * `typert` 则刻意**不**声明:配置页只是顺手提供的便利,没有它的部署(例如 headless profile)
58
- * 也该照样获得发现能力,因此它在下面按需注入,不在就安静跳过。
59
- */
60
- export declare const inject: string[];
61
- /**
62
- * 发布网关的模型清单:现在发布,之后有任何变化也发布。
63
- *
64
- * @param ctx - 插件上下文,其中 `settings` 已就绪。
65
- * @param config - 组合层的 `aperture` 段,已按 `Config` schema 校验并带上默认值;根级 volatile
66
- * 使它成为活引用,读值走 `config.get()`。
67
- * @throws Error 当配置自身矛盾(路由键不合文法、模型覆盖重复或无法服务),或存储的 `aperture`
68
- * 段非法时抛出——框架的失败路径正是“坏配置要响亮”的实现方式。
69
- */
70
- export declare function apply(ctx: Context, config: ConfigRef): void;