@vessel-agent/model-registry 0.0.0-stage → 2.3.0-beta.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.
package/package.json CHANGED
@@ -1,6 +1,167 @@
1
1
  {
2
2
  "name": "@vessel-agent/model-registry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.3.0-beta.3",
4
+ "description": "Model registry management — credentials, model entries, encrypted values and connectivity tests",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "web"
14
+ ],
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/egg-rolls/Vessel.git",
19
+ "directory": "plugins/provider/model-registry"
20
+ },
21
+ "engines": {
22
+ "bun": ">=1.3.9"
23
+ },
24
+ "scripts": {
25
+ "typecheck": "tsc --noEmit",
26
+ "build:ui": "tsc -p tsconfig.web.json --noEmit && vite build && vite build --config vite.config.embed.ts",
27
+ "typecheck:ui": "tsc -p tsconfig.web.json --noEmit"
28
+ },
29
+ "dependencies": {
30
+ "@vessel-agent/config": "2.3.0-beta.3",
31
+ "@vessel-agent/core": "2.3.0-beta.3",
32
+ "@vessel-agent/plugin-sdk": "1.0.0",
33
+ "@vessel-agent/plugin-ui": "2.3.0-beta.3",
34
+ "react": "^19.1.0",
35
+ "react-dom": "^19.1.0"
36
+ },
37
+ "devDependencies": {
38
+ "@tailwindcss/vite": "^4.3.3",
39
+ "@types/react": "^19.1.0",
40
+ "@types/react-dom": "^19.1.0",
41
+ "@vitejs/plugin-react": "^4.6.0",
42
+ "tailwindcss": "^4.3.3",
43
+ "typescript": "^7.0.2",
44
+ "vite": "^7.0.0"
45
+ },
46
+ "vessel": {
47
+ "id": "model-registry",
48
+ "name": "Model Registry",
49
+ "version": "2.3.0-beta.3",
50
+ "description": "模型管理:凭证面 + 模型面注册表 + 加密凭证库 + 连通性测试(管理 API + credentials/models 管理页)",
51
+ "side": "both",
52
+ "ui": {
53
+ "dir": "web",
54
+ "embed": {
55
+ "entry": "embed/index.mjs",
56
+ "css": "embed/index.css",
57
+ "runtime": {
58
+ "react": "^19",
59
+ "sdk": "^1"
60
+ }
61
+ }
62
+ },
63
+ "activationEvents": [
64
+ "onPage:credentials",
65
+ "onPage:models"
66
+ ],
67
+ "contributes": {
68
+ "i18n": {
69
+ "en": {
70
+ "nav.group": "Model Registry",
71
+ "nav.credentials": "Credentials",
72
+ "nav.models": "Models"
73
+ },
74
+ "zh-CN": {
75
+ "nav.group": "模型管理",
76
+ "nav.credentials": "凭证",
77
+ "nav.models": "模型"
78
+ }
79
+ },
80
+ "navGroups": [
81
+ {
82
+ "id": "plugin:model-registry",
83
+ "title": "Model Registry",
84
+ "titleKey": "nav.group",
85
+ "icon": "settings",
86
+ "order": 45
87
+ }
88
+ ],
89
+ "pages": [
90
+ {
91
+ "id": "credentials",
92
+ "title": "Credentials",
93
+ "titleKey": "nav.credentials",
94
+ "nav": "plugin:model-registry",
95
+ "icon": "settings",
96
+ "order": 10,
97
+ "entry": "credentials.html",
98
+ "component": "CredentialsView"
99
+ },
100
+ {
101
+ "id": "models",
102
+ "title": "Models",
103
+ "titleKey": "nav.models",
104
+ "nav": "plugin:model-registry",
105
+ "icon": "hub",
106
+ "order": 11,
107
+ "entry": "models.html",
108
+ "component": "ModelsView"
109
+ }
110
+ ],
111
+ "rpc": [
112
+ {
113
+ "name": "list",
114
+ "description": "Registry snapshot: credentials / entries / default / effective / legacyPresent",
115
+ "permission": "read"
116
+ },
117
+ {
118
+ "name": "model_set",
119
+ "description": "Create or replace a model entry (whole-entry replace; alias/pricing/param/info are entry fields)",
120
+ "permission": "write"
121
+ },
122
+ {
123
+ "name": "model_remove",
124
+ "description": "Remove a model entry; refuses while models.default references it",
125
+ "permission": "write"
126
+ },
127
+ {
128
+ "name": "default_set",
129
+ "description": "Set models.default ref (alias or entry key); returns the effective model",
130
+ "permission": "write"
131
+ },
132
+ {
133
+ "name": "credential_set",
134
+ "description": "Write credential metadata (baseUrl/apiKeyEnv) and optionally the encrypted value in one transaction (value is write-only, never echoed)",
135
+ "permission": "write"
136
+ },
137
+ {
138
+ "name": "credential_remove",
139
+ "description": "Remove a credential (yaml metadata + stored value); refuses while entries reference it",
140
+ "permission": "write"
141
+ },
142
+ {
143
+ "name": "credentials_list",
144
+ "description": "Credential metadata only: id / baseUrl / apiKeyEnv / hasValue / timestamps / usedBy (no values)",
145
+ "permission": "read"
146
+ },
147
+ {
148
+ "name": "test",
149
+ "description": "User-triggered connectivity test against a saved entry or credential (sends a real minimal request)",
150
+ "permission": "write"
151
+ }
152
+ ]
153
+ },
154
+ "permissions": {
155
+ "fs": [
156
+ "data-dir",
157
+ "user-config"
158
+ ],
159
+ "net": [
160
+ "*"
161
+ ],
162
+ "process": false,
163
+ "secrets": false,
164
+ "events": []
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * model-registry 插件:连通性测试(契约 §3.4)。
3
+ *
4
+ * **产品功能,用户触发**(UI「测试」按钮 / 显式 RPC test);绝不在启动 / 保存 / 定时路径
5
+ * 自动触发,实施切片的 AI 也不调用它。第 2 级发真实请求(1 token 级成本)。
6
+ *
7
+ * 两级:
8
+ * 1. openai 系协议且未指定 model:GET {baseUrl}/models(Bearer,setup-wizard fetchModels 先例)
9
+ * → ok + 模型列表(UI 可辅助导入 models)。
10
+ * 2. anthropic 协议(无 /models 端点)或指定 model:最小 chat(max_tokens=1,单条 ping;
11
+ * anthropic 用 x-api-key + anthropic-version)。
12
+ *
13
+ * 单次尝试、**不走 withRetry**、15s 超时;error 经 redactor(不含 key / 完整请求头)。
14
+ * 只接受已保存 vendor(凭证解析在 index.ts;明文 key 不出现在 test 参数)。
15
+ */
16
+
17
+ import { defaultBaseUrlFor } from '@vessel-agent/config';
18
+ import { createDefaultTraceRedactor } from '@vessel-agent/core';
19
+
20
+ export { defaultBaseUrlFor };
21
+
22
+ export interface ConnectivityResult {
23
+ ok: boolean;
24
+ latencyMs: number;
25
+ models?: string[];
26
+ error?: { code: string; message: string };
27
+ }
28
+
29
+ const TIMEOUT_MS = 15_000;
30
+ const redactor = createDefaultTraceRedactor();
31
+
32
+ /** error message 经默认 redactor(sk- / Bearer / JWT / AWS 模式 → ***)。 */
33
+ function redactMessage(message: string): string {
34
+ // 合成事件只作 redactor 包装,绝不发布(同 cleared-tool-result 先例)。
35
+ const event = redactor.redact({
36
+ type: 'redactor.wrap',
37
+ run_id: '',
38
+ ts: 0,
39
+ data: { message },
40
+ });
41
+ const value = (event.data as Record<string, unknown>).message;
42
+ return typeof value === 'string' ? value : '***';
43
+ }
44
+
45
+ /** 去掉尾斜杠,避免拼出 `//models` / `//chat/completions`。 */
46
+ function normalizeBaseUrl(url: string): string {
47
+ return url.replace(/\/+$/, '');
48
+ }
49
+
50
+ export async function testConnectivity(options: {
51
+ protocol: string;
52
+ baseUrl: string;
53
+ apiKey: string;
54
+ model?: string;
55
+ }): Promise<ConnectivityResult> {
56
+ const { protocol, apiKey, model } = options;
57
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
58
+ const startedAt = performance.now();
59
+ const elapsed = (): number => Math.round(performance.now() - startedAt);
60
+ const fail = (code: string, message: string): ConnectivityResult => ({
61
+ ok: false,
62
+ latencyMs: elapsed(),
63
+ error: { code, message: redactMessage(message) },
64
+ });
65
+
66
+ try {
67
+ const useChat = protocol === 'anthropic' || model !== undefined;
68
+ if (!useChat) {
69
+ // 第 1 级:GET /models(openai 系;Bearer)。
70
+ const res = await fetch(`${baseUrl}/models`, {
71
+ headers: { Authorization: `Bearer ${apiKey}` },
72
+ signal: AbortSignal.timeout(TIMEOUT_MS),
73
+ });
74
+ if (!res.ok) {
75
+ const body = await res.text().catch(() => '');
76
+ return fail('http_error', `HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : ''}`);
77
+ }
78
+ const payload = (await res.json()) as { data?: Array<{ id?: unknown }> };
79
+ const models = Array.isArray(payload.data)
80
+ ? payload.data
81
+ .map((entry) => entry?.id)
82
+ .filter((id): id is string => typeof id === 'string')
83
+ : [];
84
+ return { ok: true, latencyMs: elapsed(), models };
85
+ }
86
+
87
+ // 第 2 级:最小 chat(max_tokens=1,单条 ping)。
88
+ if (model === undefined || model === '') {
89
+ return fail('no_model', 'chat connectivity test requires a model');
90
+ }
91
+ const anthropic = protocol === 'anthropic';
92
+ const url = anthropic ? `${baseUrl}/v1/messages` : `${baseUrl}/chat/completions`;
93
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
94
+ if (anthropic) {
95
+ headers['x-api-key'] = apiKey;
96
+ headers['anthropic-version'] = '2023-06-01';
97
+ } else {
98
+ headers.Authorization = `Bearer ${apiKey}`;
99
+ }
100
+ const res = await fetch(url, {
101
+ method: 'POST',
102
+ headers,
103
+ body: JSON.stringify({
104
+ model,
105
+ max_tokens: 1,
106
+ messages: [{ role: 'user', content: 'ping' }],
107
+ }),
108
+ signal: AbortSignal.timeout(TIMEOUT_MS),
109
+ });
110
+ if (!res.ok) {
111
+ const body = await res.text().catch(() => '');
112
+ return fail('http_error', `HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : ''}`);
113
+ }
114
+ // 成功即连通;丢弃响应体释放连接,不解析内容。
115
+ await res.body?.cancel().catch(() => {}); // benign: 探测后取消流尽力而为。
116
+ return { ok: true, latencyMs: elapsed() };
117
+ } catch (error) {
118
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
119
+ return fail('timeout', `request timed out after ${TIMEOUT_MS}ms`);
120
+ }
121
+ return fail('network_error', error instanceof Error ? error.message : String(error));
122
+ }
123
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * model-registry 插件:加密凭证库 `<dataDir>/credentials.json`。
3
+ *
4
+ * 契约:docs/dev/plans/model-registry.md §2.2 + CONTRACT-model-registry-internal.md §2。
5
+ * - 信封 `{v:1, entries:{id:{iv,tag,data,createdAt,updatedAt}}}`;AES-256-GCM(node:crypto)。
6
+ * - key = derivePurposeToken(root, {kind:'credentials'}) 去 `vsk_` 前缀后 base64url 解码(32B);
7
+ * root 经 ensureRootSecret(缺省自动生成)。不在插件里私写第二套 HKDF。
8
+ * - atomicWrite 0600 + 插件内串行写队列(read-modify-write 整段串行,不只写盘)。
9
+ * - 轮换 = updatedAt bump(D10:root-secret 轮换 → 全部失效需重录,不做重加密迁移)。
10
+ * - 与 `<dataDir>/auth/credentials.json`(gateway 登录库)互不消费。
11
+ * - 明文纪律:value 只在 credential_set 写入瞬间存在;reveal 只供连通性测试(产品功能,
12
+ * 用户触发),RPC 结果 / 日志永不回显。
13
+ */
14
+
15
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
16
+ import { readFile } from 'node:fs/promises';
17
+ import * as path from 'node:path';
18
+ import {
19
+ DEFAULT_DATA_DIR,
20
+ DERIVED_TOKEN_PREFIX,
21
+ derivePurposeToken,
22
+ ensureRootSecret,
23
+ expandHomePath,
24
+ ROOT_SECRET_BYTES,
25
+ rootSecretPath,
26
+ type VesselConfig,
27
+ } from '@vessel-agent/config';
28
+ import { atomicWrite } from '@vessel-agent/core';
29
+
30
+ function isRecord(value: unknown): value is Record<string, unknown> {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
32
+ }
33
+
34
+ function messageOf(error: unknown): string {
35
+ return error instanceof Error ? error.message : String(error);
36
+ }
37
+
38
+ function nonEmpty(value: string | undefined): string | undefined {
39
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
40
+ }
41
+
42
+ /**
43
+ * dataDir 解析口径(契约 §2 冻结;oracle = src/data-paths.ts resolveDataDir):
44
+ * config.dataDir → VESSEL_DATA_DIR → DEFAULT_DATA_DIR,expandHome + path.resolve。
45
+ * 用 @vessel-agent/config 现成导出实现同口径,不移 resolveDataDir、不新增包导出。
46
+ */
47
+ export function resolveDataDir(config: VesselConfig): string {
48
+ const configured = nonEmpty(config.dataDir) ?? nonEmpty(process.env.VESSEL_DATA_DIR);
49
+ return path.resolve(expandHomePath(configured ?? DEFAULT_DATA_DIR));
50
+ }
51
+
52
+ interface CredentialEnvelopeEntry {
53
+ iv: string;
54
+ tag: string;
55
+ data: string;
56
+ createdAt: string;
57
+ updatedAt: string;
58
+ }
59
+
60
+ interface CredentialEnvelope {
61
+ v: 1;
62
+ entries: Record<string, CredentialEnvelopeEntry>;
63
+ }
64
+
65
+ /** credentials_list 条目:只有元数据,无值、无片段、无指纹。 */
66
+ export interface CredentialMeta {
67
+ id: string;
68
+ createdAt: string;
69
+ updatedAt: string;
70
+ }
71
+
72
+ /**
73
+ * 串行写队列(按文件路径):跨 RPC 调用串行化整段 read-modify-write。
74
+ * 实例每次 RPC 新建,队列必须挂模块级;形状同 core atomicWrite 的 pendingWrites。
75
+ */
76
+ const writeChains = new Map<string, Promise<unknown>>();
77
+
78
+ async function serialize<T>(file: string, task: () => Promise<T>): Promise<T> {
79
+ const previous = writeChains.get(file) ?? Promise.resolve();
80
+ const current = previous.then(task, task);
81
+ const tail = current.then(
82
+ () => {},
83
+ () => {},
84
+ );
85
+ writeChains.set(file, tail);
86
+ try {
87
+ return await current;
88
+ } finally {
89
+ if (writeChains.get(file) === tail) writeChains.delete(file);
90
+ }
91
+ }
92
+
93
+ export class CredentialStore {
94
+ constructor(private readonly dataDir: string) {}
95
+
96
+ private get file(): string {
97
+ return path.join(this.dataDir, 'credentials.json');
98
+ }
99
+
100
+ /** AES-256-GCM key:root-secret 经冻结 HKDF 派生(vessel:credentials),去前缀解码 32B。 */
101
+ private encryptionKey(): Buffer {
102
+ const read = ensureRootSecret(rootSecretPath(this.dataDir));
103
+ if (!read.ok) throw new Error(`root_secret_unavailable: ${read.error.message}`);
104
+ const token = derivePurposeToken(read.value.secret, { kind: 'credentials' });
105
+ const key = Buffer.from(token.slice(DERIVED_TOKEN_PREFIX.length), 'base64url');
106
+ if (key.length !== ROOT_SECRET_BYTES) {
107
+ throw new Error('credential_key_invalid: derived credentials key is not 32 bytes');
108
+ }
109
+ return key;
110
+ }
111
+
112
+ /** 读信封;不存在 = 空库;损坏 ≠ 不存在,抛错不静默覆盖。 */
113
+ private async readEnvelope(): Promise<CredentialEnvelope> {
114
+ let raw: string;
115
+ try {
116
+ raw = await readFile(this.file, 'utf-8');
117
+ } catch (error) {
118
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { v: 1, entries: {} };
119
+ throw new Error(`credentials_read_failed: ${this.file}: ${messageOf(error)}`);
120
+ }
121
+ let parsed: unknown;
122
+ try {
123
+ parsed = JSON.parse(raw);
124
+ } catch (error) {
125
+ throw new Error(`credentials_corrupt: ${this.file}: ${messageOf(error)}`);
126
+ }
127
+ if (!isRecord(parsed) || parsed.v !== 1 || !isRecord(parsed.entries)) {
128
+ throw new Error(`credentials_corrupt: ${this.file}: unexpected envelope shape`);
129
+ }
130
+ for (const [id, entry] of Object.entries(parsed.entries)) {
131
+ if (
132
+ !isRecord(entry) ||
133
+ typeof entry.iv !== 'string' ||
134
+ typeof entry.tag !== 'string' ||
135
+ typeof entry.data !== 'string' ||
136
+ typeof entry.createdAt !== 'string' ||
137
+ typeof entry.updatedAt !== 'string'
138
+ ) {
139
+ throw new Error(`credentials_corrupt: ${this.file}: entry "${id}" has invalid shape`);
140
+ }
141
+ }
142
+ return { v: 1, entries: parsed.entries as Record<string, CredentialEnvelopeEntry> };
143
+ }
144
+
145
+ private async persist(envelope: CredentialEnvelope): Promise<void> {
146
+ await atomicWrite(this.file, `${JSON.stringify(envelope, null, 2)}\n`, {
147
+ mode: 0o600,
148
+ ensureDir: true,
149
+ });
150
+ }
151
+
152
+ /** 元数据列表(无值)。usedBy 由调用方按 registry 引用计算。 */
153
+ async list(): Promise<CredentialMeta[]> {
154
+ const envelope = await this.readEnvelope();
155
+ return Object.entries(envelope.entries).map(([id, entry]) => ({
156
+ id,
157
+ createdAt: entry.createdAt,
158
+ updatedAt: entry.updatedAt,
159
+ }));
160
+ }
161
+
162
+ /** 增 / 轮换合一:新 iv 重加密;既有 createdAt 保留,updatedAt bump。 */
163
+ async set(id: string, value: string): Promise<{ updatedAt: string }> {
164
+ return serialize(this.file, async () => {
165
+ const envelope = await this.readEnvelope();
166
+ const key = this.encryptionKey();
167
+ const iv = randomBytes(12);
168
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
169
+ const data = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
170
+ const now = new Date().toISOString();
171
+ const existing = envelope.entries[id];
172
+ envelope.entries[id] = {
173
+ iv: iv.toString('base64'),
174
+ tag: cipher.getAuthTag().toString('base64'),
175
+ data: data.toString('base64'),
176
+ createdAt: existing?.createdAt ?? now,
177
+ updatedAt: now,
178
+ };
179
+ await this.persist(envelope);
180
+ return { updatedAt: now };
181
+ });
182
+ }
183
+
184
+ /** 删除;不存在即报错(引用检查在调用方,先于本方法)。 */
185
+ async remove(id: string): Promise<void> {
186
+ return serialize(this.file, async () => {
187
+ const envelope = await this.readEnvelope();
188
+ if (!Object.hasOwn(envelope.entries, id)) {
189
+ throw new Error(`unknown_credential: "${id}"`);
190
+ }
191
+ delete envelope.entries[id];
192
+ await this.persist(envelope);
193
+ });
194
+ }
195
+
196
+ /**
197
+ * 解密取明文:**只供连通性测试**(产品功能,用户触发)在进程内消费;
198
+ * 绝不进 RPC 结果 / 日志。解密失败 = root-secret 可能已轮换(D10:需重录)。
199
+ */
200
+ async reveal(id: string): Promise<string> {
201
+ const envelope = await this.readEnvelope();
202
+ const entry = envelope.entries[id];
203
+ if (entry === undefined) throw new Error(`unknown_credential: "${id}"`);
204
+ const key = this.encryptionKey();
205
+ try {
206
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(entry.iv, 'base64'));
207
+ decipher.setAuthTag(Buffer.from(entry.tag, 'base64'));
208
+ return Buffer.concat([
209
+ decipher.update(Buffer.from(entry.data, 'base64')),
210
+ decipher.final(),
211
+ ]).toString('utf8');
212
+ } catch {
213
+ throw new Error(
214
+ `credential_decrypt_failed: "${id}" cannot be decrypted ` +
215
+ '(the root secret may have been rotated; re-record the credential)',
216
+ );
217
+ }
218
+ }
219
+ }