@sanqianx/claude-ai-workbench 0.13.2 → 0.13.4

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 (122) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +156 -156
  3. package/apps/agent-terminal/app.css +652 -613
  4. package/apps/agent-terminal/app.js +143 -67
  5. package/apps/agent-terminal/conversation-composer.js +44 -0
  6. package/apps/agent-terminal/index.html +172 -170
  7. package/apps/agent-terminal/panel-host-proof.html +152 -152
  8. package/apps/agent-terminal/panel-proof-content.html +41 -41
  9. package/apps/agent-terminal/right-workspace-dock.css +189 -159
  10. package/apps/agent-terminal/right-workspace-dock.js +652 -521
  11. package/apps/agent-terminal/user-question-card.js +68 -0
  12. package/apps/ai-profile-settings-host/index.html +25 -25
  13. package/apps/ai-profile-settings-host/page.css +1 -1
  14. package/apps/ai-profile-settings-host/page.js +113 -113
  15. package/apps/minimal-test-host/README.md +15 -15
  16. package/apps/minimal-test-host/host.css +2 -2
  17. package/apps/minimal-test-host/host.js +35 -35
  18. package/apps/minimal-test-host/index.html +58 -58
  19. package/apps/minimal-test-host/optional-mock/fault-injection.js +15 -15
  20. package/docs/sdk/FILE_LAYOUT.md +31 -31
  21. package/docs/sdk/INTEGRATION.md +126 -126
  22. package/docs/sdk/README.md +21 -21
  23. package/docs/sdk/SESSION_EVENTS.md +15 -13
  24. package/docs/sdk/openapi.yaml +16 -1
  25. package/package.json +1 -1
  26. package/packages/client/README.md +29 -29
  27. package/packages/client/index.d.ts +122 -122
  28. package/packages/client/index.js +260 -260
  29. package/packages/client/package.json +2 -2
  30. package/packages/contracts/README.md +9 -9
  31. package/packages/contracts/index.d.ts +519 -517
  32. package/packages/contracts/index.js +312 -312
  33. package/packages/contracts/package.json +1 -1
  34. package/packages/core/README.md +8 -8
  35. package/packages/core/index.d.ts +76 -76
  36. package/packages/core/index.js +222 -222
  37. package/packages/core/package.json +2 -2
  38. package/packages/server/README.md +17 -17
  39. package/packages/server/bin/agent-terminal-server.js +42 -42
  40. package/packages/server/bin/claude-workbench.js +225 -225
  41. package/packages/server/index.d.ts +171 -171
  42. package/packages/server/index.js +230 -230
  43. package/packages/server/lib/agent-discovery.js +133 -133
  44. package/packages/server/lib/agent-registry.js +143 -143
  45. package/packages/server/lib/agent-spawn-env.js +17 -17
  46. package/packages/server/lib/attachment-store.js +78 -78
  47. package/packages/server/lib/bridges/app-server-bridge.js +373 -373
  48. package/packages/server/lib/bridges/opencode-server-bridge.js +506 -506
  49. package/packages/server/lib/capture-settings-store.js +35 -35
  50. package/packages/server/lib/claude-history-recovery.js +87 -87
  51. package/packages/server/lib/cli-session-recovery.js +28 -28
  52. package/packages/server/lib/context-resolver.js +55 -55
  53. package/packages/server/lib/conversation-capture.js +51 -51
  54. package/packages/server/lib/delegation-phase-store.js +357 -357
  55. package/packages/server/lib/delegation-store.js +474 -468
  56. package/packages/server/lib/diagnostics.js +32 -32
  57. package/packages/server/lib/drivers/cli-json-runner.js +974 -974
  58. package/packages/server/lib/drivers/codex-driver.js +1461 -1442
  59. package/packages/server/lib/drivers/opencode-driver.js +1554 -1554
  60. package/packages/server/lib/drivers/zcode-driver.js +1250 -1250
  61. package/packages/server/lib/drivers/zcode-profile-runtime.js +71 -71
  62. package/packages/server/lib/event-stream.js +138 -138
  63. package/packages/server/lib/folder-picker.js +623 -623
  64. package/packages/server/lib/http-handler.js +339 -339
  65. package/packages/server/lib/json-file.js +26 -26
  66. package/packages/server/lib/knowledge-context.js +33 -33
  67. package/packages/server/lib/model-detection.js +295 -295
  68. package/packages/server/lib/parent-context.js +44 -0
  69. package/packages/server/lib/profile-store.js +283 -283
  70. package/packages/server/lib/project-store.js +102 -102
  71. package/packages/server/lib/runtime-loader.js +120 -120
  72. package/packages/server/lib/session-archive-store.js +53 -53
  73. package/packages/server/lib/session-history.js +612 -612
  74. package/packages/server/lib/system-doctor.js +125 -125
  75. package/packages/server/lib/ui-preferences-store.js +48 -48
  76. package/packages/server/lib/user-questions.js +67 -0
  77. package/packages/server/lib/workbench-service.js +1696 -1675
  78. package/packages/server/package.json +2 -2
  79. package/packages/ui/README.md +30 -30
  80. package/packages/ui/ai-profile-settings.d.ts +45 -45
  81. package/packages/ui/ai-profile-settings.js +283 -283
  82. package/packages/ui/claude-terminal.d.ts +31 -31
  83. package/packages/ui/claude-terminal.js +343 -343
  84. package/packages/ui/index.d.ts +18 -18
  85. package/packages/ui/index.js +51 -51
  86. package/packages/ui/package.json +2 -2
  87. package/packages/ui/theme.css +13 -13
  88. package/src/assets/claude-prompts.json +21 -21
  89. package/src/backend/http/ai-profile-routes.js +61 -61
  90. package/src/backend/http/claude-routes.js +170 -170
  91. package/src/backend/http/node-helpers.js +45 -45
  92. package/src/backend/index.js +21 -21
  93. package/src/backend/lib/ai-adapter.js +144 -144
  94. package/src/backend/lib/ai-profile-store.js +259 -259
  95. package/src/backend/lib/ai-vendor-presets.js +83 -83
  96. package/src/backend/lib/ai-workspace.js +140 -140
  97. package/src/backend/lib/automation-config.js +253 -253
  98. package/src/backend/lib/claude-cli-runner.js +2408 -2392
  99. package/src/backend/lib/data-dir.js +169 -169
  100. package/src/backend/lib/llm-client.js +176 -176
  101. package/src/backend/lib/model-context-windows.js +82 -82
  102. package/src/backend/lib/native-task-control.js +217 -217
  103. package/src/backend/lib/native-task-history-index.js +475 -475
  104. package/src/backend/lib/native-task-history-reader.js +526 -526
  105. package/src/backend/lib/native-task-messages.js +457 -457
  106. package/src/backend/lib/native-task-registry.js +325 -325
  107. package/src/backend/lib/native-task-runtime.js +242 -242
  108. package/src/backend/lib/native-task-trace.js +440 -440
  109. package/src/backend/lib/native-task-transcript.js +393 -393
  110. package/src/backend/lib/prompt-registry.js +166 -166
  111. package/src/backend/lib/runtime-config.js +121 -121
  112. package/src/backend/lib/sdk-session-stream.js +143 -143
  113. package/src/backend/lib/sdk-turn-stream.js +16 -16
  114. package/src/backend/lib/store-scope.js +131 -131
  115. package/src/backend/lib/task-identity.js +104 -104
  116. package/src/backend/lib/task-state-projection.js +58 -58
  117. package/src/index.js +7 -7
  118. package/src/sdk-wave-a.ts +1 -1
  119. package/src/sdk-wave-b.ts +1 -1
  120. package/src/sdk-wave-c.ts +1 -1
  121. package/src/sdk-wave-d.ts +1 -1
  122. package/src/sdk-wave-e.ts +1 -1
