@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.
- package/LICENSE +201 -201
- package/README.md +156 -156
- package/apps/agent-terminal/app.css +652 -613
- package/apps/agent-terminal/app.js +143 -67
- package/apps/agent-terminal/conversation-composer.js +44 -0
- package/apps/agent-terminal/index.html +172 -170
- package/apps/agent-terminal/panel-host-proof.html +152 -152
- package/apps/agent-terminal/panel-proof-content.html +41 -41
- package/apps/agent-terminal/right-workspace-dock.css +189 -159
- package/apps/agent-terminal/right-workspace-dock.js +652 -521
- package/apps/agent-terminal/user-question-card.js +68 -0
- package/apps/ai-profile-settings-host/index.html +25 -25
- package/apps/ai-profile-settings-host/page.css +1 -1
- package/apps/ai-profile-settings-host/page.js +113 -113
- package/apps/minimal-test-host/README.md +15 -15
- package/apps/minimal-test-host/host.css +2 -2
- package/apps/minimal-test-host/host.js +35 -35
- package/apps/minimal-test-host/index.html +58 -58
- package/apps/minimal-test-host/optional-mock/fault-injection.js +15 -15
- package/docs/sdk/FILE_LAYOUT.md +31 -31
- package/docs/sdk/INTEGRATION.md +126 -126
- package/docs/sdk/README.md +21 -21
- package/docs/sdk/SESSION_EVENTS.md +15 -13
- package/docs/sdk/openapi.yaml +16 -1
- package/package.json +1 -1
- package/packages/client/README.md +29 -29
- package/packages/client/index.d.ts +122 -122
- package/packages/client/index.js +260 -260
- package/packages/client/package.json +2 -2
- package/packages/contracts/README.md +9 -9
- package/packages/contracts/index.d.ts +519 -517
- package/packages/contracts/index.js +312 -312
- package/packages/contracts/package.json +1 -1
- package/packages/core/README.md +8 -8
- package/packages/core/index.d.ts +76 -76
- package/packages/core/index.js +222 -222
- package/packages/core/package.json +2 -2
- package/packages/server/README.md +17 -17
- package/packages/server/bin/agent-terminal-server.js +42 -42
- package/packages/server/bin/claude-workbench.js +225 -225
- package/packages/server/index.d.ts +171 -171
- package/packages/server/index.js +230 -230
- package/packages/server/lib/agent-discovery.js +133 -133
- package/packages/server/lib/agent-registry.js +143 -143
- package/packages/server/lib/agent-spawn-env.js +17 -17
- package/packages/server/lib/attachment-store.js +78 -78
- package/packages/server/lib/bridges/app-server-bridge.js +373 -373
- package/packages/server/lib/bridges/opencode-server-bridge.js +506 -506
- package/packages/server/lib/capture-settings-store.js +35 -35
- package/packages/server/lib/claude-history-recovery.js +87 -87
- package/packages/server/lib/cli-session-recovery.js +28 -28
- package/packages/server/lib/context-resolver.js +55 -55
- package/packages/server/lib/conversation-capture.js +51 -51
- package/packages/server/lib/delegation-phase-store.js +357 -357
- package/packages/server/lib/delegation-store.js +474 -468
- package/packages/server/lib/diagnostics.js +32 -32
- package/packages/server/lib/drivers/cli-json-runner.js +974 -974
- package/packages/server/lib/drivers/codex-driver.js +1461 -1442
- package/packages/server/lib/drivers/opencode-driver.js +1554 -1554
- package/packages/server/lib/drivers/zcode-driver.js +1250 -1250
- package/packages/server/lib/drivers/zcode-profile-runtime.js +71 -71
- package/packages/server/lib/event-stream.js +138 -138
- package/packages/server/lib/folder-picker.js +623 -623
- package/packages/server/lib/http-handler.js +339 -339
- package/packages/server/lib/json-file.js +26 -26
- package/packages/server/lib/knowledge-context.js +33 -33
- package/packages/server/lib/model-detection.js +295 -295
- package/packages/server/lib/parent-context.js +44 -0
- package/packages/server/lib/profile-store.js +283 -283
- package/packages/server/lib/project-store.js +102 -102
- package/packages/server/lib/runtime-loader.js +120 -120
- package/packages/server/lib/session-archive-store.js +53 -53
- package/packages/server/lib/session-history.js +612 -612
- package/packages/server/lib/system-doctor.js +125 -125
- package/packages/server/lib/ui-preferences-store.js +48 -48
- package/packages/server/lib/user-questions.js +67 -0
- package/packages/server/lib/workbench-service.js +1696 -1675
- package/packages/server/package.json +2 -2
- package/packages/ui/README.md +30 -30
- package/packages/ui/ai-profile-settings.d.ts +45 -45
- package/packages/ui/ai-profile-settings.js +283 -283
- package/packages/ui/claude-terminal.d.ts +31 -31
- package/packages/ui/claude-terminal.js +343 -343
- package/packages/ui/index.d.ts +18 -18
- package/packages/ui/index.js +51 -51
- package/packages/ui/package.json +2 -2
- package/packages/ui/theme.css +13 -13
- package/src/assets/claude-prompts.json +21 -21
- package/src/backend/http/ai-profile-routes.js +61 -61
- package/src/backend/http/claude-routes.js +170 -170
- package/src/backend/http/node-helpers.js +45 -45
- package/src/backend/index.js +21 -21
- package/src/backend/lib/ai-adapter.js +144 -144
- package/src/backend/lib/ai-profile-store.js +259 -259
- package/src/backend/lib/ai-vendor-presets.js +83 -83
- package/src/backend/lib/ai-workspace.js +140 -140
- package/src/backend/lib/automation-config.js +253 -253
- package/src/backend/lib/claude-cli-runner.js +2408 -2392
- package/src/backend/lib/data-dir.js +169 -169
- package/src/backend/lib/llm-client.js +176 -176
- package/src/backend/lib/model-context-windows.js +82 -82
- package/src/backend/lib/native-task-control.js +217 -217
- package/src/backend/lib/native-task-history-index.js +475 -475
- package/src/backend/lib/native-task-history-reader.js +526 -526
- package/src/backend/lib/native-task-messages.js +457 -457
- package/src/backend/lib/native-task-registry.js +325 -325
- package/src/backend/lib/native-task-runtime.js +242 -242
- package/src/backend/lib/native-task-trace.js +440 -440
- package/src/backend/lib/native-task-transcript.js +393 -393
- package/src/backend/lib/prompt-registry.js +166 -166
- package/src/backend/lib/runtime-config.js +121 -121
- package/src/backend/lib/sdk-session-stream.js +143 -143
- package/src/backend/lib/sdk-turn-stream.js +16 -16
- package/src/backend/lib/store-scope.js +131 -131
- package/src/backend/lib/task-identity.js +104 -104
- package/src/backend/lib/task-state-projection.js +58 -58
- package/src/index.js +7 -7
- package/src/sdk-wave-a.ts +1 -1
- package/src/sdk-wave-b.ts +1 -1
- package/src/sdk-wave-c.ts +1 -1
- package/src/sdk-wave-d.ts +1 -1
- package/src/sdk-wave-e.ts +1 -1
package/packages/server/index.js
CHANGED
|
@@ -1,230 +1,230 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const http = require('http');
|
|
4
|
-
const fs = require('fs');
|
|
5
|
-
const path = require('path');
|
|
6
|
-
const { loadLegacyRuntime } = require('./lib/runtime-loader');
|
|
7
|
-
const { configureWorkbench } = loadLegacyRuntime('runtime-config');
|
|
8
|
-
const { getDataDir } = loadLegacyRuntime('data-dir');
|
|
9
|
-
const { DEFAULT_API_PREFIX } = require('../contracts');
|
|
10
|
-
const { ProfileStore } = require('./lib/profile-store');
|
|
11
|
-
const { CaptureSettingsStore } = require('./lib/capture-settings-store');
|
|
12
|
-
const { UiPreferencesStore } = require('./lib/ui-preferences-store');
|
|
13
|
-
const { ContextResolver } = require('./lib/context-resolver');
|
|
14
|
-
const { WorkbenchService } = require('./lib/workbench-service');
|
|
15
|
-
const { AttachmentStore } = require('./lib/attachment-store');
|
|
16
|
-
const { ProjectStore } = require('./lib/project-store');
|
|
17
|
-
const { SessionArchiveStore } = require('./lib/session-archive-store');
|
|
18
|
-
const { AgentRegistry } = require('./lib/agent-registry');
|
|
19
|
-
const { createAgentDiscovery, probeExecutableAsync, resolveClaudeAsync, resolveZCodeAsync } = require('./lib/agent-discovery');
|
|
20
|
-
const { createDiagnostics } = require('./lib/diagnostics');
|
|
21
|
-
const { createSystemDoctor } = require('./lib/system-doctor');
|
|
22
|
-
const { createModelDetection } = require('./lib/model-detection');
|
|
23
|
-
const { createCodexDriver } = require('./lib/drivers/codex-driver');
|
|
24
|
-
const { createOpenCodeDriver } = require('./lib/drivers/opencode-driver');
|
|
25
|
-
const { createZCodeDriver } = require('./lib/drivers/zcode-driver');
|
|
26
|
-
const { createDelegationStore } = require('./lib/delegation-store');
|
|
27
|
-
const { createDelegationPhaseStore } = require('./lib/delegation-phase-store');
|
|
28
|
-
const { createHttpHandler } = require('./lib/http-handler');
|
|
29
|
-
|
|
30
|
-
function createWorkbenchServer(options = {}) {
|
|
31
|
-
if (options.dataDir) configureWorkbench({ dataDir: options.dataDir });
|
|
32
|
-
const dataDir = path.resolve(options.dataDir || getDataDir());
|
|
33
|
-
const storeIdentity = loadLegacyRuntime('store-scope').ensureStoreScope(dataDir);
|
|
34
|
-
const apiPrefix = options.apiPrefix || DEFAULT_API_PREFIX;
|
|
35
|
-
const testRoot = path.join(dataDir, 'test-workspaces');
|
|
36
|
-
const projects = options.projects || new ProjectStore({ dataDir });
|
|
37
|
-
require('./lib/cli-session-recovery').recoverOwnedCliSessions({ dataDir, projects });
|
|
38
|
-
const sessionArchive = options.sessionArchive || new SessionArchiveStore({ dataDir });
|
|
39
|
-
const workspaces = {
|
|
40
|
-
'test-workspace-a': path.join(testRoot, 'context-a'),
|
|
41
|
-
'test-workspace-b': path.join(testRoot, 'context-b'),
|
|
42
|
-
'test-workspace-c': path.join(testRoot, 'context-c'),
|
|
43
|
-
...(options.workspaces || {}),
|
|
44
|
-
...projects.toWorkspaceMap(),
|
|
45
|
-
};
|
|
46
|
-
const profiles = options.profiles || new ProfileStore({ dataDir });
|
|
47
|
-
const bridgeUrl = options.bridgeUrl || process.env.KB_EVENT_BRIDGE_URL;
|
|
48
|
-
const runtimeToken = options.runtimeToken || process.env.KB_WORKBENCH_RUNTIME_TOKEN;
|
|
49
|
-
const conversationCapture = options.conversationCapture || (bridgeUrl && runtimeToken ? new (require('./lib/conversation-capture').ConversationCapture)({ file: path.join(dataDir, 'capture-outbox.v1.json'), bridgeUrl, token: runtimeToken }) : null);
|
|
50
|
-
const captureSettings = options.captureSettings || new CaptureSettingsStore({ dataDir, defaultConversations: !!conversationCapture });
|
|
51
|
-
const uiPreferences = options.uiPreferences || new UiPreferencesStore({ dataDir });
|
|
52
|
-
const attachments = options.attachments || new AttachmentStore({ root: path.join(dataDir, 'attachments') });
|
|
53
|
-
const contexts = options.contexts || new ContextResolver({ workspaces, createMissing: options.createMissingWorkspaces !== false });
|
|
54
|
-
const claudeDriver = options.runner || loadLegacyRuntime('claude-cli-runner');
|
|
55
|
-
const knowledgeContextProvided = Boolean(options.knowledge || options.engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL);
|
|
56
|
-
claudeDriver.setKnowledgeContextProvided?.(knowledgeContextProvided);
|
|
57
|
-
// Bridge capture scope: terminal sessions are exempt from Development
|
|
58
|
-
// Conversation capture unless the 会话捕获 setting says otherwise. Applied to
|
|
59
|
-
// the driver at boot and re-applied on every settings save.
|
|
60
|
-
const applyBridgeCapture = enabled => {
|
|
61
|
-
if (claudeDriver && typeof claudeDriver.setBridgeCaptureConversation === 'function') {
|
|
62
|
-
// Native capture records the original input, not the augmented SDK
|
|
63
|
-
// prompt. Suppress inherited CLI hooks to avoid duplicate capture.
|
|
64
|
-
claudeDriver.setBridgeCaptureConversation(conversationCapture ? false : enabled);
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
applyBridgeCapture(captureSettings.read().terminalConversations);
|
|
68
|
-
const registry = options.registry || new AgentRegistry({
|
|
69
|
-
drivers: {
|
|
70
|
-
'claude-code': claudeDriver,
|
|
71
|
-
...(options.drivers || {
|
|
72
|
-
codex: createCodexDriver({ knowledgeContextProvided, conversationCaptureProvided: Boolean(conversationCapture), persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
73
|
-
opencode: createOpenCodeDriver({ persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
74
|
-
zcode: createZCodeDriver({ knowledgeContextProvided, conversationCaptureProvided: Boolean(conversationCapture), persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
75
|
-
}),
|
|
76
|
-
},
|
|
77
|
-
});
|
|
78
|
-
const runner = registry.asRunner();
|
|
79
|
-
const diagnostics = options.logger || createDiagnostics({ dataDir, secrets: () => [...Object.values(profiles._credentials().credentials), process.env.ANTHROPIC_API_KEY, process.env.ANTHROPIC_AUTH_TOKEN] });
|
|
80
|
-
const agentDiscovery = options.agentDiscovery || createAgentDiscovery({
|
|
81
|
-
claudeProbe: async ({ signal } = {}) => {
|
|
82
|
-
try {
|
|
83
|
-
const executable = await resolveClaudeAsync(claudeDriver, { signal });
|
|
84
|
-
// Handle both shapes: the legacy runner returns {cmd}, test doubles
|
|
85
|
-
// may return a plain string. No usable executable -> not available.
|
|
86
|
-
const cmd = typeof executable === 'string'
|
|
87
|
-
? executable
|
|
88
|
-
: executable && executable.cmd;
|
|
89
|
-
if (!cmd) {
|
|
90
|
-
const reason = executable?.reason || '未发现可用的 Claude Code 启动文件。';
|
|
91
|
-
diagnostics.error('agent.discovery.failed', 'Claude Code 不可用。', { phase: 'discovery', error: { code: 'CLAUDE_EXECUTABLE_NOT_FOUND', message: reason }, context: { agent: 'claude-code', rejectedPaths: executable?.rejected || [] } });
|
|
92
|
-
return { available: false, version: null, reason };
|
|
93
|
-
}
|
|
94
|
-
// Honest probe: spawn the resolved executable with --version. Same
|
|
95
|
-
// contract as every other agent: no version, no availability claim.
|
|
96
|
-
const probe = await probeExecutableAsync(cmd, { signal });
|
|
97
|
-
if (!probe.available) diagnostics.error('agent.discovery.failed', 'Claude Code 版本探测失败。', { phase: 'version-probe', error: { code: probe.code, message: probe.reason }, context: { agent: 'claude-code', executable: cmd, exitCode: probe.exitCode } });
|
|
98
|
-
else if (executable.rejected?.length) diagnostics.warn('agent.discovery.recovered', '已跳过失效的 Claude Code 启动路径,使用有效安装。', { phase: 'discovery', context: { executable: cmd, rejectedPaths: executable.rejected } });
|
|
99
|
-
return probe;
|
|
100
|
-
} catch { return { available: false, version: null }; }
|
|
101
|
-
},
|
|
102
|
-
});
|
|
103
|
-
const modelContextWindows = options.modelContextWindows || safeLoad('model-context-windows');
|
|
104
|
-
const modelDetection = options.modelDetection || createModelDetection({
|
|
105
|
-
contextLookup: modelContextWindows && modelContextWindows.lookupContextWindow,
|
|
106
|
-
});
|
|
107
|
-
const collectDoctor = options.doctor || createSystemDoctor({
|
|
108
|
-
resolveClaudeExecutable: async () => {
|
|
109
|
-
try { return await resolveClaudeAsync(claudeDriver); } catch { return { cmd: null }; }
|
|
110
|
-
},
|
|
111
|
-
discoverZCodeCli: () => resolveZCodeAsync(),
|
|
112
|
-
});
|
|
113
|
-
const doctor = async () => {
|
|
114
|
-
const report = await collectDoctor();
|
|
115
|
-
const claude = report.agents?.['claude-code'];
|
|
116
|
-
if (claude && !claude.versionProbe?.ok) diagnostics.error('agent.doctor.failed', 'Claude Code 环境诊断失败。', { phase: 'doctor', error: { code: 'CLAUDE_PROBE_FAILED', message: claude.versionProbe?.error || claude.resolutionReason }, context: { agent: 'claude-code', executable: claude.resolvedExecutable, rejectedPaths: claude.rejectedPaths, exitCode: claude.versionProbe?.exitCode } });
|
|
117
|
-
return report;
|
|
118
|
-
};
|
|
119
|
-
const service = options.service || new WorkbenchService({
|
|
120
|
-
knowledge: options.knowledge || new (require('./lib/knowledge-context').KnowledgeContext)({ engineUrl: options.engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL, contextFile: path.join(dataDir, 'knowledge-contexts.v1.json') }),
|
|
121
|
-
runner, profiles, contexts, attachments, apiPrefix, diagnostics,
|
|
122
|
-
resolveRuntimeExecutable: () => resolveClaudeAsync(claudeDriver),
|
|
123
|
-
projects, sessionArchive, agentDiscovery, modelContextWindows, modelDetection,
|
|
124
|
-
archiveRetentionDays: options.archiveRetentionDays,
|
|
125
|
-
captureSettings, uiPreferences, onCaptureSettingsSaved: applyBridgeCapture,
|
|
126
|
-
conversationCapture,
|
|
127
|
-
testWorkspace: path.join(testRoot, 'profile-test'), auditFile: path.join(dataDir, 'audit.jsonl'),
|
|
128
|
-
version: options.version || require('./package.json').version,
|
|
129
|
-
maxSessions: options.maxSessions, maxConcurrentRuns: options.maxConcurrentRuns,
|
|
130
|
-
storeIdentity,
|
|
131
|
-
delegations: buildDelegationStores(dataDir, storeIdentity, options),
|
|
132
|
-
});
|
|
133
|
-
const handleApi = createHttpHandler(service, { apiPrefix, corsOrigin: options.corsOrigin, doctor, runtimeToken: options.runtimeToken || process.env.KB_WORKBENCH_RUNTIME_TOKEN });
|
|
134
|
-
const distributionRoot = resolveDistributionRoot();
|
|
135
|
-
const staticRoot = path.resolve(options.staticRoot || path.join(distributionRoot, 'apps', 'minimal-test-host'));
|
|
136
|
-
const profileSettingsRoot = path.resolve(options.profileSettingsRoot || path.join(distributionRoot, 'apps', 'ai-profile-settings-host'));
|
|
137
|
-
const agentTerminalRoot = path.resolve(options.agentTerminalRoot || path.join(distributionRoot, 'apps', 'agent-terminal'));
|
|
138
|
-
const packagesRoot = path.join(distributionRoot, 'packages');
|
|
139
|
-
const server = http.createServer(async (req, res) => {
|
|
140
|
-
if (await handleApi(req, res)) return;
|
|
141
|
-
if (options.serveHost !== false && servePackageAsset(req, res, packagesRoot)) return;
|
|
142
|
-
if (options.serveHost !== false && serveAppStatic(req, res, '/profile-settings/', profileSettingsRoot)) return;
|
|
143
|
-
if (options.serveHost !== false && serveAppStatic(req, res, '/agent-terminal/', agentTerminalRoot)) return;
|
|
144
|
-
if (options.serveHost !== false && serveStatic(req, res, staticRoot)) return;
|
|
145
|
-
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
146
|
-
res.end(JSON.stringify({ ok: false, error: 'not found' }));
|
|
147
|
-
});
|
|
148
|
-
server.on('close', () => { agentDiscovery.close?.(); Promise.resolve(service.destroy()).catch(error => diagnostics.error('agent.shutdown.failed', '客户端运行环境关闭失败。', { phase: 'shutdown', error: { code: error.code || 'SHUTDOWN_FAILED', message: error.message } })); });
|
|
149
|
-
return { server, service, profiles, contexts, attachments, projects, sessionArchive, registry, agentDiscovery, apiPrefix, dataDir };
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function safeLoad(name) {
|
|
153
|
-
try { return loadLegacyRuntime(name); } catch { return null; }
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Delegation stores bind to the SAME durable store identity as native-task
|
|
157
|
-
// scopes; without one the delegation APIs answer explicit unavailability.
|
|
158
|
-
function buildDelegationStores(dataDir, storeIdentity, options) {
|
|
159
|
-
if (options.delegations) return options.delegations;
|
|
160
|
-
if (!storeIdentity || storeIdentity.available !== true || !storeIdentity.storeScope) return null;
|
|
161
|
-
const root = path.join(dataDir, 'delegations');
|
|
162
|
-
return {
|
|
163
|
-
ledger: createDelegationStore({ root, storeScope: storeIdentity.storeScope }),
|
|
164
|
-
phases: createDelegationPhaseStore({ root, storeScope: storeIdentity.storeScope }),
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
function resolveDistributionRoot() {
|
|
169
|
-
// A source checkout must win over whatever unrelated 'claude-ai-workbench'
|
|
170
|
-
// package require.resolve happens to find on this machine (an old copy in
|
|
171
|
-
// the user's home node_modules once shadowed this tree and served a stale
|
|
172
|
-
// agent-terminal). Only trust require.resolve when this file is not running
|
|
173
|
-
// from a checkout of the monorepo itself.
|
|
174
|
-
const sourceRoot = path.resolve(__dirname, '..', '..');
|
|
175
|
-
try {
|
|
176
|
-
const manifest = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8'));
|
|
177
|
-
if (manifest && manifest.name === '@sanqianx/claude-ai-workbench') return sourceRoot;
|
|
178
|
-
} catch { /* not a source layout: fall through */ }
|
|
179
|
-
try { return path.dirname(require.resolve('claude-ai-workbench/package.json')); }
|
|
180
|
-
catch { return sourceRoot; }
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function servePackageAsset(req, res, packagesRoot) {
|
|
184
|
-
const url = new URL(req.url, 'http://127.0.0.1');
|
|
185
|
-
if (req.method !== 'GET' || !url.pathname.startsWith('/packages/')) return false;
|
|
186
|
-
const relative = decodeURIComponent(url.pathname.slice('/packages/'.length));
|
|
187
|
-
const file = path.resolve(packagesRoot, relative);
|
|
188
|
-
if (!file.startsWith(`${packagesRoot}${path.sep}`) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
189
|
-
const type = path.extname(file) === '.css' ? 'text/css' : 'text/javascript';
|
|
190
|
-
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
191
|
-
fs.createReadStream(file).pipe(res); return true;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
function serveStatic(req, res, root) {
|
|
195
|
-
const url = new URL(req.url, 'http://127.0.0.1');
|
|
196
|
-
if (!['GET', 'HEAD'].includes(req.method)) return false;
|
|
197
|
-
let pathname = decodeURIComponent(url.pathname);
|
|
198
|
-
if (pathname === '/') { res.writeHead(302, { Location: '/agent-terminal/' }); res.end(); return true; }
|
|
199
|
-
if (!pathname.startsWith('/test-host/')) return false;
|
|
200
|
-
const relative = pathname.slice('/test-host/'.length) || 'index.html';
|
|
201
|
-
const file = path.resolve(root, relative);
|
|
202
|
-
if (file !== root && !file.startsWith(`${root}${path.sep}`)) return false;
|
|
203
|
-
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
204
|
-
const type = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml' }[path.extname(file)] || 'application/octet-stream';
|
|
205
|
-
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
206
|
-
if (req.method === 'HEAD') res.end(); else fs.createReadStream(file).pipe(res);
|
|
207
|
-
return true;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
function serveAppStatic(req, res, urlPrefix, root) {
|
|
211
|
-
const url = new URL(req.url, 'http://127.0.0.1');
|
|
212
|
-
if (!['GET', 'HEAD'].includes(req.method)) return false;
|
|
213
|
-
if (url.pathname === urlPrefix.slice(0, -1)) { res.writeHead(302, { Location: urlPrefix }); res.end(); return true; }
|
|
214
|
-
if (!url.pathname.startsWith(urlPrefix)) return false;
|
|
215
|
-
const relative = decodeURIComponent(url.pathname.slice(urlPrefix.length)) || 'index.html';
|
|
216
|
-
const file = path.resolve(root, relative);
|
|
217
|
-
if (file !== root && !file.startsWith(`${root}${path.sep}`)) return false;
|
|
218
|
-
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
219
|
-
const type = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml' }[path.extname(file)] || 'application/octet-stream';
|
|
220
|
-
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
221
|
-
if (req.method === 'HEAD') res.end(); else fs.createReadStream(file).pipe(res);
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
module.exports = {
|
|
226
|
-
createWorkbenchServer, ProfileStore, CaptureSettingsStore, ContextResolver, AttachmentStore, WorkbenchService, createHttpHandler,
|
|
227
|
-
ProjectStore, SessionArchiveStore, AgentRegistry, createAgentDiscovery, UiPreferencesStore,
|
|
228
|
-
createCodexDriver, createOpenCodeDriver, createZCodeDriver,
|
|
229
|
-
createDelegationStore, createDelegationPhaseStore,
|
|
230
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const http = require('http');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { loadLegacyRuntime } = require('./lib/runtime-loader');
|
|
7
|
+
const { configureWorkbench } = loadLegacyRuntime('runtime-config');
|
|
8
|
+
const { getDataDir } = loadLegacyRuntime('data-dir');
|
|
9
|
+
const { DEFAULT_API_PREFIX } = require('../contracts');
|
|
10
|
+
const { ProfileStore } = require('./lib/profile-store');
|
|
11
|
+
const { CaptureSettingsStore } = require('./lib/capture-settings-store');
|
|
12
|
+
const { UiPreferencesStore } = require('./lib/ui-preferences-store');
|
|
13
|
+
const { ContextResolver } = require('./lib/context-resolver');
|
|
14
|
+
const { WorkbenchService } = require('./lib/workbench-service');
|
|
15
|
+
const { AttachmentStore } = require('./lib/attachment-store');
|
|
16
|
+
const { ProjectStore } = require('./lib/project-store');
|
|
17
|
+
const { SessionArchiveStore } = require('./lib/session-archive-store');
|
|
18
|
+
const { AgentRegistry } = require('./lib/agent-registry');
|
|
19
|
+
const { createAgentDiscovery, probeExecutableAsync, resolveClaudeAsync, resolveZCodeAsync } = require('./lib/agent-discovery');
|
|
20
|
+
const { createDiagnostics } = require('./lib/diagnostics');
|
|
21
|
+
const { createSystemDoctor } = require('./lib/system-doctor');
|
|
22
|
+
const { createModelDetection } = require('./lib/model-detection');
|
|
23
|
+
const { createCodexDriver } = require('./lib/drivers/codex-driver');
|
|
24
|
+
const { createOpenCodeDriver } = require('./lib/drivers/opencode-driver');
|
|
25
|
+
const { createZCodeDriver } = require('./lib/drivers/zcode-driver');
|
|
26
|
+
const { createDelegationStore } = require('./lib/delegation-store');
|
|
27
|
+
const { createDelegationPhaseStore } = require('./lib/delegation-phase-store');
|
|
28
|
+
const { createHttpHandler } = require('./lib/http-handler');
|
|
29
|
+
|
|
30
|
+
function createWorkbenchServer(options = {}) {
|
|
31
|
+
if (options.dataDir) configureWorkbench({ dataDir: options.dataDir });
|
|
32
|
+
const dataDir = path.resolve(options.dataDir || getDataDir());
|
|
33
|
+
const storeIdentity = loadLegacyRuntime('store-scope').ensureStoreScope(dataDir);
|
|
34
|
+
const apiPrefix = options.apiPrefix || DEFAULT_API_PREFIX;
|
|
35
|
+
const testRoot = path.join(dataDir, 'test-workspaces');
|
|
36
|
+
const projects = options.projects || new ProjectStore({ dataDir });
|
|
37
|
+
require('./lib/cli-session-recovery').recoverOwnedCliSessions({ dataDir, projects });
|
|
38
|
+
const sessionArchive = options.sessionArchive || new SessionArchiveStore({ dataDir });
|
|
39
|
+
const workspaces = {
|
|
40
|
+
'test-workspace-a': path.join(testRoot, 'context-a'),
|
|
41
|
+
'test-workspace-b': path.join(testRoot, 'context-b'),
|
|
42
|
+
'test-workspace-c': path.join(testRoot, 'context-c'),
|
|
43
|
+
...(options.workspaces || {}),
|
|
44
|
+
...projects.toWorkspaceMap(),
|
|
45
|
+
};
|
|
46
|
+
const profiles = options.profiles || new ProfileStore({ dataDir });
|
|
47
|
+
const bridgeUrl = options.bridgeUrl || process.env.KB_EVENT_BRIDGE_URL;
|
|
48
|
+
const runtimeToken = options.runtimeToken || process.env.KB_WORKBENCH_RUNTIME_TOKEN;
|
|
49
|
+
const conversationCapture = options.conversationCapture || (bridgeUrl && runtimeToken ? new (require('./lib/conversation-capture').ConversationCapture)({ file: path.join(dataDir, 'capture-outbox.v1.json'), bridgeUrl, token: runtimeToken }) : null);
|
|
50
|
+
const captureSettings = options.captureSettings || new CaptureSettingsStore({ dataDir, defaultConversations: !!conversationCapture });
|
|
51
|
+
const uiPreferences = options.uiPreferences || new UiPreferencesStore({ dataDir });
|
|
52
|
+
const attachments = options.attachments || new AttachmentStore({ root: path.join(dataDir, 'attachments') });
|
|
53
|
+
const contexts = options.contexts || new ContextResolver({ workspaces, createMissing: options.createMissingWorkspaces !== false });
|
|
54
|
+
const claudeDriver = options.runner || loadLegacyRuntime('claude-cli-runner');
|
|
55
|
+
const knowledgeContextProvided = Boolean(options.knowledge || options.engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL);
|
|
56
|
+
claudeDriver.setKnowledgeContextProvided?.(knowledgeContextProvided);
|
|
57
|
+
// Bridge capture scope: terminal sessions are exempt from Development
|
|
58
|
+
// Conversation capture unless the 会话捕获 setting says otherwise. Applied to
|
|
59
|
+
// the driver at boot and re-applied on every settings save.
|
|
60
|
+
const applyBridgeCapture = enabled => {
|
|
61
|
+
if (claudeDriver && typeof claudeDriver.setBridgeCaptureConversation === 'function') {
|
|
62
|
+
// Native capture records the original input, not the augmented SDK
|
|
63
|
+
// prompt. Suppress inherited CLI hooks to avoid duplicate capture.
|
|
64
|
+
claudeDriver.setBridgeCaptureConversation(conversationCapture ? false : enabled);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
applyBridgeCapture(captureSettings.read().terminalConversations);
|
|
68
|
+
const registry = options.registry || new AgentRegistry({
|
|
69
|
+
drivers: {
|
|
70
|
+
'claude-code': claudeDriver,
|
|
71
|
+
...(options.drivers || {
|
|
72
|
+
codex: createCodexDriver({ knowledgeContextProvided, conversationCaptureProvided: Boolean(conversationCapture), persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
73
|
+
opencode: createOpenCodeDriver({ persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
74
|
+
zcode: createZCodeDriver({ knowledgeContextProvided, conversationCaptureProvided: Boolean(conversationCapture), persistence: { dir: path.join(dataDir, 'cli-sessions') } }),
|
|
75
|
+
}),
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
const runner = registry.asRunner();
|
|
79
|
+
const diagnostics = options.logger || createDiagnostics({ dataDir, secrets: () => [...Object.values(profiles._credentials().credentials), process.env.ANTHROPIC_API_KEY, process.env.ANTHROPIC_AUTH_TOKEN] });
|
|
80
|
+
const agentDiscovery = options.agentDiscovery || createAgentDiscovery({
|
|
81
|
+
claudeProbe: async ({ signal } = {}) => {
|
|
82
|
+
try {
|
|
83
|
+
const executable = await resolveClaudeAsync(claudeDriver, { signal });
|
|
84
|
+
// Handle both shapes: the legacy runner returns {cmd}, test doubles
|
|
85
|
+
// may return a plain string. No usable executable -> not available.
|
|
86
|
+
const cmd = typeof executable === 'string'
|
|
87
|
+
? executable
|
|
88
|
+
: executable && executable.cmd;
|
|
89
|
+
if (!cmd) {
|
|
90
|
+
const reason = executable?.reason || '未发现可用的 Claude Code 启动文件。';
|
|
91
|
+
diagnostics.error('agent.discovery.failed', 'Claude Code 不可用。', { phase: 'discovery', error: { code: 'CLAUDE_EXECUTABLE_NOT_FOUND', message: reason }, context: { agent: 'claude-code', rejectedPaths: executable?.rejected || [] } });
|
|
92
|
+
return { available: false, version: null, reason };
|
|
93
|
+
}
|
|
94
|
+
// Honest probe: spawn the resolved executable with --version. Same
|
|
95
|
+
// contract as every other agent: no version, no availability claim.
|
|
96
|
+
const probe = await probeExecutableAsync(cmd, { signal });
|
|
97
|
+
if (!probe.available) diagnostics.error('agent.discovery.failed', 'Claude Code 版本探测失败。', { phase: 'version-probe', error: { code: probe.code, message: probe.reason }, context: { agent: 'claude-code', executable: cmd, exitCode: probe.exitCode } });
|
|
98
|
+
else if (executable.rejected?.length) diagnostics.warn('agent.discovery.recovered', '已跳过失效的 Claude Code 启动路径,使用有效安装。', { phase: 'discovery', context: { executable: cmd, rejectedPaths: executable.rejected } });
|
|
99
|
+
return probe;
|
|
100
|
+
} catch { return { available: false, version: null }; }
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
const modelContextWindows = options.modelContextWindows || safeLoad('model-context-windows');
|
|
104
|
+
const modelDetection = options.modelDetection || createModelDetection({
|
|
105
|
+
contextLookup: modelContextWindows && modelContextWindows.lookupContextWindow,
|
|
106
|
+
});
|
|
107
|
+
const collectDoctor = options.doctor || createSystemDoctor({
|
|
108
|
+
resolveClaudeExecutable: async () => {
|
|
109
|
+
try { return await resolveClaudeAsync(claudeDriver); } catch { return { cmd: null }; }
|
|
110
|
+
},
|
|
111
|
+
discoverZCodeCli: () => resolveZCodeAsync(),
|
|
112
|
+
});
|
|
113
|
+
const doctor = async () => {
|
|
114
|
+
const report = await collectDoctor();
|
|
115
|
+
const claude = report.agents?.['claude-code'];
|
|
116
|
+
if (claude && !claude.versionProbe?.ok) diagnostics.error('agent.doctor.failed', 'Claude Code 环境诊断失败。', { phase: 'doctor', error: { code: 'CLAUDE_PROBE_FAILED', message: claude.versionProbe?.error || claude.resolutionReason }, context: { agent: 'claude-code', executable: claude.resolvedExecutable, rejectedPaths: claude.rejectedPaths, exitCode: claude.versionProbe?.exitCode } });
|
|
117
|
+
return report;
|
|
118
|
+
};
|
|
119
|
+
const service = options.service || new WorkbenchService({
|
|
120
|
+
knowledge: options.knowledge || new (require('./lib/knowledge-context').KnowledgeContext)({ engineUrl: options.engineUrl || process.env.KB_KNOWLEDGE_ENGINE_URL, contextFile: path.join(dataDir, 'knowledge-contexts.v1.json') }),
|
|
121
|
+
runner, profiles, contexts, attachments, apiPrefix, diagnostics,
|
|
122
|
+
resolveRuntimeExecutable: () => resolveClaudeAsync(claudeDriver),
|
|
123
|
+
projects, sessionArchive, agentDiscovery, modelContextWindows, modelDetection,
|
|
124
|
+
archiveRetentionDays: options.archiveRetentionDays,
|
|
125
|
+
captureSettings, uiPreferences, onCaptureSettingsSaved: applyBridgeCapture,
|
|
126
|
+
conversationCapture,
|
|
127
|
+
testWorkspace: path.join(testRoot, 'profile-test'), auditFile: path.join(dataDir, 'audit.jsonl'),
|
|
128
|
+
version: options.version || require('./package.json').version,
|
|
129
|
+
maxSessions: options.maxSessions, maxConcurrentRuns: options.maxConcurrentRuns,
|
|
130
|
+
storeIdentity,
|
|
131
|
+
delegations: buildDelegationStores(dataDir, storeIdentity, options),
|
|
132
|
+
});
|
|
133
|
+
const handleApi = createHttpHandler(service, { apiPrefix, corsOrigin: options.corsOrigin, doctor, runtimeToken: options.runtimeToken || process.env.KB_WORKBENCH_RUNTIME_TOKEN });
|
|
134
|
+
const distributionRoot = resolveDistributionRoot();
|
|
135
|
+
const staticRoot = path.resolve(options.staticRoot || path.join(distributionRoot, 'apps', 'minimal-test-host'));
|
|
136
|
+
const profileSettingsRoot = path.resolve(options.profileSettingsRoot || path.join(distributionRoot, 'apps', 'ai-profile-settings-host'));
|
|
137
|
+
const agentTerminalRoot = path.resolve(options.agentTerminalRoot || path.join(distributionRoot, 'apps', 'agent-terminal'));
|
|
138
|
+
const packagesRoot = path.join(distributionRoot, 'packages');
|
|
139
|
+
const server = http.createServer(async (req, res) => {
|
|
140
|
+
if (await handleApi(req, res)) return;
|
|
141
|
+
if (options.serveHost !== false && servePackageAsset(req, res, packagesRoot)) return;
|
|
142
|
+
if (options.serveHost !== false && serveAppStatic(req, res, '/profile-settings/', profileSettingsRoot)) return;
|
|
143
|
+
if (options.serveHost !== false && serveAppStatic(req, res, '/agent-terminal/', agentTerminalRoot)) return;
|
|
144
|
+
if (options.serveHost !== false && serveStatic(req, res, staticRoot)) return;
|
|
145
|
+
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
146
|
+
res.end(JSON.stringify({ ok: false, error: 'not found' }));
|
|
147
|
+
});
|
|
148
|
+
server.on('close', () => { agentDiscovery.close?.(); Promise.resolve(service.destroy()).catch(error => diagnostics.error('agent.shutdown.failed', '客户端运行环境关闭失败。', { phase: 'shutdown', error: { code: error.code || 'SHUTDOWN_FAILED', message: error.message } })); });
|
|
149
|
+
return { server, service, profiles, contexts, attachments, projects, sessionArchive, registry, agentDiscovery, apiPrefix, dataDir };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function safeLoad(name) {
|
|
153
|
+
try { return loadLegacyRuntime(name); } catch { return null; }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Delegation stores bind to the SAME durable store identity as native-task
|
|
157
|
+
// scopes; without one the delegation APIs answer explicit unavailability.
|
|
158
|
+
function buildDelegationStores(dataDir, storeIdentity, options) {
|
|
159
|
+
if (options.delegations) return options.delegations;
|
|
160
|
+
if (!storeIdentity || storeIdentity.available !== true || !storeIdentity.storeScope) return null;
|
|
161
|
+
const root = path.join(dataDir, 'delegations');
|
|
162
|
+
return {
|
|
163
|
+
ledger: createDelegationStore({ root, storeScope: storeIdentity.storeScope }),
|
|
164
|
+
phases: createDelegationPhaseStore({ root, storeScope: storeIdentity.storeScope }),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function resolveDistributionRoot() {
|
|
169
|
+
// A source checkout must win over whatever unrelated 'claude-ai-workbench'
|
|
170
|
+
// package require.resolve happens to find on this machine (an old copy in
|
|
171
|
+
// the user's home node_modules once shadowed this tree and served a stale
|
|
172
|
+
// agent-terminal). Only trust require.resolve when this file is not running
|
|
173
|
+
// from a checkout of the monorepo itself.
|
|
174
|
+
const sourceRoot = path.resolve(__dirname, '..', '..');
|
|
175
|
+
try {
|
|
176
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8'));
|
|
177
|
+
if (manifest && manifest.name === '@sanqianx/claude-ai-workbench') return sourceRoot;
|
|
178
|
+
} catch { /* not a source layout: fall through */ }
|
|
179
|
+
try { return path.dirname(require.resolve('claude-ai-workbench/package.json')); }
|
|
180
|
+
catch { return sourceRoot; }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function servePackageAsset(req, res, packagesRoot) {
|
|
184
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
185
|
+
if (req.method !== 'GET' || !url.pathname.startsWith('/packages/')) return false;
|
|
186
|
+
const relative = decodeURIComponent(url.pathname.slice('/packages/'.length));
|
|
187
|
+
const file = path.resolve(packagesRoot, relative);
|
|
188
|
+
if (!file.startsWith(`${packagesRoot}${path.sep}`) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
189
|
+
const type = path.extname(file) === '.css' ? 'text/css' : 'text/javascript';
|
|
190
|
+
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
191
|
+
fs.createReadStream(file).pipe(res); return true;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function serveStatic(req, res, root) {
|
|
195
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
196
|
+
if (!['GET', 'HEAD'].includes(req.method)) return false;
|
|
197
|
+
let pathname = decodeURIComponent(url.pathname);
|
|
198
|
+
if (pathname === '/') { res.writeHead(302, { Location: '/agent-terminal/' }); res.end(); return true; }
|
|
199
|
+
if (!pathname.startsWith('/test-host/')) return false;
|
|
200
|
+
const relative = pathname.slice('/test-host/'.length) || 'index.html';
|
|
201
|
+
const file = path.resolve(root, relative);
|
|
202
|
+
if (file !== root && !file.startsWith(`${root}${path.sep}`)) return false;
|
|
203
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
204
|
+
const type = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml' }[path.extname(file)] || 'application/octet-stream';
|
|
205
|
+
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
206
|
+
if (req.method === 'HEAD') res.end(); else fs.createReadStream(file).pipe(res);
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function serveAppStatic(req, res, urlPrefix, root) {
|
|
211
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
212
|
+
if (!['GET', 'HEAD'].includes(req.method)) return false;
|
|
213
|
+
if (url.pathname === urlPrefix.slice(0, -1)) { res.writeHead(302, { Location: urlPrefix }); res.end(); return true; }
|
|
214
|
+
if (!url.pathname.startsWith(urlPrefix)) return false;
|
|
215
|
+
const relative = decodeURIComponent(url.pathname.slice(urlPrefix.length)) || 'index.html';
|
|
216
|
+
const file = path.resolve(root, relative);
|
|
217
|
+
if (file !== root && !file.startsWith(`${root}${path.sep}`)) return false;
|
|
218
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return false;
|
|
219
|
+
const type = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml' }[path.extname(file)] || 'application/octet-stream';
|
|
220
|
+
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-store' });
|
|
221
|
+
if (req.method === 'HEAD') res.end(); else fs.createReadStream(file).pipe(res);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
module.exports = {
|
|
226
|
+
createWorkbenchServer, ProfileStore, CaptureSettingsStore, ContextResolver, AttachmentStore, WorkbenchService, createHttpHandler,
|
|
227
|
+
ProjectStore, SessionArchiveStore, AgentRegistry, createAgentDiscovery, UiPreferencesStore,
|
|
228
|
+
createCodexDriver, createOpenCodeDriver, createZCodeDriver,
|
|
229
|
+
createDelegationStore, createDelegationPhaseStore,
|
|
230
|
+
};
|