@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,125 +1,125 @@
1
- 'use strict';
2
-
3
- const { runProbe } = require('./agent-discovery');
4
- const fs = require('fs');
5
- const os = require('os');
6
- const path = require('path');
7
-
8
- // Environment diagnostics behind GET /system/doctor. Everything a fresh
9
- // machine needs to explain "discovery showed the agent but turns failed":
10
- // resolved executables, live version probes, login-state files — no secrets.
11
- function createSystemDoctor(deps = {}) {
12
- const resolveClaudeExecutable = deps.resolveClaudeExecutable || (() => ({ cmd: null }));
13
- const discoverZCodeCli = deps.discoverZCodeCli || (() => null);
14
- const probeZCodeVersion = deps.probeZCodeVersion || (() => null);
15
- const doSpawnSync = deps.spawnSyncImpl;
16
- const env = deps.env || process.env;
17
- const platform = deps.platform || process.platform;
18
-
19
- async function probe(command, args) {
20
- try {
21
- const script = /\.[cm]?js$/i.test(command);
22
- if (!doSpawnSync) {
23
- const result = await runProbe(script ? process.execPath : command, script ? [command, ...args] : args, { shell: !script && platform === 'win32' && !path.isAbsolute(command) });
24
- return { ok: result.available, version: result.version || null, exitCode: result.exitCode, error: result.available ? undefined : result.reason };
25
- }
26
- const result = doSpawnSync(script ? process.execPath : command, script ? [command, ...args] : args, {
27
- timeout: 10000,
28
- windowsHide: true,
29
- encoding: 'utf8',
30
- shell: !script && platform === 'win32' && !require('path').isAbsolute(command),
31
- env,
32
- });
33
- if (result.error) {
34
- return { ok: false, error: String(result.error.message || result.error).slice(0, 200) };
35
- }
36
- const text = String(result.stdout || result.stderr || '').trim();
37
- if (result.status !== 0) {
38
- return { ok: false, exitCode: result.status, error: text.slice(0, 200) || `exit ${result.status}` };
39
- }
40
- const match = text.match(/(\d+\.\d+[\w.-]*)/);
41
- return { ok: true, version: match ? match[1] : text.split(/\r?\n/)[0].slice(0, 64) || null };
42
- } catch (error) {
43
- return { ok: false, error: String(error && error.message || error).slice(0, 200) };
44
- }
45
- }
46
-
47
- function fileState(file) {
48
- try {
49
- const stat = fs.statSync(file);
50
- return { exists: true, sizeBytes: stat.size };
51
- } catch {
52
- return { exists: false };
53
- }
54
- }
55
-
56
- function zcodeLoginState() {
57
- const home = os.homedir();
58
- const config = path.join(home, '.zcode', 'v2', 'config.json');
59
- const state = { config: fileState(config), providers: [] };
60
- if (!state.config.exists) return state;
61
- try {
62
- const parsed = JSON.parse(fs.readFileSync(config, 'utf8'));
63
- const scan = (node) => {
64
- if (!node || typeof node !== 'object') return;
65
- for (const [key, value] of Object.entries(node)) {
66
- if (/provider|coding|glm|anthropic|openai/i.test(key) && value && typeof value === 'object') {
67
- state.providers.push(key);
68
- } else if (typeof value === 'object') {
69
- scan(value);
70
- }
71
- }
72
- };
73
- scan(parsed);
74
- } catch (error) {
75
- state.parseError = String(error && error.message || error).slice(0, 120);
76
- }
77
- return state;
78
- }
79
-
80
- function claudeLoginState() {
81
- const home = os.homedir();
82
- return {
83
- claudeJson: fileState(path.join(home, '.claude.json')),
84
- claudeDir: fileState(path.join(home, '.claude')),
85
- execPathOverride: env.CLAUDE_CODE_EXECPATH || null,
86
- };
87
- }
88
-
89
- return async function doctor() {
90
- const claude = await resolveClaudeExecutable() || {};
91
- const claudeProbe = claude.cmd
92
- ? await probe(claude.cmd, ['--version'])
93
- : { ok: false, error: claude.reason || 'no executable resolved' };
94
- const zcode = await discoverZCodeCli();
95
- const report = {
96
- schema: 'agent-terminal-doctor/v1',
97
- at: new Date().toISOString(),
98
- environment: {
99
- node: process.version,
100
- platform,
101
- arch: process.arch,
102
- cwd: process.cwd(),
103
- },
104
- agents: {
105
- 'claude-code': {
106
- resolvedExecutable: claude.cmd || null,
107
- resolutionReason: claude.cmd ? null : (claude.reason || 'not found'),
108
- rejectedPaths: claude.rejected || [],
109
- versionProbe: claudeProbe,
110
- loginState: claudeLoginState(),
111
- },
112
- codex: { versionProbe: await probe('codex', ['--version']) },
113
- opencode: { versionProbe: await probe('opencode', ['--version']) },
114
- zcode: {
115
- cli: zcode ? { path: zcode.path, source: zcode.source || null } : null,
116
- versionProbe: zcode ? await probe(process.execPath, [zcode.path, '--version']) : { ok: false, error: 'CLI not discovered' },
117
- loginState: zcodeLoginState(),
118
- },
119
- },
120
- };
121
- return report;
122
- };
123
- }
124
-
125
- module.exports = { createSystemDoctor };
1
+ 'use strict';
2
+
3
+ const { runProbe } = require('./agent-discovery');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+
8
+ // Environment diagnostics behind GET /system/doctor. Everything a fresh
9
+ // machine needs to explain "discovery showed the agent but turns failed":
10
+ // resolved executables, live version probes, login-state files — no secrets.
11
+ function createSystemDoctor(deps = {}) {
12
+ const resolveClaudeExecutable = deps.resolveClaudeExecutable || (() => ({ cmd: null }));
13
+ const discoverZCodeCli = deps.discoverZCodeCli || (() => null);
14
+ const probeZCodeVersion = deps.probeZCodeVersion || (() => null);
15
+ const doSpawnSync = deps.spawnSyncImpl;
16
+ const env = deps.env || process.env;
17
+ const platform = deps.platform || process.platform;
18
+
19
+ async function probe(command, args) {
20
+ try {
21
+ const script = /\.[cm]?js$/i.test(command);
22
+ if (!doSpawnSync) {
23
+ const result = await runProbe(script ? process.execPath : command, script ? [command, ...args] : args, { shell: !script && platform === 'win32' && !path.isAbsolute(command) });
24
+ return { ok: result.available, version: result.version || null, exitCode: result.exitCode, error: result.available ? undefined : result.reason };
25
+ }
26
+ const result = doSpawnSync(script ? process.execPath : command, script ? [command, ...args] : args, {
27
+ timeout: 10000,
28
+ windowsHide: true,
29
+ encoding: 'utf8',
30
+ shell: !script && platform === 'win32' && !require('path').isAbsolute(command),
31
+ env,
32
+ });
33
+ if (result.error) {
34
+ return { ok: false, error: String(result.error.message || result.error).slice(0, 200) };
35
+ }
36
+ const text = String(result.stdout || result.stderr || '').trim();
37
+ if (result.status !== 0) {
38
+ return { ok: false, exitCode: result.status, error: text.slice(0, 200) || `exit ${result.status}` };
39
+ }
40
+ const match = text.match(/(\d+\.\d+[\w.-]*)/);
41
+ return { ok: true, version: match ? match[1] : text.split(/\r?\n/)[0].slice(0, 64) || null };
42
+ } catch (error) {
43
+ return { ok: false, error: String(error && error.message || error).slice(0, 200) };
44
+ }
45
+ }
46
+
47
+ function fileState(file) {
48
+ try {
49
+ const stat = fs.statSync(file);
50
+ return { exists: true, sizeBytes: stat.size };
51
+ } catch {
52
+ return { exists: false };
53
+ }
54
+ }
55
+
56
+ function zcodeLoginState() {
57
+ const home = os.homedir();
58
+ const config = path.join(home, '.zcode', 'v2', 'config.json');
59
+ const state = { config: fileState(config), providers: [] };
60
+ if (!state.config.exists) return state;
61
+ try {
62
+ const parsed = JSON.parse(fs.readFileSync(config, 'utf8'));
63
+ const scan = (node) => {
64
+ if (!node || typeof node !== 'object') return;
65
+ for (const [key, value] of Object.entries(node)) {
66
+ if (/provider|coding|glm|anthropic|openai/i.test(key) && value && typeof value === 'object') {
67
+ state.providers.push(key);
68
+ } else if (typeof value === 'object') {
69
+ scan(value);
70
+ }
71
+ }
72
+ };
73
+ scan(parsed);
74
+ } catch (error) {
75
+ state.parseError = String(error && error.message || error).slice(0, 120);
76
+ }
77
+ return state;
78
+ }
79
+
80
+ function claudeLoginState() {
81
+ const home = os.homedir();
82
+ return {
83
+ claudeJson: fileState(path.join(home, '.claude.json')),
84
+ claudeDir: fileState(path.join(home, '.claude')),
85
+ execPathOverride: env.CLAUDE_CODE_EXECPATH || null,
86
+ };
87
+ }
88
+
89
+ return async function doctor() {
90
+ const claude = await resolveClaudeExecutable() || {};
91
+ const claudeProbe = claude.cmd
92
+ ? await probe(claude.cmd, ['--version'])
93
+ : { ok: false, error: claude.reason || 'no executable resolved' };
94
+ const zcode = await discoverZCodeCli();
95
+ const report = {
96
+ schema: 'agent-terminal-doctor/v1',
97
+ at: new Date().toISOString(),
98
+ environment: {
99
+ node: process.version,
100
+ platform,
101
+ arch: process.arch,
102
+ cwd: process.cwd(),
103
+ },
104
+ agents: {
105
+ 'claude-code': {
106
+ resolvedExecutable: claude.cmd || null,
107
+ resolutionReason: claude.cmd ? null : (claude.reason || 'not found'),
108
+ rejectedPaths: claude.rejected || [],
109
+ versionProbe: claudeProbe,
110
+ loginState: claudeLoginState(),
111
+ },
112
+ codex: { versionProbe: await probe('codex', ['--version']) },
113
+ opencode: { versionProbe: await probe('opencode', ['--version']) },
114
+ zcode: {
115
+ cli: zcode ? { path: zcode.path, source: zcode.source || null } : null,
116
+ versionProbe: zcode ? await probe(process.execPath, [zcode.path, '--version']) : { ok: false, error: 'CLI not discovered' },
117
+ loginState: zcodeLoginState(),
118
+ },
119
+ },
120
+ };
121
+ return report;
122
+ };
123
+ }
124
+
125
+ module.exports = { createSystemDoctor };
@@ -1,48 +1,48 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const { readJson, writeJson } = require('./json-file');
5
-
6
- const SCHEMA = 'agent-terminal-ui-preferences/v1';
7
-
8
- // Last-used composer selector values (protection mode, model, effort, agent).
9
- // The UI loads them on boot and stores every user-driven change back, so the
10
- // selections survive conversation/project switches and full restarts. Only
11
- // whitelisted string keys are kept, so a stale or hostile payload cannot
12
- // smuggle arbitrary state into the renderer.
13
- const ALLOWED_KEYS = ['permissionMode', 'effort', 'currentAgent', 'currentProfileId', 'currentModel'];
14
-
15
- class UiPreferencesStore {
16
- constructor(options = {}) {
17
- if (!options.dataDir) throw new Error('UiPreferencesStore dataDir is required');
18
- this.preferencesFile = options.preferencesFile || path.join(options.dataDir, 'ui-preferences.v1.json');
19
- }
20
-
21
- read() {
22
- const cfg = readJson(this.preferencesFile, { schema: SCHEMA, values: {} });
23
- return { schema: SCHEMA, values: this._clean(cfg.values || {}) };
24
- }
25
-
26
- save(input = {}) {
27
- if (!input || typeof input !== 'object' || Array.isArray(input)) {
28
- throw Object.assign(new Error('ui preferences must be an object'), { status: 400 });
29
- }
30
- const values = { ...this.read().values, ...this._clean(input) };
31
- const cfg = { schema: SCHEMA, values, updatedAt: new Date().toISOString() };
32
- writeJson(this.preferencesFile, cfg);
33
- return { schema: SCHEMA, values };
34
- }
35
-
36
- _clean(input) {
37
- const values = {};
38
- for (const key of ALLOWED_KEYS) {
39
- if (input[key] === undefined) continue;
40
- if (input[key] !== null && typeof input[key] !== 'string') continue;
41
- if (typeof input[key] === 'string' && input[key].length > 200) continue;
42
- values[key] = input[key];
43
- }
44
- return values;
45
- }
46
- }
47
-
48
- module.exports = { UiPreferencesStore, SCHEMA };
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { readJson, writeJson } = require('./json-file');
5
+
6
+ const SCHEMA = 'agent-terminal-ui-preferences/v1';
7
+
8
+ // Last-used composer selector values (protection mode, model, effort, agent).
9
+ // The UI loads them on boot and stores every user-driven change back, so the
10
+ // selections survive conversation/project switches and full restarts. Only
11
+ // whitelisted string keys are kept, so a stale or hostile payload cannot
12
+ // smuggle arbitrary state into the renderer.
13
+ const ALLOWED_KEYS = ['permissionMode', 'effort', 'currentAgent', 'currentProfileId', 'currentModel'];
14
+
15
+ class UiPreferencesStore {
16
+ constructor(options = {}) {
17
+ if (!options.dataDir) throw new Error('UiPreferencesStore dataDir is required');
18
+ this.preferencesFile = options.preferencesFile || path.join(options.dataDir, 'ui-preferences.v1.json');
19
+ }
20
+
21
+ read() {
22
+ const cfg = readJson(this.preferencesFile, { schema: SCHEMA, values: {} });
23
+ return { schema: SCHEMA, values: this._clean(cfg.values || {}) };
24
+ }
25
+
26
+ save(input = {}) {
27
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
28
+ throw Object.assign(new Error('ui preferences must be an object'), { status: 400 });
29
+ }
30
+ const values = { ...this.read().values, ...this._clean(input) };
31
+ const cfg = { schema: SCHEMA, values, updatedAt: new Date().toISOString() };
32
+ writeJson(this.preferencesFile, cfg);
33
+ return { schema: SCHEMA, values };
34
+ }
35
+
36
+ _clean(input) {
37
+ const values = {};
38
+ for (const key of ALLOWED_KEYS) {
39
+ if (input[key] === undefined) continue;
40
+ if (input[key] !== null && typeof input[key] !== 'string') continue;
41
+ if (typeof input[key] === 'string' && input[key].length > 200) continue;
42
+ values[key] = input[key];
43
+ }
44
+ return values;
45
+ }
46
+ }
47
+
48
+ module.exports = { UiPreferencesStore, SCHEMA };
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ function invalid(message) { return Object.assign(new Error(message), { status: 400, code: 'QUESTION_ANSWER_INVALID' }); }
4
+ function normalizeQuestions(input, codex = false) {
5
+ if (!Array.isArray(input?.questions) || !input.questions.length || input.questions.length > 8) throw invalid('问题列表无效,请重新提问。');
6
+ const ids = new Set();
7
+ return input.questions.map((question, index) => {
8
+ const id = codex ? question.id : `question-${index + 1}`;
9
+ if (typeof id !== 'string' || !id || ids.has(id) || typeof question.question !== 'string' || !question.question.trim()) throw invalid('问题标识或内容无效。');
10
+ ids.add(id);
11
+ const options = Array.isArray(question.options) ? question.options.map(option => {
12
+ if (typeof option?.label !== 'string' || !option.label.trim()) throw invalid('问题选项无效。');
13
+ return { label: option.label, description: String(option.description || '') };
14
+ }) : [];
15
+ return { id, header: String(question.header || ''), question: question.question, options,
16
+ multiSelect: !codex && question.multiSelect === true, isSecret: question.isSecret === true,
17
+ allowCustom: !codex || question.isOther === true || !options.length };
18
+ });
19
+ }
20
+ function validateAnswers(questions, answers) {
21
+ if (!answers || typeof answers !== 'object' || Array.isArray(answers)) throw invalid('请填写答案后再提交。');
22
+ if (Object.keys(answers).some(id => !questions.some(question => question.id === id))) throw invalid('答案不属于本次问题。');
23
+ const result = Object.create(null);
24
+ for (const question of questions) {
25
+ const value = Object.hasOwn(answers, question.id) ? answers[question.id] : undefined;
26
+ const selected = typeof value === 'string' ? [value] : value;
27
+ if (!Array.isArray(selected) || !selected.length || !question.multiSelect && selected.length !== 1
28
+ || selected.some(item => typeof item !== 'string' || !item.trim() || item.length > 8192)) throw invalid('请回答全部问题后再提交。');
29
+ if (!question.allowCustom && selected.some(item => !question.options.some(option => option.label === item))) throw invalid('请选择本次问题提供的选项。');
30
+ result[question.id] = [...new Set(selected.map(item => question.options.some(option => option.label === item) ? item : item.trim()))];
31
+ }
32
+ return result;
33
+ }
34
+ function sdkAnswers(input, questions, answers) {
35
+ const checked = validateAnswers(questions, answers);
36
+ return { ...input, answers: Object.fromEntries(questions.map(question => [question.question, checked[question.id].join(', ')])) };
37
+ }
38
+ function codexAnswers(questions, answers) {
39
+ const checked = validateAnswers(questions, answers);
40
+ return { answers: Object.fromEntries(questions.map(question => [question.id, { answers: checked[question.id] }])) };
41
+ }
42
+ function waitForSdkQuestion({ session, input, context = {}, requestId, emit, setState }) {
43
+ const questions = normalizeQuestions(input);
44
+ if (session.pendingToolApproval) throw invalid('已有待回答的问题或授权,请先完成当前操作。');
45
+ return new Promise(resolve => {
46
+ const cleanup = () => context.signal?.removeEventListener('abort', cancel);
47
+ const cancel = () => {
48
+ if (session.pendingToolApproval?.requestId !== requestId) return;
49
+ session.pendingToolApproval = null; session.pendingPermission = null; cleanup();
50
+ emit({ type: 'claude/permission-resolved', requestId, kind: 'question', allow: false, cancelled: true });
51
+ resolve({ behavior: 'deny', interrupt: true, message: 'Question cancelled without a user answer. No option was selected.', toolUseID: context.toolUseID });
52
+ };
53
+ session.pendingToolApproval = { requestId, input, questions, toolUseID: context.toolUseID,
54
+ resolve: result => { cleanup(); resolve(result); }, cancel };
55
+ session.pendingPermission = { requestId, kind: 'question', toolName: 'AskUserQuestion', questions,
56
+ status: 'pending', createdAt: new Date().toISOString() };
57
+ if (context.signal?.aborted) { cancel(); return; }
58
+ context.signal?.addEventListener('abort', cancel, { once: true });
59
+ setState('pending-permission');
60
+ emit({ type: 'claude/permission-request', ...session.pendingPermission });
61
+ });
62
+ }
63
+ async function questionPromptHook(input) {
64
+ if (input.tool_name !== 'AskUserQuestion') return {};
65
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: '等待用户明确回答问题。' } };
66
+ }
67
+ module.exports = { normalizeQuestions, validateAnswers, sdkAnswers, codexAnswers, waitForSdkQuestion, questionPromptHook };