@@ -1,283 +1,283 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const fs = require('fs');
5
- const { normalizeProfile, cleanId } = require('../../contracts');
6
- const { readJson, writeJson } = require('./json-file');
7
-
8
- class ProfileStore {
9
- constructor(options = {}) {
10
- if (!options.dataDir) throw new Error('ProfileStore dataDir is required');
11
- this.profileFile = options.profileFile || path.join(options.dataDir, 'profiles.v2.json');
12
- this.credentialFile = options.credentialFile || path.join(options.dataDir, 'credentials.v1.json');
13
- }
14
-
15
- _profiles() { return readJson(this.profileFile, { schema: 'claude-workbench-profiles/v2', profiles: [] }); }
16
- _credentials() { return readJson(this.credentialFile, { schema: 'claude-workbench-credentials/v1', credentials: {} }); }
17
-
18
- _configured(profile) {
19
- return Boolean(this._credentials().credentials[profile.credentialRef]);
20
- }
21
-
22
- publicProfile(profile) {
23
- profile = normalizeProfile(profile);
24
- const secret = this._credentials().credentials[profile.credentialRef] || '';
25
- const clean = {
26
- ...profile,
27
- credentialConfigured: Boolean(secret),
28
- credentialMasked: maskCredential(secret),
29
- };
30
- delete clean.apiKey;
31
- delete clean.authToken;
32
- delete clean.anthropicAuthToken;
33
- delete clean.secret;
34
- return clean;
35
- }
36
-
37
- list() { return this._profiles().profiles.map(profile => this.publicProfile(profile)); }
38
-
39
- maintenanceDefault() {
40
- const id = this._profiles().maintenanceDefaultProfileId || null;
41
- return { profileId: id, profile: id ? this.get(id) : null };
42
- }
43
-
44
- setMaintenanceDefault(id) {
45
- const profileId = id == null ? null : cleanId(id, 'profileId');
46
- if (profileId) this.runtimeProfile(profileId);
47
- const cfg = this._profiles();
48
- cfg.maintenanceDefaultProfileId = profileId;
49
- writeJson(this.profileFile, cfg);
50
- return this.maintenanceDefault();
51
- }
52
-
53
- maintenanceRuntime() {
54
- const { profileId } = this.maintenanceDefault();
55
- if (!profileId) throw Object.assign(new Error('maintenance default profile is not configured'), { status: 409 });
56
- // Always use the persisted provider default, never a session selection.
57
- return this.runtimeProfile(profileId);
58
- }
59
-
60
- embeddingConfig() {
61
- const saved = this._profiles().embedding;
62
- if (!saved) return { configured: false, config: null };
63
- const { credentialRef, ...config } = saved;
64
- config.endpoint = normalizeEmbedding(saved).endpoint;
65
- let configured = false;
66
- try { configured = Boolean(this.embeddingRuntime()); } catch {}
67
- return { configured, config };
68
- }
69
-
70
- setEmbeddingConfig(input = {}) {
71
- const cfg = this._profiles();
72
- if (input.enabled === false) {
73
- const keys = this._credentials();
74
- delete keys.credentials[cfg.embedding?.credentialRef];
75
- writeJson(this.credentialFile, keys);
76
- cfg.embedding = null;
77
- } else {
78
- const next = normalizeEmbedding(input);
79
- if (next.profileId) this.runtimeProfile(next.profileId);
80
- else {
81
- next.credentialRef = 'knowledge-embedding';
82
- const keys = this._credentials();
83
- const secret = typeof input.secret === 'string' ? input.secret.trim() : '';
84
- if (secret) keys.credentials[next.credentialRef] = secret;
85
- if (!keys.credentials[next.credentialRef]) throw Object.assign(new Error('向量模型凭据未配置。'), { status: 400 });
86
- writeJson(this.credentialFile, keys);
87
- }
88
- cfg.embedding = next;
89
- }
90
- writeJson(this.profileFile, cfg);
91
- return this.embeddingConfig();
92
- }
93
-
94
- embeddingRuntime() {
95
- const saved = this._profiles().embedding;
96
- if (!saved) throw Object.assign(new Error('向量模型未配置。'), { status: 409 });
97
- const secret = saved.profileId ? this.runtimeProfile(saved.profileId).apiKey : this._credentials().credentials[saved.credentialRef];
98
- if (!secret) throw Object.assign(new Error('向量模型凭据未配置。'), { status: 409 });
99
- return { provider: saved.provider, model: saved.model, endpoint: normalizeEmbedding(saved).endpoint, apiKey: secret };
100
- }
101
-
102
- importEmbedding({ migrationId, settings }) {
103
- if (!/^embedding-[a-f0-9]{64}$/.test(migrationId || '')) throw Object.assign(new Error('无效的向量配置迁移。'), { status: 400 });
104
- const cfg = this._profiles();
105
- if (cfg.embeddingImports?.[migrationId]) return this.embeddingConfig();
106
- const backup = path.join(path.dirname(this.profileFile), 'recovery', migrationId);
107
- fs.mkdirSync(backup, { recursive: true, mode: 0o700 });
108
- for (const file of [this.profileFile, this.credentialFile]) {
109
- const target = path.join(backup, path.basename(file));
110
- if (fs.existsSync(file) && !fs.existsSync(target)) { fs.copyFileSync(file, target, fs.constants.COPYFILE_EXCL); fs.chmodSync(target, 0o600); }
111
- }
112
- // An existing Workbench choice wins. The caller keeps its own rollback
113
- // backup before removing the retired, module-local active credential.
114
- if (!cfg.embedding) this.setEmbeddingConfig({ ...settings, secret: settings?.apiKey });
115
- const next = this._profiles();
116
- next.embeddingImports = { ...next.embeddingImports, [migrationId]: true };
117
- writeJson(this.profileFile, next);
118
- return this.embeddingConfig();
119
- }
120
-
121
- importLegacy({ migrationId, profiles, defaultProfileId }) {
122
- if (!/^cutover-[a-f0-9-]{36}$/.test(migrationId || '') || !Array.isArray(profiles)) throw Object.assign(new Error('invalid profile migration'), { status: 400 });
123
- const current = this._profiles();
124
- if (current.migrationImports?.[migrationId]) return current.migrationImports[migrationId];
125
- const prepared = profiles.map(raw => {
126
- const id = `legacy-${cleanId(raw.id, 'profileId')}`;
127
- if (this.get(id)) throw Object.assign(new Error('legacy profile identity conflicts with existing configuration'), { status: 409 });
128
- const profile = normalizeProfile({ id, name: raw.name || raw.id, provider: raw.provider || 'anthropic-compatible', baseUrl: raw.baseUrl || raw.anthropicBaseUrl, openaiBaseUrl: raw.openaiBaseUrl, enabled: raw.enabled !== false, models: raw.models || { default: raw.mainModel || raw.model, reasoning: raw.thinkingModel, fast: raw.haikuModel, coding: raw.sonnetModel, largeContext: raw.opusModel } });
129
- validateProfile(profile);
130
- return { sourceId: raw.id, profile, secret: raw.apiKey || raw.anthropicApiKey || raw.authToken || raw.anthropicAuthToken || '' };
131
- });
132
- const backup = path.join(path.dirname(this.profileFile), 'recovery', migrationId);
133
- fs.mkdirSync(backup, { recursive: true, mode: 0o700 });
134
- for (const file of [this.profileFile, this.credentialFile]) {
135
- const target = path.join(backup, path.basename(file));
136
- if (fs.existsSync(file) && !fs.existsSync(target)) { fs.copyFileSync(file, target, fs.constants.COPYFILE_EXCL); fs.chmodSync(target, 0o600); }
137
- }
138
- const mapping = {};
139
- const nextProfiles = current;
140
- const nextCredentials = this._credentials();
141
- for (const item of prepared) {
142
- mapping[item.sourceId] = item.profile.id;
143
- nextProfiles.profiles.push(item.profile);
144
- if (item.secret) nextCredentials.credentials[item.profile.credentialRef] = String(item.secret);
145
- }
146
- // Write keys first: a crash may leave an unused credential, never a profile
147
- // silently bound to a missing/different secret. Retrying uses the same map.
148
- writeJson(this.credentialFile, nextCredentials);
149
- const preferred = prepared.find(item => item.sourceId === defaultProfileId && item.secret && item.profile.enabled) || prepared.find(item => item.secret && item.profile.enabled);
150
- if (!nextProfiles.maintenanceDefaultProfileId && preferred) nextProfiles.maintenanceDefaultProfileId = preferred.profile.id;
151
- nextProfiles.migrationImports = { ...nextProfiles.migrationImports, [migrationId]: mapping };
152
- writeJson(this.profileFile, nextProfiles);
153
- return mapping;
154
- }
155
-
156
- get(id) {
157
- const profileId = cleanId(id, 'profileId');
158
- const profile = this._profiles().profiles.find(item => item.id === profileId);
159
- return profile ? this.publicProfile(profile) : null;
160
- }
161
-
162
- save(input, idOverride) {
163
- const profile = normalizeProfile(input, idOverride);
164
- validateProfile(profile);
165
- const cfg = this._profiles();
166
- const index = cfg.profiles.findIndex(item => item.id === profile.id);
167
- if (index >= 0) cfg.profiles[index] = profile;
168
- else cfg.profiles.push(profile);
169
- writeJson(this.profileFile, cfg);
170
- return this.publicProfile(profile);
171
- }
172
-
173
- delete(id) {
174
- const profileId = cleanId(id, 'profileId');
175
- const cfg = this._profiles();
176
- const profile = cfg.profiles.find(item => item.id === profileId);
177
- if (!profile) return false;
178
- cfg.profiles = cfg.profiles.filter(item => item.id !== profileId);
179
- if (cfg.maintenanceDefaultProfileId === profileId) cfg.maintenanceDefaultProfileId = null;
180
- writeJson(this.profileFile, cfg);
181
- const secrets = this._credentials();
182
- delete secrets.credentials[profile.credentialRef];
183
- writeJson(this.credentialFile, secrets);
184
- return true;
185
- }
186
-
187
- setCredential(id, credential) {
188
- const profileId = cleanId(id, 'profileId');
189
- const cfg = this._profiles();
190
- const profile = cfg.profiles.find(item => item.id === profileId);
191
- if (!profile) throw Object.assign(new Error('profile not found'), { status: 404 });
192
- const secret = typeof credential === 'string' ? credential : credential && credential.secret;
193
- if (!secret || typeof secret !== 'string') {
194
- throw Object.assign(new Error('credential secret is required'), { status: 400 });
195
- }
196
- const secrets = this._credentials();
197
- secrets.credentials[profile.credentialRef] = String(secret);
198
- writeJson(this.credentialFile, secrets);
199
- }
200
-
201
- runtimeProfile(id) {
202
- const profileId = cleanId(id, 'profileId');
203
- const profile = this._profiles().profiles.find(item => item.id === profileId);
204
- if (!profile) throw Object.assign(new Error('profile not found'), { status: 404 });
205
- if (!profile.enabled) throw Object.assign(new Error('profile is disabled'), { status: 400 });
206
- const secret = this._credentials().credentials[profile.credentialRef];
207
- if (!secret) throw Object.assign(new Error('profile credential is not configured'), { status: 400 });
208
- return runtimeShape(profile, secret);
209
- }
210
-
211
- runtimeDraft(input, credential, options = {}) {
212
- const profile = normalizeProfile(input);
213
- validateProfile(profile, options);
214
- if (!profile.enabled) throw Object.assign(new Error('profile is disabled'), { status: 400 });
215
- let secret = typeof credential === 'string' ? credential : credential && credential.secret;
216
- if (!secret) {
217
- const saved = this._profiles().profiles.find(item => item.id === profile.id);
218
- if (saved) secret = this._credentials().credentials[saved.credentialRef];
219
- }
220
- if (!secret) throw Object.assign(new Error('profile credential is not configured'), { status: 400 });
221
- return runtimeShape(profile, String(secret));
222
- }
223
- }
224
-
225
- function runtimeShape(profile, secret) {
226
- profile = normalizeProfile(profile);
227
- return {
228
- ...profile,
229
- apiKey: secret,
230
- mainModel: profile.models.default,
231
- thinkingModel: profile.models.reasoning || profile.models.default,
232
- haikuModel: profile.models.fast || profile.models.default,
233
- sonnetModel: profile.models.coding || profile.models.default,
234
- opusModel: profile.models.largeContext || profile.models.default,
235
- };
236
- }
237
-
238
- function maskCredential(secret) {
239
- const value = String(secret || '');
240
- if (!value) return '';
241
- if (value.length <= 12) return `${value.slice(0, 2)}****${value.slice(-2)}`;
242
- return `${value.slice(0, 6)}****${value.slice(-6)}`;
243
- }
244
-
245
- function normalizeEmbedding(input) {
246
- if (!['minimax', 'openai'].includes(input.provider)) throw Object.assign(new Error('请选择支持的向量协议。'), { status: 400 });
247
- const model = String(input.model || (input.provider === 'minimax' ? 'embo-01' : 'text-embedding-3-small')).trim();
248
- if (!model || model.length > 200 || /[\x00-\x1f]/.test(model)) throw Object.assign(new Error('无效的向量模型。'), { status: 400 });
249
- let endpoint = String(input.endpoint || '').trim();
250
- if (endpoint) {
251
- let url; try { url = new URL(endpoint); } catch {}
252
- if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw Object.assign(new Error('向量接口地址无效。'), { status: 400 });
253
- // MiniMax appends /v1/embeddings itself. Only official, known route
254
- // aliases are normalized; private gateways may require their path prefix.
255
- if (input.provider === 'minimax' && ['api.minimaxi.com', 'api.minimax.io', 'api.minimax.cn', 'api.minimax.chat'].includes(url.hostname) && /^\/(?:anthropic|v1(?:\/embeddings)?)?\/?$/.test(url.pathname)) endpoint = url.origin;
256
- }
257
- return { provider: input.provider, model, endpoint, profileId: input.profileId ? cleanId(input.profileId, 'profileId') : null };
258
- }
259
-
260
- function validateProfile(profile, options = {}) {
261
- if (profile.runtime !== 'claude-code') throw Object.assign(new Error('runtime must be claude-code'), { status: 400 });
262
- if (!profile.provider) throw Object.assign(new Error('provider is required'), { status: 400 });
263
- // One protocol endpoint is enough: single-protocol providers are valid;
264
- // the agents that speak the missing protocol simply can't use it.
265
- if (!profile.baseUrl && !profile.openaiBaseUrl) {
266
- throw Object.assign(new Error('baseUrl is required'), { status: 400 });
267
- }
268
- for (const field of ['baseUrl', 'openaiBaseUrl']) {
269
- if (!profile[field]) continue;
270
- let url;
271
- try { url = new URL(profile[field]); } catch {}
272
- if (!url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
273
- throw Object.assign(new Error(`${field} must be an HTTP(S) endpoint without credentials, query, or fragment`), { status: 400 });
274
- }
275
- }
276
- // Detection runs before any model is configured; every other path needs one.
277
- if (!profile.models.default && options.requireModel !== false) {
278
- throw Object.assign(new Error('models.default is required'), { status: 400 });
279
- }
280
- return profile;
281
- }
282
-
283
- module.exports = { ProfileStore, validateProfile, maskCredential };
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const { normalizeProfile, cleanId } = require('../../contracts');
6
+ const { readJson, writeJson } = require('./json-file');
7
+
8
+ class ProfileStore {
9
+ constructor(options = {}) {
10
+ if (!options.dataDir) throw new Error('ProfileStore dataDir is required');
11
+ this.profileFile = options.profileFile || path.join(options.dataDir, 'profiles.v2.json');
12
+ this.credentialFile = options.credentialFile || path.join(options.dataDir, 'credentials.v1.json');
13
+ }
14
+
15
+ _profiles() { return readJson(this.profileFile, { schema: 'claude-workbench-profiles/v2', profiles: [] }); }
16
+ _credentials() { return readJson(this.credentialFile, { schema: 'claude-workbench-credentials/v1', credentials: {} }); }
17
+
18
+ _configured(profile) {
19
+ return Boolean(this._credentials().credentials[profile.credentialRef]);
20
+ }
21
+
22
+ publicProfile(profile) {
23
+ profile = normalizeProfile(profile);
24
+ const secret = this._credentials().credentials[profile.credentialRef] || '';
25
+ const clean = {
26
+ ...profile,
27
+ credentialConfigured: Boolean(secret),
28
+ credentialMasked: maskCredential(secret),
29
+ };
30
+ delete clean.apiKey;
31
+ delete clean.authToken;
32
+ delete clean.anthropicAuthToken;
33
+ delete clean.secret;
34
+ return clean;
35
+ }
36
+
37
+ list() { return this._profiles().profiles.map(profile => this.publicProfile(profile)); }
38
+
39
+ maintenanceDefault() {
40
+ const id = this._profiles().maintenanceDefaultProfileId || null;
41
+ return { profileId: id, profile: id ? this.get(id) : null };
42
+ }
43
+
44
+ setMaintenanceDefault(id) {
45
+ const profileId = id == null ? null : cleanId(id, 'profileId');
46
+ if (profileId) this.runtimeProfile(profileId);
47
+ const cfg = this._profiles();
48
+ cfg.maintenanceDefaultProfileId = profileId;
49
+ writeJson(this.profileFile, cfg);
50
+ return this.maintenanceDefault();
51
+ }
52
+
53
+ maintenanceRuntime() {
54
+ const { profileId } = this.maintenanceDefault();
55
+ if (!profileId) throw Object.assign(new Error('maintenance default profile is not configured'), { status: 409 });
56
+ // Always use the persisted provider default, never a session selection.
57
+ return this.runtimeProfile(profileId);
58
+ }
59
+
60
+ embeddingConfig() {
61
+ const saved = this._profiles().embedding;
62
+ if (!saved) return { configured: false, config: null };
63
+ const { credentialRef, ...config } = saved;
64
+ config.endpoint = normalizeEmbedding(saved).endpoint;
65
+ let configured = false;
66
+ try { configured = Boolean(this.embeddingRuntime()); } catch {}
67
+ return { configured, config };
68
+ }
69
+
70
+ setEmbeddingConfig(input = {}) {
71
+ const cfg = this._profiles();
72
+ if (input.enabled === false) {
73
+ const keys = this._credentials();
74
+ delete keys.credentials[cfg.embedding?.credentialRef];
75
+ writeJson(this.credentialFile, keys);
76
+ cfg.embedding = null;
77
+ } else {
78
+ const next = normalizeEmbedding(input);
79
+ if (next.profileId) this.runtimeProfile(next.profileId);
80
+ else {
81
+ next.credentialRef = 'knowledge-embedding';
82
+ const keys = this._credentials();
83
+ const secret = typeof input.secret === 'string' ? input.secret.trim() : '';
84
+ if (secret) keys.credentials[next.credentialRef] = secret;
85
+ if (!keys.credentials[next.credentialRef]) throw Object.assign(new Error('向量模型凭据未配置。'), { status: 400 });
86
+ writeJson(this.credentialFile, keys);
87
+ }
88
+ cfg.embedding = next;
89
+ }
90
+ writeJson(this.profileFile, cfg);
91
+ return this.embeddingConfig();
92
+ }
93
+
94
+ embeddingRuntime() {
95
+ const saved = this._profiles().embedding;
96
+ if (!saved) throw Object.assign(new Error('向量模型未配置。'), { status: 409 });
97
+ const secret = saved.profileId ? this.runtimeProfile(saved.profileId).apiKey : this._credentials().credentials[saved.credentialRef];
98
+ if (!secret) throw Object.assign(new Error('向量模型凭据未配置。'), { status: 409 });
99
+ return { provider: saved.provider, model: saved.model, endpoint: normalizeEmbedding(saved).endpoint, apiKey: secret };
100
+ }
101
+
102
+ importEmbedding({ migrationId, settings }) {
103
+ if (!/^embedding-[a-f0-9]{64}$/.test(migrationId || '')) throw Object.assign(new Error('无效的向量配置迁移。'), { status: 400 });
104
+ const cfg = this._profiles();
105
+ if (cfg.embeddingImports?.[migrationId]) return this.embeddingConfig();
106
+ const backup = path.join(path.dirname(this.profileFile), 'recovery', migrationId);
107
+ fs.mkdirSync(backup, { recursive: true, mode: 0o700 });
108
+ for (const file of [this.profileFile, this.credentialFile]) {
109
+ const target = path.join(backup, path.basename(file));
110
+ if (fs.existsSync(file) && !fs.existsSync(target)) { fs.copyFileSync(file, target, fs.constants.COPYFILE_EXCL); fs.chmodSync(target, 0o600); }
111
+ }
112
+ // An existing Workbench choice wins. The caller keeps its own rollback
113
+ // backup before removing the retired, module-local active credential.
114
+ if (!cfg.embedding) this.setEmbeddingConfig({ ...settings, secret: settings?.apiKey });
115
+ const next = this._profiles();
116
+ next.embeddingImports = { ...next.embeddingImports, [migrationId]: true };
117
+ writeJson(this.profileFile, next);
118
+ return this.embeddingConfig();
119
+ }
120
+
121
+ importLegacy({ migrationId, profiles, defaultProfileId }) {
122
+ if (!/^cutover-[a-f0-9-]{36}$/.test(migrationId || '') || !Array.isArray(profiles)) throw Object.assign(new Error('invalid profile migration'), { status: 400 });
123
+ const current = this._profiles();
124
+ if (current.migrationImports?.[migrationId]) return current.migrationImports[migrationId];
125
+ const prepared = profiles.map(raw => {
126
+ const id = `legacy-${cleanId(raw.id, 'profileId')}`;
127
+ if (this.get(id)) throw Object.assign(new Error('legacy profile identity conflicts with existing configuration'), { status: 409 });
128
+ const profile = normalizeProfile({ id, name: raw.name || raw.id, provider: raw.provider || 'anthropic-compatible', baseUrl: raw.baseUrl || raw.anthropicBaseUrl, openaiBaseUrl: raw.openaiBaseUrl, enabled: raw.enabled !== false, models: raw.models || { default: raw.mainModel || raw.model, reasoning: raw.thinkingModel, fast: raw.haikuModel, coding: raw.sonnetModel, largeContext: raw.opusModel } });
129
+ validateProfile(profile);
130
+ return { sourceId: raw.id, profile, secret: raw.apiKey || raw.anthropicApiKey || raw.authToken || raw.anthropicAuthToken || '' };
131
+ });
132
+ const backup = path.join(path.dirname(this.profileFile), 'recovery', migrationId);
133
+ fs.mkdirSync(backup, { recursive: true, mode: 0o700 });
134
+ for (const file of [this.profileFile, this.credentialFile]) {
135
+ const target = path.join(backup, path.basename(file));
136
+ if (fs.existsSync(file) && !fs.existsSync(target)) { fs.copyFileSync(file, target, fs.constants.COPYFILE_EXCL); fs.chmodSync(target, 0o600); }
137
+ }
138
+ const mapping = {};
139
+ const nextProfiles = current;
140
+ const nextCredentials = this._credentials();
141
+ for (const item of prepared) {
142
+ mapping[item.sourceId] = item.profile.id;
143
+ nextProfiles.profiles.push(item.profile);
144
+ if (item.secret) nextCredentials.credentials[item.profile.credentialRef] = String(item.secret);
145
+ }
146
+ // Write keys first: a crash may leave an unused credential, never a profile
147
+ // silently bound to a missing/different secret. Retrying uses the same map.
148
+ writeJson(this.credentialFile, nextCredentials);
149
+ const preferred = prepared.find(item => item.sourceId === defaultProfileId && item.secret && item.profile.enabled) || prepared.find(item => item.secret && item.profile.enabled);
150
+ if (!nextProfiles.maintenanceDefaultProfileId && preferred) nextProfiles.maintenanceDefaultProfileId = preferred.profile.id;
151
+ nextProfiles.migrationImports = { ...nextProfiles.migrationImports, [migrationId]: mapping };
152
+ writeJson(this.profileFile, nextProfiles);
153
+ return mapping;
154
+ }
155
+
156
+ get(id) {
157
+ const profileId = cleanId(id, 'profileId');
158
+ const profile = this._profiles().profiles.find(item => item.id === profileId);
159
+ return profile ? this.publicProfile(profile) : null;
160
+ }
161
+
162
+ save(input, idOverride) {
163
+ const profile = normalizeProfile(input, idOverride);
164
+ validateProfile(profile);
165
+ const cfg = this._profiles();
166
+ const index = cfg.profiles.findIndex(item => item.id === profile.id);
167
+ if (index >= 0) cfg.profiles[index] = profile;
168
+ else cfg.profiles.push(profile);
169
+ writeJson(this.profileFile, cfg);
170
+ return this.publicProfile(profile);
171
+ }
172
+
173
+ delete(id) {
174
+ const profileId = cleanId(id, 'profileId');
175
+ const cfg = this._profiles();
176
+ const profile = cfg.profiles.find(item => item.id === profileId);
177
+ if (!profile) return false;
178
+ cfg.profiles = cfg.profiles.filter(item => item.id !== profileId);
179
+ if (cfg.maintenanceDefaultProfileId === profileId) cfg.maintenanceDefaultProfileId = null;
180
+ writeJson(this.profileFile, cfg);
181
+ const secrets = this._credentials();
182
+ delete secrets.credentials[profile.credentialRef];
183
+ writeJson(this.credentialFile, secrets);
184
+ return true;
185
+ }
186
+
187
+ setCredential(id, credential) {
188
+ const profileId = cleanId(id, 'profileId');
189
+ const cfg = this._profiles();
190
+ const profile = cfg.profiles.find(item => item.id === profileId);
191
+ if (!profile) throw Object.assign(new Error('profile not found'), { status: 404 });
192
+ const secret = typeof credential === 'string' ? credential : credential && credential.secret;
193
+ if (!secret || typeof secret !== 'string') {
194
+ throw Object.assign(new Error('credential secret is required'), { status: 400 });
195
+ }
196
+ const secrets = this._credentials();
197
+ secrets.credentials[profile.credentialRef] = String(secret);
198
+ writeJson(this.credentialFile, secrets);
199
+ }
200
+
201
+ runtimeProfile(id) {
202
+ const profileId = cleanId(id, 'profileId');
203
+ const profile = this._profiles().profiles.find(item => item.id === profileId);
204
+ if (!profile) throw Object.assign(new Error('profile not found'), { status: 404 });
205
+ if (!profile.enabled) throw Object.assign(new Error('profile is disabled'), { status: 400 });
206
+ const secret = this._credentials().credentials[profile.credentialRef];
207
+ if (!secret) throw Object.assign(new Error('profile credential is not configured'), { status: 400 });
208
+ return runtimeShape(profile, secret);
209
+ }
210
+
211
+ runtimeDraft(input, credential, options = {}) {
212
+ const profile = normalizeProfile(input);
213
+ validateProfile(profile, options);
214
+ if (!profile.enabled) throw Object.assign(new Error('profile is disabled'), { status: 400 });
215
+ let secret = typeof credential === 'string' ? credential : credential && credential.secret;
216
+ if (!secret) {
217
+ const saved = this._profiles().profiles.find(item => item.id === profile.id);
218
+ if (saved) secret = this._credentials().credentials[saved.credentialRef];
219
+ }
220
+ if (!secret) throw Object.assign(new Error('profile credential is not configured'), { status: 400 });
221
+ return runtimeShape(profile, String(secret));
222
+ }
223
+ }
224
+
225
+ function runtimeShape(profile, secret) {
226
+ profile = normalizeProfile(profile);
227
+ return {
228
+ ...profile,
229
+ apiKey: secret,
230
+ mainModel: profile.models.default,
231
+ thinkingModel: profile.models.reasoning || profile.models.default,
232
+ haikuModel: profile.models.fast || profile.models.default,
233
+ sonnetModel: profile.models.coding || profile.models.default,
234
+ opusModel: profile.models.largeContext || profile.models.default,
235
+ };
236
+ }
237
+
238
+ function maskCredential(secret) {
239
+ const value = String(secret || '');
240
+ if (!value) return '';
241
+ if (value.length <= 12) return `${value.slice(0, 2)}****${value.slice(-2)}`;
242
+ return `${value.slice(0, 6)}****${value.slice(-6)}`;
243
+ }
244
+
245
+ function normalizeEmbedding(input) {
246
+ if (!['minimax', 'openai'].includes(input.provider)) throw Object.assign(new Error('请选择支持的向量协议。'), { status: 400 });
247
+ const model = String(input.model || (input.provider === 'minimax' ? 'embo-01' : 'text-embedding-3-small')).trim();
248
+ if (!model || model.length > 200 || /[\x00-\x1f]/.test(model)) throw Object.assign(new Error('无效的向量模型。'), { status: 400 });
249
+ let endpoint = String(input.endpoint || '').trim();
250
+ if (endpoint) {
251
+ let url; try { url = new URL(endpoint); } catch {}
252
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw Object.assign(new Error('向量接口地址无效。'), { status: 400 });
253
+ // MiniMax appends /v1/embeddings itself. Only official, known route
254
+ // aliases are normalized; private gateways may require their path prefix.
255
+ if (input.provider === 'minimax' && ['api.minimaxi.com', 'api.minimax.io', 'api.minimax.cn', 'api.minimax.chat'].includes(url.hostname) && /^\/(?:anthropic|v1(?:\/embeddings)?)?\/?$/.test(url.pathname)) endpoint = url.origin;
256
+ }
257
+ return { provider: input.provider, model, endpoint, profileId: input.profileId ? cleanId(input.profileId, 'profileId') : null };
258
+ }
259
+
260
+ function validateProfile(profile, options = {}) {
261
+ if (profile.runtime !== 'claude-code') throw Object.assign(new Error('runtime must be claude-code'), { status: 400 });
262
+ if (!profile.provider) throw Object.assign(new Error('provider is required'), { status: 400 });
263
+ // One protocol endpoint is enough: single-protocol providers are valid;
264
+ // the agents that speak the missing protocol simply can't use it.
265
+ if (!profile.baseUrl && !profile.openaiBaseUrl) {
266
+ throw Object.assign(new Error('baseUrl is required'), { status: 400 });
267
+ }
268
+ for (const field of ['baseUrl', 'openaiBaseUrl']) {
269
+ if (!profile[field]) continue;
270
+ let url;
271
+ try { url = new URL(profile[field]); } catch {}
272
+ if (!url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
273
+ throw Object.assign(new Error(`${field} must be an HTTP(S) endpoint without credentials, query, or fragment`), { status: 400 });
274
+ }
275
+ }
276
+ // Detection runs before any model is configured; every other path needs one.
277
+ if (!profile.models.default && options.requireModel !== false) {
278
+ throw Object.assign(new Error('models.default is required'), { status: 400 });
279
+ }
280
+ return profile;
281
+ }
282
+
283
+ module.exports = { ProfileStore, validateProfile, maskCredential };