ai_co_discuss 0.3.73 → 0.3.74

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.
@@ -1,448 +1,680 @@
1
- /**
2
- * Claude Code adapter: one headless `claude -p` process per turn resuming the bound session, or, for a taken-over manual
3
- * member whose window is open, a task posted into that window. Sessions are branched by Claude's own --fork-session.
4
- */
5
- import { spawn, spawnSync } from 'node:child_process';
6
- import { randomUUID } from 'node:crypto';
7
- import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
8
- import { connect } from 'node:net';
9
- import { homedir } from 'node:os';
10
- import { dirname, join, resolve } from 'node:path';
11
- import { runs_commands } from '../expert_prompts.mjs';
12
- import { bind_access, DENIAL_FIELD, EDIT_TOOLS, launch_directory, log_entries, marked, MAX_DENIALS, model_entry, json_line,
13
- newest_record, not_sent, project_directory, prompt_text, query_catalog, TASK_SUBCOMMANDS, tree_killable, watch_events } from './common.mjs';
14
-
15
- // A message posted to an open Claude window that has not started by then is reported, not failed.
16
- const INBOX_CHECK_MS = 90_000;
17
- // How often an open window's session log is read for the end of the turn that took a task.
18
- const WINDOW_POLL_MS = 3_000;
19
- // Error kinds Claude Code records that a retry a minute later meets again: a used-up plan limit, a lost login.
20
- const LASTING_ERRORS = ['rate_limit', 'authentication_failed'];
21
- const EDIT_TOOL_NAMES = /^(Edit|MultiEdit|Write|NotebookEdit)$/;
22
- // Claude Code logs side queries (titles, compaction, subagents) too; only these sources are the member's own turns.
23
- const CLAUDE_MAIN_SOURCES = ['sdk', 'repl_main_thread'];
24
- // A background process can be stopped and streams its progress; a turn in the member's own window does neither.
25
- const PROCESS = { stoppable: true, progress: true };
26
- const WINDOW = { stoppable: false, progress: false };
27
-
28
- /** Explain why a finished Claude print run failed, including errors reported with exit code 0. */
29
- export function claude_exit_error(code, output) {
30
- let result = null;
31
- try { result = JSON.parse(output.trim().split(/\r?\n/).at(-1)); } catch { /* Non-JSON output keeps the exit code check. */ }
32
- if (result?.is_error) return `Claude 执行出错:${result.result || result.api_error || result.subtype || '未知错误'}`;
33
- return code === 0 ? '' : `Claude 退出码 ${code}`;
34
- }
35
-
36
- /**
37
- * The API error Claude Code wrote in place of an answer, from a session log entry or a stream-json event, or null.
38
- * Its `kind` is Claude's own category (`rate_limit`, `authentication_failed`, `server_error`, ...).
39
- */
40
- export function claude_api_error(entry) {
41
- if (entry?.type !== 'assistant' || !(entry.isApiErrorMessage || entry.is_api_error_message)) return null;
42
- const text = prompt_text(entry.message?.content).trim();
43
- const kind = String(entry.error || '');
44
- return { kind, text: text || String(entry.api_error || kind || '未知错误'), lasting: LASTING_ERRORS.includes(kind) };
45
- }
46
-
47
- /** How a Claude API error reads on the failed execution; a lasting one says it is not retried. */
48
- export function claude_error_reason(error) {
49
- const label = { rate_limit: 'Claude 用量已达上限', authentication_failed: 'Claude 未登录或登录已失效' }[error.kind] || 'Claude 接口出错';
50
- return `${label}:${error.text}${error.lasting ? '(不自动重试;恢复后请重新发送)' : ''}`;
51
- }
52
-
53
- /** The first program a shell command runs, skipping `cd` and `Set-Location` steps, for a prefix rule that also allows a retry. */
54
- function command_program(command) {
55
- const steps = String(command).split(/&&|\|\||;|\|/).map(step => step.trim().split(/\s+/)[0]).filter(Boolean);
56
- return steps.find(step => !/^(cd|Set-Location|sl|pushd)$/i.test(step)) || steps[0] || '';
57
- }
58
-
59
- /**
60
- * The operations a headless Claude run refused, from the `permission_denials` of its final result line, each with the
61
- * `--allowedTools` rule that would let the next run do it: a command prefix, an edit of that folder, or the tool itself.
62
- */
63
- export function claude_denials(output) {
64
- let result = null;
65
- try { result = JSON.parse(output.trim().split(/\r?\n/).at(-1)); } catch { return []; }
66
- const seen = new Set();
67
- return (Array.isArray(result?.permission_denials) ? result.permission_denials : []).map(denial => {
68
- const tool = String(denial.tool_name || '').slice(0, 40), input = denial.tool_input || {};
69
- if (['Bash', 'PowerShell'].includes(tool) && input.command) {
70
- const program = command_program(input.command);
71
- return { tool, detail: String(input.command), rule: program ? `${tool}(${program} *)` : '' };
72
- }
73
- const path = input.file_path || input.notebook_path;
74
- if (EDIT_TOOL_NAMES.test(tool) && path) return { tool, detail: String(path), rule: `Edit(${claude_rule_path(dirname(path))}/**)` };
75
- return { tool, detail: JSON.stringify(input), rule: tool };
76
- }).filter(item => item.tool && !seen.has(item.detail) && seen.add(item.detail))
77
- .slice(0, MAX_DENIALS).map(item => ({ ...item, detail: item.detail.slice(0, DENIAL_FIELD), rule: item.rule.length <= DENIAL_FIELD ? item.rule : '' }));
78
- }
79
-
80
- /**
81
- * The environment for one spawned Claude CLI: variables a hosting Claude session injects are dropped, and the user's
82
- * persisted login variables, read afresh on Windows, override the ones this long-running process inherited at start,
83
- * so a token switched with setx or the system settings takes effect on the next turn without restarting the runner.
84
- */
85
- export function standalone_claude_env(env = process.env, persisted = persisted_claude_env) {
86
- const own = env.CLAUDECODE !== '1' ? env : Object.fromEntries(Object.entries(env).filter(([key]) =>
87
- !/^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT)$|^(CLAUDE_CODE_|CLAUDE_AGENT_SDK_|CLAUDE_PREVIEW_)/.test(key)));
88
- return { ...own, ...persisted() };
89
- }
90
-
91
- /** Read Machine then User persisted ANTHROPIC_/CLAUDE variables on every call; values stay in memory only. */
92
- function persisted_claude_env() {
93
- if (process.platform !== 'win32') return {};
94
- const script = "$r=@{}; foreach($s in 'Machine','User'){ $v=[Environment]::GetEnvironmentVariables($s);"
95
- + " foreach($k in $v.Keys){ if($k -match '^(ANTHROPIC_|CLAUDE)'){ $r[$k]=$v[$k] } } }; $r | ConvertTo-Json -Compress";
96
- const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
97
- try { return result.status === 0 && result.stdout.trim() ? JSON.parse(result.stdout) : {}; }
98
- catch { return {}; }
99
- }
100
-
101
- /** Claude permission rules match Windows paths in POSIX form, e.g. C:\a becomes //c/a. */
102
- export function claude_rule_path(directory) {
103
- const path = resolve(directory).replaceAll('\\', '/').replace(/^([A-Za-z]):/, (_, drive) => `/${drive.toLowerCase()}`);
104
- return `/${path}`;
105
- }
106
-
107
- /**
108
- * Allow the listed codiscuss website subcommands and draft writes for this run; a writable member also edits its project
109
- * and runs any command. The room's other project directories (`task.extra_directories`) are added as working
110
- * directories, edited only where their access is write. User rules are added after. Claude Code on Windows may run
111
- * commands through its PowerShell tool instead of Bash, so both are listed.
112
- */
113
- export function claude_permissions(config, task) {
114
- const extras = task.extra_directories || [];
115
- const added = [task.directory, task.draft_directory, ...task.skill_directories, ...extras.map(item => item.path)];
116
- // A headless run cannot ask for approval: 自动 and a taken-over manual member use auto mode, as the original window
117
- // does, and 全放开 skips every check; the website commands and drafts stay pre-approved either way.
118
- if (['own', 'auto', 'full'].includes(config.project_access)) {
119
- const commands = TASK_SUBCOMMANDS.flatMap(command => [`Bash(codiscuss ${command} *)`, `PowerShell(codiscuss ${command} *)`]);
120
- return ['--permission-mode', config.project_access === 'full' ? 'bypassPermissions' : 'auto', '--add-dir', ...added, '--allowedTools',
121
- ...commands, `Edit(${claude_rule_path(task.draft_directory)}/**)`, ...(config.allowed_tools || []), ...edit_denial(task)];
122
- }
123
- const commands = runs_commands(config, extras) ? ['Bash', 'PowerShell']
124
- : TASK_SUBCOMMANDS.flatMap(command => [`Bash(codiscuss ${command} *)`, `PowerShell(codiscuss ${command} *)`]);
125
- const writable = [task.draft_directory, ...(runs_commands(config, extras)
126
- ? [project_directory(config), ...extras.filter(item => item.access === 'write').map(item => item.path)].filter(Boolean) : [])];
127
- return ['--add-dir', ...added, '--allowedTools',
128
- ...commands, ...writable.map(directory => `Edit(${claude_rule_path(directory)}/**)`), ...(config.allowed_tools || []), ...edit_denial(task)];
129
- }
130
-
131
- /**
132
- * Skill folders (the shared skills and an enabled workflow) are read, never edited, and so are the room's project
133
- * directories this member may only read. This stops Claude's own edit tools only; a command the member may run can
134
- * still write there, and Windows has no native sandbox to prevent it.
135
- */
136
- function edit_denial(task) {
137
- const read_only = (task.extra_directories || []).filter(item => item.access === 'read').map(item => item.path);
138
- return ['--disallowedTools', ...[...task.skill_directories, ...read_only].map(directory => `Edit(${claude_rule_path(directory)}/**)`)];
139
- }
140
-
141
- /** What Claude's stream-json events say the agent is doing, which tool it starts, and text it wrote to the user. */
142
- const events = {
143
- phase(event) {
144
- if (event.type === 'system' || event.type === 'user') return 'thinking';
145
- const block = event.type === 'assistant' ? event.message?.content?.at(-1) : null;
146
- if (block?.type === 'tool_use') return /^(Bash|PowerShell)$/.test(block.name) ? 'command' : EDIT_TOOLS.test(block.name) ? 'editing' : 'tool';
147
- return block?.type === 'text' ? 'writing' : block?.type === 'thinking' ? 'thinking' : '';
148
- },
149
- tool(event) {
150
- const block = event.type === 'assistant' ? event.message?.content?.at(-1) : null;
151
- return block?.type === 'tool_use' ? String(block.name || '') : '';
152
- },
153
- note(event) {
154
- if (event.type !== 'assistant') return '';
155
- return (event.message?.content || []).filter(block => block.type === 'text').map(block => block.text).join('\n').trim();
156
- },
157
- edits(event) {
158
- if (event.type !== 'assistant') return [];
159
- return (event.message?.content || []).filter(block => block.type === 'tool_use' && EDIT_TOOL_NAMES.test(block.name))
160
- .map(block => String(block.input?.file_path || block.input?.notebook_path || '')).filter(Boolean);
161
- },
162
- detail: claude_detail,
163
- };
164
-
165
- /** The one argument that names what a tool call does: its command, file, pattern, query or address. */
166
- function tool_subject(block) {
167
- const input = block.input || {};
168
- const subject = input.command ?? input.file_path ?? input.notebook_path ?? input.pattern ?? input.query ?? input.url ?? input.description;
169
- return typeof subject === 'string' ? subject : JSON.stringify(input);
170
- }
171
-
172
- /** Text of a tool result, which Claude gives as a string or a list of blocks. */
173
- function result_text(content) {
174
- if (typeof content === 'string') return content;
175
- return (Array.isArray(content) ? content : []).map(part => part?.text ?? '').join('\n');
176
- }
177
-
178
- /**
179
- * One stream-json event as execution-detail entries: a tool call and its result share the call's id. Claude Code
180
- * streams thinking as signed blocks with empty text, so thinking shows only when it carries text.
181
- */
182
- function claude_detail(event) {
183
- const blocks = Array.isArray(event.message?.content) ? event.message.content : [];
184
- if (event.type === 'assistant') return blocks.flatMap(block => {
185
- if (block.type === 'text' && block.text?.trim()) return [{ kind: 'message', body: block.text }];
186
- if (block.type === 'thinking' && block.thinking?.trim()) return [{ kind: 'thinking', body: block.thinking }];
187
- if (block.type !== 'tool_use') return [];
188
- const kind = /^(Bash|PowerShell)$/.test(block.name) ? 'command' : EDIT_TOOL_NAMES.test(block.name) ? 'edit'
189
- : /^Web(Search|Fetch)$/.test(block.name) ? 'search' : 'tool';
190
- return [{ id: `tool-${block.id}`, kind, title: kind === 'command' ? tool_subject(block) : `${block.name} ${tool_subject(block)}`, state: 'running' }];
191
- });
192
- if (event.type === 'user') return blocks.filter(block => block.type === 'tool_result')
193
- .map(block => ({ id: `tool-${block.tool_use_id}`, body: result_text(block.content), state: block.is_error ? 'failed' : 'done' }));
194
- if (event.type === 'result' && event.is_error) return [{ kind: 'error', body: String(event.result || event.subtype || '本轮失败') }];
195
- return [];
196
- }
197
-
198
- /**
199
- * The open Claude Code window holding one session, with its cross-session inbox, or null when no live session holds it.
200
- * Read from the registry each running session writes; `inbox` is null on a version without one. Not a public interface:
201
- * the peer token and message line are what Claude's own sessions use (tested on 2.1.312).
202
- */
203
- export function claude_window(session_id, env = process.env) {
204
- const directory = join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
205
- if (!session_id || !existsSync(directory)) return null;
206
- for (const name of readdirSync(directory).filter(item => /^\d+\.json$/.test(item))) {
207
- let record;
208
- try { record = JSON.parse(readFileSync(join(directory, name), 'utf8')); } catch { continue; }
209
- if (record.sessionId !== session_id) continue;
210
- try { process.kill(Number(record.pid), 0); } catch { continue; }
211
- const key = readdirSync(directory).find(item => item.startsWith(`${record.pid}.`) && item.endsWith('.key'));
212
- let token = '';
213
- try { token = key ? JSON.parse(readFileSync(join(directory, key), 'utf8')).peerToken || '' : ''; } catch { /* no inbox credential */ }
214
- return { pid: Number(record.pid), inbox: record.messagingSocketPath && token ? { socket: record.messagingSocketPath, token } : null };
215
- }
216
- return null;
217
- }
218
-
219
- /** Whether this execution goes into a manual member's own open window (taken over with `own` permissions) rather than a background process. */
220
- export function claude_inbox_ready(profile, binding) {
221
- return profile.adapter === 'claude' && profile.project_access === 'own' && Boolean(profile.session_id)
222
- && binding.session_id === profile.session_id && Boolean(claude_window(profile.session_id)?.inbox);
223
- }
224
-
225
- /**
226
- * A taken-over manual Claude member whose session a window without an inbox still holds: resuming that session from
227
- * here would split its file into two branches neither side sees in full, so its first hosted turn forks it and later
228
- * turns resume the fork; a fork whose session was never written is retried under the same ID. Once no window holds
229
- * the session, it is resumed as it is.
230
- */
231
- export function adopted_fork(config, binding, held, exists = id => session_exists(id)) {
232
- if (config.project_access !== 'own' || !config.session_id || binding.fork || !binding.session_id) return binding;
233
- if (binding.session_id !== config.session_id) return exists(binding.session_id) ? binding : { ...binding, fork: { from: config.session_id, at: '' } };
234
- return held ? { ...binding, session_id: randomUUID(), fork: { from: config.session_id, at: '' } } : binding;
235
- }
236
-
237
- /** Post one task into an open Claude window; it starts a turn there, or between tool calls of the turn it is in. */
238
- async function inbox_delivery(config, window, task) {
239
- const { inbox } = window;
240
- try { bind_access(task.access_path, config.session_id); }
241
- catch (error) { throw not_sent(error); }
242
- // Only what the window writes after this point can be the turn that takes this task.
243
- const file = session_path(config.session_id);
244
- const offset = file ? statSync(file).size : 0;
245
- const text = `CoDiscuss 本机服务代房间转达(你已注册为该房间成员,这是房间分派给你的任务):\n${task.prompt}`;
246
- const lines = [{ type: 'auth', token: inbox.token }, { type: 'user', message: { role: 'user', content: text } }];
247
- await new Promise((resolve_sent, reject) => {
248
- let written = false;
249
- const socket = connect(inbox.socket, () => {
250
- socket.end(lines.map(line => `${JSON.stringify(line)}\n`).join(''), () => { written = true; resolve_sent(); });
251
- });
252
- socket.on('error', error => written ? undefined : reject(not_sent(error)));
253
- });
254
- // The discussion runner enters the execution once the session is known, as it does when a process reports it.
255
- task.on_binding?.(config.session_id);
256
- watch_window_turn({ file, offset, pid: window.pid, marker: `${task.id}.task.json` }, task);
257
- return { session_id: config.session_id, status: 'accepted', capabilities: WINDOW };
258
- }
259
-
260
- /**
261
- * Follow a task posted into an open window through the session log, from `offset` on: note once when the window has not
262
- * taken it by INBOX_CHECK_MS, and when the turn that took it ends (or the window closes first), report the API error that
263
- * turn ended on as a failure, otherwise its end, so an answer it never submitted fails the execution instead of hanging.
264
- */
265
- export function watch_window_turn({ file, offset, pid, marker }, task, { interval = WINDOW_POLL_MS, unstarted_after = INBOX_CHECK_MS } = {}) {
266
- const since = Date.now();
267
- let pending = Buffer.alloc(0), taken = false, noted = false, error = null;
268
- const finish = () => {
269
- clearInterval(timer);
270
- if (error) task.on_failure?.(claude_error_reason(error), { retryable: !error.lasting });
271
- else task.on_exit?.();
272
- };
273
- const timer = setInterval(() => {
274
- for (const entry of read_appended()) {
275
- if (!taken) { taken = entry.type === 'user' && prompt_text(entry.message?.content).includes(marker); continue; }
276
- error = claude_api_error(entry) || error;
277
- if (entry.type === 'system' && entry.subtype === 'turn_duration') return finish();
278
- }
279
- if (!process_alive(pid)) return finish();
280
- if (!taken && !noted && Date.now() - since >= unstarted_after) {
281
- noted = true;
282
- task.on_note?.('已投递到原窗口,但它还没开始处理:原窗口可能处于跳过审批模式(需在窗口中批准这条消息)或仍在忙。');
283
- }
284
- }, interval);
285
- timer.unref();
286
- /** Whole lines the log gained since the last read; a line still being written waits for the next. */
287
- function read_appended() {
288
- let size;
289
- try { size = file ? statSync(file).size : 0; } catch { return []; }
290
- if (size <= offset) return [];
291
- const chunk = Buffer.alloc(size - offset), handle = openSync(file, 'r');
292
- try { readSync(handle, chunk, 0, chunk.length, offset); } finally { closeSync(handle); }
293
- offset = size;
294
- pending = Buffer.concat([pending, chunk]);
295
- const end = pending.lastIndexOf(0x0a);
296
- if (end < 0) return [];
297
- const lines = pending.subarray(0, end).toString('utf8').split('\n');
298
- pending = pending.subarray(end + 1);
299
- return lines.map(json_line).filter(Boolean);
300
- }
301
- }
302
-
303
- /** One user message as a stream-json input line. */
304
- function claude_input(text) {
305
- return `${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text }] } })}\n`;
306
- }
307
-
308
- function process_alive(pid) {
309
- try { process.kill(pid, 0); return true; } catch { return false; }
310
- }
311
-
312
- /** Use one official Claude process per turn and resume the persisted session, or post into the member's open window. */
313
- async function deliver(config, binding, task, spawn_process = spawn) {
314
- const window = config.project_access === 'own' && binding.session_id && binding.session_id === config.session_id ? claude_window(config.session_id) : null;
315
- // Only a task written for the window names its credential file; a background process gets it through its environment.
316
- if (window?.inbox && task.inbox) return inbox_delivery(config, window, task);
317
- binding = adopted_fork(config, binding, Boolean(window));
318
- const session_id = binding.session_id || randomUUID();
319
- try { bind_access(task.access_path, session_id); }
320
- catch (error) { throw not_sent(error); }
321
- // Streamed events show the turn's progress; the final line is still the result that decides success.
322
- // A rewound or forked member first forks its earlier session into the ID it is now bound to, cut at `at` when given.
323
- const fork = binding.fork ? ['--resume', binding.fork.from, '--fork-session', ...(binding.fork.at ? ['--resume-session-at', binding.fork.at] : []), '--session-id', session_id]
324
- : [binding.session_id ? '--resume' : '--session-id', session_id];
325
- // The prompt goes in as the first stdin message and stdin stays open, so an interjection can follow while the turn runs.
326
- const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', ...fork,
327
- ...(config.model ? ['--model', config.model] : []), ...(config.effort ? ['--effort', config.effort] : []), ...claude_permissions(config, task)];
328
- let child;
329
- try {
330
- child = spawn_process(config.executable, args, {
331
- cwd: launch_directory(config, task), windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'],
332
- env: { ...standalone_claude_env(), DISCUSS_ACCESS_FILE: task.access_path },
333
- });
334
- } catch (error) { throw not_sent(error); }
335
- tree_killable(child);
336
- let spawned = false;
337
- const log_path = resolve(task.directory, `claude-${task.id}.log`);
338
- let output = '';
339
- let partial_line = '';
340
- child.stdout.on('data', chunk => {
341
- output += chunk;
342
- task.on_output(log_path, chunk);
343
- // With streamed input Claude waits for more after its result; closing stdin lets it exit.
344
- const lines = (partial_line + chunk).split('\n');
345
- partial_line = lines.pop();
346
- if (!child.stdin.writableEnded && lines.some(line => json_line(line)?.type === 'result')) child.stdin.end();
347
- });
348
- child.stdin.on('error', () => { /* A process that already exited takes no more input. */ });
349
- child.stderr.on('data', chunk => task.on_output(log_path, chunk));
350
- watch_events(claude, child.stdout, task);
351
- child.once('close', code => {
352
- if (!spawned) return;
353
- const denials = claude_denials(output);
354
- if (denials.length) task.on_denials?.(denials);
355
- const error = claude_exit_error(code, output);
356
- const api_error = error ? output.split(/\r?\n/).map(json_line).map(claude_api_error).filter(Boolean).at(-1) : null;
357
- if (api_error) task.on_failure(claude_error_reason(api_error), { retryable: !api_error.lasting });
358
- else if (error) task.on_failure(error);
359
- else task.on_exit?.();
360
- });
361
- task.on_process(child);
362
- await new Promise((resolve_spawn, reject) => {
363
- child.once('spawn', () => { spawned = true; resolve_spawn(); });
364
- child.once('error', error => spawned ? task.on_failure(error.message) : reject(not_sent(error)));
365
- });
366
- child.stdin.write(claude_input(task.prompt));
367
- // A failed spawn creates no session; only a successfully started process can be resumed.
368
- task.on_binding(session_id);
369
- // An interjection reaches the turn at its next tool call; text written in one go without tools waits for the next turn.
370
- const steer = text => {
371
- if (child.stdin.writableEnded || child.exitCode !== null) return false;
372
- child.stdin.write(claude_input(text));
373
- task.on_output(log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
374
- return true;
375
- };
376
- return { session_id, status: 'accepted', capabilities: PROCESS, steer };
377
- }
378
-
379
- /** Where Claude keeps one session's log, or '' when this machine has none by that ID. */
380
- function session_path(session_id, env = process.env, home = homedir()) {
381
- const projects = join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'projects');
382
- if (!existsSync(projects)) return '';
383
- return readdirSync(projects).map(dir => join(projects, dir, `${session_id}.jsonl`)).find(existsSync) || '';
384
- }
385
-
386
- /** Whether Claude stored a session by that ID on this machine, e.g. whether a pending fork already happened. */
387
- function session_exists(session_id, { env = process.env, home = homedir() } = {}) {
388
- return Boolean(session_id && session_path(session_id, env, home));
389
- }
390
-
391
- /** The directory a session was made in, from its log; Claude resumes a session only there. '' when it recorded none. */
392
- function session_cwd(session_id, { env = process.env, home = homedir() } = {}) {
393
- const file = session_path(session_id, env, home);
394
- if (!file) return '';
395
- return readFileSync(file, 'utf8').split('\n').map(line => { try { return JSON.parse(line).cwd; } catch { return undefined; } }).find(Boolean) || '';
396
- }
397
-
398
- /** Fork on the next turn at the last answer before the first marked prompt; a cut before any answer starts anew. */
399
- function branch(profile, session_id, markers, { always, env, home }) {
400
- const file = session_path(session_id, env, home);
401
- if (!file) throw new Error(`本机找不到 Claude 会话 ${session_id}`);
402
- const entries = log_entries(file);
403
- const index = entries.findIndex(entry => entry.type === 'user' && marked(prompt_text(entry.message?.content), markers));
404
- if (index < 0) return always ? { session_id: randomUUID(), fork: { from: session_id, at: '' } } : null;
405
- const at = entries.slice(0, index).findLast(entry => entry.type === 'assistant' && entry.uuid)?.uuid;
406
- return at ? { session_id: randomUUID(), fork: { from: session_id, at } } : { session_id: '' };
407
- }
408
-
409
- /** Claude's user settings: what it runs with when the card leaves model or effort empty. */
410
- function defaults(profile, { env = process.env, home = homedir() } = {}) {
411
- try {
412
- const settings = JSON.parse(readFileSync(join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'settings.json'), 'utf8'));
413
- return { model: typeof settings.model === 'string' ? settings.model : '', effort: typeof settings.effortLevel === 'string' ? settings.effortLevel : '' };
414
- } catch { return { model: '', effort: '' }; }
415
- }
416
-
417
- /** The model and effort a session last ran with, from its own log; no turn is started. */
418
- function session_settings(session_id, { env = process.env, home = homedir() } = {}) {
419
- const file = session_path(session_id, env, home);
420
- if (!file) return null;
421
- return newest_record(file, '"type":"api-request"', record => record.type === 'api-request' && CLAUDE_MAIN_SOURCES.includes(record.querySource)
422
- && typeof record.params?.model === 'string' ? { model: record.params.model, effort: String(record.params.output_config?.effort || '') } : null);
423
- }
424
-
425
- /** Claude's initialization exposes its model picker; the query process never persists a session or loads MCP servers. */
426
- function models(profile, options) {
427
- const args = ['--safe-mode', '-p', '--input-format', 'stream-json', '--output-format', 'stream-json',
428
- '--verbose', '--no-session-persistence', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'];
429
- return query_catalog(profile, args, (send, finish) => ({
430
- start: () => send({ type: 'control_request', request_id: 'catalog', request: { subtype: 'initialize' } }),
431
- line: line => {
432
- const reply = json_line(line);
433
- if (reply?.type !== 'control_response' || reply.response?.request_id !== 'catalog') return;
434
- if (reply.response.subtype !== 'success') return finish(new Error('Claude 模型目录查询失败,请检查 CLI 版本与登录'));
435
- finish(null, (reply.response.response?.models || []).map(model => model_entry(model.value, model.displayName,
436
- model.supportedEffortLevels || (model.supportsEffort ? undefined : []))));
437
- },
438
- }), options);
439
- }
440
-
441
- /** Claude Code's behaviour; its static facts are in profiles.mjs. */
442
- export const claude = {
443
- id: 'claude', catalog_source: 'claude-cli',
444
- into_window: claude_inbox_ready,
445
- deliver, events,
446
- session: { path: session_path, exists: session_exists, owns: session_exists, cwd: session_cwd, branch, settings: session_settings },
447
- models: { list: models, defaults },
448
- };
1
+ /**
2
+ * Claude Code adapter: one headless `claude -p` process per turn resuming the bound session, or, for a taken-over manual
3
+ * member whose window is open, a task or private chat line posted into that window. Sessions are branched by Claude's own
4
+ * --fork-session.
5
+ */
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { EventEmitter } from 'node:events';
9
+ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
10
+ import { connect } from 'node:net';
11
+ import { homedir } from 'node:os';
12
+ import { dirname, join, resolve } from 'node:path';
13
+ import { runs_commands } from '../expert_prompts.mjs';
14
+ import { bind_access, DENIAL_FIELD, EDIT_TOOLS, launch_directory, log_entries, marked, MAX_DENIALS, model_entry, json_line,
15
+ newest_record, not_sent, project_directory, prompt_text, query_catalog, TASK_SUBCOMMANDS, tree_killable, watch_events } from './common.mjs';
16
+
17
+ // A message posted to an open Claude window that has not started by then is reported, not failed.
18
+ const INBOX_CHECK_MS = 90_000;
19
+ // How often an open window's session log is read for the end of the turn that took a task.
20
+ const WINDOW_POLL_MS = 3_000;
21
+ // A private chat line posted to an open window fails when the window has not taken it by then, when the window waits on
22
+ // a prompt (an approval, a dialog) that long, or when its turn runs past the limit.
23
+ const CHAT_START_MS = 90_000;
24
+ const CHAT_WAITING_MS = 120_000;
25
+ const CHAT_TURN_MS = 30 * 60_000;
26
+ // Error kinds Claude Code records that a retry a minute later meets again: a used-up plan limit, a lost login.
27
+ const LASTING_ERRORS = ['rate_limit', 'authentication_failed'];
28
+ const EDIT_TOOL_NAMES = /^(Edit|MultiEdit|Write|NotebookEdit)$/;
29
+ // Claude Code logs side queries (titles, compaction, subagents) too; only these sources are the member's own turns.
30
+ const CLAUDE_MAIN_SOURCES = ['sdk', 'repl_main_thread'];
31
+ // A background process can be stopped and streams its progress; a turn in the member's own window does neither.
32
+ const PROCESS = { stoppable: true, progress: true };
33
+ const WINDOW = { stoppable: false, progress: false };
34
+ // A stopped window turn is read this often. Its Esc key waits for a running tool to return first, at most the wait; a
35
+ // turn the key reached that records no end by the end wait was not stopped.
36
+ const STOP_POLL_MS = 200;
37
+ const STOP_TOOL_WAIT_MS = 120_000;
38
+ const STOP_END_WAIT_MS = 15_000;
39
+ // What Claude Code records when Esc ends a turn: while it writes, or while a tool runs (`… for tool use`).
40
+ const INTERRUPTED = /^\[Request interrupted by user/;
41
+ // Attach to one process's console, name its window class and root owner's, and with CODISCUSS_WINDOW_KEY=escape write
42
+ // one Esc press into that console's input buffer only (never the foreground window). Prints one JSON line.
43
+ const CONSOLE_SCRIPT = String.raw`$code = @"
44
+ using System; using System.Text; using System.Runtime.InteropServices;
45
+ public class CodiscussConsole {
46
+ [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)] public struct KEY { [FieldOffset(0)] public int down; [FieldOffset(4)] public short repeat;
47
+ [FieldOffset(6)] public short vk; [FieldOffset(8)] public short scan; [FieldOffset(10)] public char ch; [FieldOffset(12)] public int state; }
48
+ [StructLayout(LayoutKind.Explicit)] public struct RECORD { [FieldOffset(0)] public short type; [FieldOffset(4)] public KEY key; }
49
+ [DllImport("kernel32.dll")] static extern bool FreeConsole();
50
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool AttachConsole(int pid);
51
+ [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow();
52
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern IntPtr CreateFileW(string n, uint a, uint s, IntPtr sa, uint c, uint f, IntPtr t);
53
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern bool WriteConsoleInputW(IntPtr h, RECORD[] r, int n, out int w);
54
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
55
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
56
+ [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint f);
57
+ static string Name(IntPtr w) { var s = new StringBuilder(256); if (w != IntPtr.Zero) GetClassNameW(w, s, 256); return s.ToString(); }
58
+ public static string Run(int pid, bool escape) {
59
+ FreeConsole();
60
+ if (!AttachConsole(pid)) return "{\"attached\":false,\"error\":" + Marshal.GetLastWin32Error() + "}";
61
+ IntPtr w = GetConsoleWindow(); string window = Name(w), owner = Name(GetAncestor(w, 3)); bool written = false;
62
+ if (escape) {
63
+ IntPtr h = CreateFileW("CONIN$", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
64
+ if (h != new IntPtr(-1)) {
65
+ var r = new RECORD[2];
66
+ for (int i = 0; i < 2; i++) { r[i].type = 1; r[i].key.down = i == 0 ? 1 : 0; r[i].key.repeat = 1; r[i].key.vk = 0x1B; r[i].key.scan = 1; r[i].key.ch = (char)0x1B; }
67
+ int n; written = WriteConsoleInputW(h, r, 2, out n) && n == 2; CloseHandle(h);
68
+ }
69
+ }
70
+ FreeConsole();
71
+ return "{\"attached\":true,\"window\":\"" + window + "\",\"owner\":\"" + owner + "\",\"written\":" + (written ? "true" : "false") + "}";
72
+ }
73
+ }
74
+ "@
75
+ Add-Type -TypeDefinition $code
76
+ [Console]::Out.WriteLine([CodiscussConsole]::Run([int]$env:CODISCUSS_WINDOW_PID, $env:CODISCUSS_WINDOW_KEY -eq 'escape'))`;
77
+
78
+ /** Explain why a finished Claude print run failed, including errors reported with exit code 0. */
79
+ export function claude_exit_error(code, output) {
80
+ let result = null;
81
+ try { result = JSON.parse(output.trim().split(/\r?\n/).at(-1)); } catch { /* Non-JSON output keeps the exit code check. */ }
82
+ if (result?.is_error) return `Claude 执行出错:${result.result || result.api_error || result.subtype || '未知错误'}`;
83
+ return code === 0 ? '' : `Claude 退出码 ${code}`;
84
+ }
85
+
86
+ /**
87
+ * The API error Claude Code wrote in place of an answer, from a session log entry or a stream-json event, or null.
88
+ * Its `kind` is Claude's own category (`rate_limit`, `authentication_failed`, `server_error`, ...).
89
+ */
90
+ export function claude_api_error(entry) {
91
+ if (entry?.type !== 'assistant' || !(entry.isApiErrorMessage || entry.is_api_error_message)) return null;
92
+ const text = prompt_text(entry.message?.content).trim();
93
+ const kind = String(entry.error || '');
94
+ return { kind, text: text || String(entry.api_error || kind || '未知错误'), lasting: LASTING_ERRORS.includes(kind) };
95
+ }
96
+
97
+ /** How a Claude API error reads on the failed execution; a lasting one says it is not retried. */
98
+ export function claude_error_reason(error) {
99
+ const label = { rate_limit: 'Claude 用量已达上限', authentication_failed: 'Claude 未登录或登录已失效' }[error.kind] || 'Claude 接口出错';
100
+ return `${label}:${error.text}${error.lasting ? '(不自动重试;恢复后请重新发送)' : ''}`;
101
+ }
102
+
103
+ /** The first program a shell command runs, skipping `cd` and `Set-Location` steps, for a prefix rule that also allows a retry. */
104
+ function command_program(command) {
105
+ const steps = String(command).split(/&&|\|\||;|\|/).map(step => step.trim().split(/\s+/)[0]).filter(Boolean);
106
+ return steps.find(step => !/^(cd|Set-Location|sl|pushd)$/i.test(step)) || steps[0] || '';
107
+ }
108
+
109
+ /**
110
+ * The operations a headless Claude run refused, from the `permission_denials` of its final result line, each with the
111
+ * `--allowedTools` rule that would let the next run do it: a command prefix, an edit of that folder, or the tool itself.
112
+ */
113
+ export function claude_denials(output) {
114
+ let result = null;
115
+ try { result = JSON.parse(output.trim().split(/\r?\n/).at(-1)); } catch { return []; }
116
+ const seen = new Set();
117
+ return (Array.isArray(result?.permission_denials) ? result.permission_denials : []).map(denial => {
118
+ const tool = String(denial.tool_name || '').slice(0, 40), input = denial.tool_input || {};
119
+ if (['Bash', 'PowerShell'].includes(tool) && input.command) {
120
+ const program = command_program(input.command);
121
+ return { tool, detail: String(input.command), rule: program ? `${tool}(${program} *)` : '' };
122
+ }
123
+ const path = input.file_path || input.notebook_path;
124
+ if (EDIT_TOOL_NAMES.test(tool) && path) return { tool, detail: String(path), rule: `Edit(${claude_rule_path(dirname(path))}/**)` };
125
+ return { tool, detail: JSON.stringify(input), rule: tool };
126
+ }).filter(item => item.tool && !seen.has(item.detail) && seen.add(item.detail))
127
+ .slice(0, MAX_DENIALS).map(item => ({ ...item, detail: item.detail.slice(0, DENIAL_FIELD), rule: item.rule.length <= DENIAL_FIELD ? item.rule : '' }));
128
+ }
129
+
130
+ /**
131
+ * The environment for one spawned Claude CLI: variables a hosting Claude session injects are dropped, and the user's
132
+ * persisted login variables, read afresh on Windows, override the ones this long-running process inherited at start,
133
+ * so a token switched with setx or the system settings takes effect on the next turn without restarting the runner.
134
+ */
135
+ export function standalone_claude_env(env = process.env, persisted = persisted_claude_env) {
136
+ const own = env.CLAUDECODE !== '1' ? env : Object.fromEntries(Object.entries(env).filter(([key]) =>
137
+ !/^(CLAUDECODE|CLAUDE_PID|CLAUDE_EFFORT)$|^(CLAUDE_CODE_|CLAUDE_AGENT_SDK_|CLAUDE_PREVIEW_)/.test(key)));
138
+ return { ...own, ...persisted() };
139
+ }
140
+
141
+ /** Read Machine then User persisted ANTHROPIC_/CLAUDE variables on every call; values stay in memory only. */
142
+ function persisted_claude_env() {
143
+ if (process.platform !== 'win32') return {};
144
+ const script = "$r=@{}; foreach($s in 'Machine','User'){ $v=[Environment]::GetEnvironmentVariables($s);"
145
+ + " foreach($k in $v.Keys){ if($k -match '^(ANTHROPIC_|CLAUDE)'){ $r[$k]=$v[$k] } } }; $r | ConvertTo-Json -Compress";
146
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { encoding: 'utf8', windowsHide: true });
147
+ try { return result.status === 0 && result.stdout.trim() ? JSON.parse(result.stdout) : {}; }
148
+ catch { return {}; }
149
+ }
150
+
151
+ /** Claude permission rules match Windows paths in POSIX form, e.g. C:\a becomes //c/a. */
152
+ export function claude_rule_path(directory) {
153
+ const path = resolve(directory).replaceAll('\\', '/').replace(/^([A-Za-z]):/, (_, drive) => `/${drive.toLowerCase()}`);
154
+ return `/${path}`;
155
+ }
156
+
157
+ /**
158
+ * Allow the listed codiscuss website subcommands and draft writes for this run; a writable member also edits its project
159
+ * and runs any command. The room's other project directories (`task.extra_directories`) are added as working
160
+ * directories, edited only where their access is write. User rules are added after. Claude Code on Windows may run
161
+ * commands through its PowerShell tool instead of Bash, so both are listed.
162
+ */
163
+ export function claude_permissions(config, task) {
164
+ const extras = task.extra_directories || [];
165
+ const added = [task.directory, task.draft_directory, ...task.skill_directories, ...extras.map(item => item.path)];
166
+ // A headless run cannot ask for approval: 自动 and a taken-over manual member use auto mode, as the original window
167
+ // does, and 全放开 skips every check; the website commands and drafts stay pre-approved either way.
168
+ if (['own', 'auto', 'full'].includes(config.project_access)) {
169
+ const commands = TASK_SUBCOMMANDS.flatMap(command => [`Bash(codiscuss ${command} *)`, `PowerShell(codiscuss ${command} *)`]);
170
+ return ['--permission-mode', config.project_access === 'full' ? 'bypassPermissions' : 'auto', '--add-dir', ...added, '--allowedTools',
171
+ ...commands, `Edit(${claude_rule_path(task.draft_directory)}/**)`, ...(config.allowed_tools || []), ...edit_denial(task)];
172
+ }
173
+ const commands = runs_commands(config, extras) ? ['Bash', 'PowerShell']
174
+ : TASK_SUBCOMMANDS.flatMap(command => [`Bash(codiscuss ${command} *)`, `PowerShell(codiscuss ${command} *)`]);
175
+ const writable = [task.draft_directory, ...(runs_commands(config, extras)
176
+ ? [project_directory(config), ...extras.filter(item => item.access === 'write').map(item => item.path)].filter(Boolean) : [])];
177
+ return ['--add-dir', ...added, '--allowedTools',
178
+ ...commands, ...writable.map(directory => `Edit(${claude_rule_path(directory)}/**)`), ...(config.allowed_tools || []), ...edit_denial(task)];
179
+ }
180
+
181
+ /**
182
+ * Skill folders (the shared skills and an enabled workflow) are read, never edited, and so are the room's project
183
+ * directories this member may only read. This stops Claude's own edit tools only; a command the member may run can
184
+ * still write there, and Windows has no native sandbox to prevent it.
185
+ */
186
+ function edit_denial(task) {
187
+ const read_only = (task.extra_directories || []).filter(item => item.access === 'read').map(item => item.path);
188
+ return ['--disallowedTools', ...[...task.skill_directories, ...read_only].map(directory => `Edit(${claude_rule_path(directory)}/**)`)];
189
+ }
190
+
191
+ /** What Claude's stream-json events say the agent is doing, which tool it starts, and text it wrote to the user. */
192
+ const events = {
193
+ phase(event) {
194
+ if (event.type === 'system' || event.type === 'user') return 'thinking';
195
+ const block = event.type === 'assistant' ? event.message?.content?.at(-1) : null;
196
+ if (block?.type === 'tool_use') return /^(Bash|PowerShell)$/.test(block.name) ? 'command' : EDIT_TOOLS.test(block.name) ? 'editing' : 'tool';
197
+ return block?.type === 'text' ? 'writing' : block?.type === 'thinking' ? 'thinking' : '';
198
+ },
199
+ tool(event) {
200
+ const block = event.type === 'assistant' ? event.message?.content?.at(-1) : null;
201
+ return block?.type === 'tool_use' ? String(block.name || '') : '';
202
+ },
203
+ note(event) {
204
+ if (event.type !== 'assistant') return '';
205
+ return (event.message?.content || []).filter(block => block.type === 'text').map(block => block.text).join('\n').trim();
206
+ },
207
+ edits(event) {
208
+ if (event.type !== 'assistant') return [];
209
+ return (event.message?.content || []).filter(block => block.type === 'tool_use' && EDIT_TOOL_NAMES.test(block.name))
210
+ .map(block => String(block.input?.file_path || block.input?.notebook_path || '')).filter(Boolean);
211
+ },
212
+ detail: claude_detail,
213
+ };
214
+
215
+ /** The one argument that names what a tool call does: its command, file, pattern, query or address. */
216
+ function tool_subject(block) {
217
+ const input = block.input || {};
218
+ const subject = input.command ?? input.file_path ?? input.notebook_path ?? input.pattern ?? input.query ?? input.url ?? input.description;
219
+ return typeof subject === 'string' ? subject : JSON.stringify(input);
220
+ }
221
+
222
+ /** Text of a tool result, which Claude gives as a string or a list of blocks. */
223
+ function result_text(content) {
224
+ if (typeof content === 'string') return content;
225
+ return (Array.isArray(content) ? content : []).map(part => part?.text ?? '').join('\n');
226
+ }
227
+
228
+ /**
229
+ * One stream-json event as execution-detail entries: a tool call and its result share the call's id. Claude Code
230
+ * streams thinking as signed blocks with empty text, so thinking shows only when it carries text.
231
+ */
232
+ function claude_detail(event) {
233
+ const blocks = Array.isArray(event.message?.content) ? event.message.content : [];
234
+ if (event.type === 'assistant') return blocks.flatMap(block => {
235
+ if (block.type === 'text' && block.text?.trim()) return [{ kind: 'message', body: block.text }];
236
+ if (block.type === 'thinking' && block.thinking?.trim()) return [{ kind: 'thinking', body: block.thinking }];
237
+ if (block.type !== 'tool_use') return [];
238
+ const kind = /^(Bash|PowerShell)$/.test(block.name) ? 'command' : EDIT_TOOL_NAMES.test(block.name) ? 'edit'
239
+ : /^Web(Search|Fetch)$/.test(block.name) ? 'search' : 'tool';
240
+ return [{ id: `tool-${block.id}`, kind, title: kind === 'command' ? tool_subject(block) : `${block.name} ${tool_subject(block)}`, state: 'running' }];
241
+ });
242
+ if (event.type === 'user') return blocks.filter(block => block.type === 'tool_result')
243
+ .map(block => ({ id: `tool-${block.tool_use_id}`, body: result_text(block.content), state: block.is_error ? 'failed' : 'done' }));
244
+ if (event.type === 'result' && event.is_error) return [{ kind: 'error', body: String(event.result || event.subtype || '本轮失败') }];
245
+ return [];
246
+ }
247
+
248
+ /**
249
+ * The open Claude Code window holding one session, with its cross-session inbox, or null when no live session holds it.
250
+ * Read from the registry each running session writes; `inbox` is null on a version without one. Not a public interface:
251
+ * the peer token and message line are what Claude's own sessions use (tested on 2.1.312).
252
+ */
253
+ export function claude_window(session_id, env = process.env) {
254
+ const directory = join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
255
+ if (!session_id || !existsSync(directory)) return null;
256
+ for (const name of readdirSync(directory).filter(item => /^\d+\.json$/.test(item))) {
257
+ let record;
258
+ try { record = JSON.parse(readFileSync(join(directory, name), 'utf8')); } catch { continue; }
259
+ if (record.sessionId !== session_id) continue;
260
+ try { process.kill(Number(record.pid), 0); } catch { continue; }
261
+ const key = readdirSync(directory).find(item => item.startsWith(`${record.pid}.`) && item.endsWith('.key'));
262
+ let token = '';
263
+ try { token = key ? JSON.parse(readFileSync(join(directory, key), 'utf8')).peerToken || '' : ''; } catch { /* no inbox credential */ }
264
+ return { pid: Number(record.pid), inbox: record.messagingSocketPath && token ? { socket: record.messagingSocketPath, token } : null };
265
+ }
266
+ return null;
267
+ }
268
+
269
+ /**
270
+ * The console an open Claude window runs in, and with `escape` one Esc key press written into its input, which Claude
271
+ * Code takes as the stop of the turn it runs. Windows only. Returns `{ok, terminal, reason}`: `terminal` is `conhost`
272
+ * or `Windows Terminal` when the console window says which, `reason` why it could not attach or write.
273
+ */
274
+ export function window_console(pid, { escape = false, run = spawnSync, platform = process.platform } = {}) {
275
+ if (platform !== 'win32') return { ok: false, terminal: '', reason: '只有 Windows 上能向 Claude 窗口发送停止键' };
276
+ const result = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(CONSOLE_SCRIPT, 'utf16le').toString('base64')], {
277
+ encoding: 'utf8', windowsHide: true, timeout: 20_000,
278
+ env: { ...process.env, CODISCUSS_WINDOW_PID: String(pid), CODISCUSS_WINDOW_KEY: escape ? 'escape' : '' } });
279
+ const reply = json_line(String(result.stdout || '').trim().split(/\r?\n/).at(-1) || '');
280
+ if (!reply) return { ok: false, terminal: '', reason: `无法连接到这个 Claude 窗口的控制台(PowerShell 没有返回结果:${String(result.stderr || result.error?.message || result.status).trim().slice(0, 200)})` };
281
+ const terminal = reply.window === 'ConsoleWindowClass' ? 'conhost' : reply.owner === 'CASCADIA_HOSTING_WINDOW_CLASS' ? 'Windows Terminal' : String(reply.window || '');
282
+ if (!reply.attached) return { ok: false, terminal, reason: `无法连接到这个 Claude 窗口的控制台(AttachConsole 错误 ${reply.error})` };
283
+ if (escape && !reply.written) return { ok: false, terminal, reason: `未能向这个 Claude 窗口(${terminal || '未知终端'})写入停止键` };
284
+ return { ok: true, terminal, reason: '' };
285
+ }
286
+
287
+ /** Whether this execution goes into a manual member's own open window (taken over with `own` permissions) rather than a background process. */
288
+ export function claude_inbox_ready(profile, binding) {
289
+ return profile.adapter === 'claude' && profile.project_access === 'own' && Boolean(profile.session_id)
290
+ && binding.session_id === profile.session_id && Boolean(claude_window(profile.session_id)?.inbox);
291
+ }
292
+
293
+ /**
294
+ * A taken-over manual Claude member whose session a window without an inbox still holds: resuming that session from
295
+ * here would split its file into two branches neither side sees in full, so its first hosted turn forks it and later
296
+ * turns resume the fork; a fork whose session was never written is retried under the same ID. Once no window holds
297
+ * the session, it is resumed as it is.
298
+ */
299
+ export function adopted_fork(config, binding, held, exists = id => session_exists(id)) {
300
+ if (config.project_access !== 'own' || !config.session_id || binding.fork || !binding.session_id) return binding;
301
+ if (binding.session_id !== config.session_id) return exists(binding.session_id) ? binding : { ...binding, fork: { from: config.session_id, at: '' } };
302
+ return held ? { ...binding, session_id: randomUUID(), fork: { from: config.session_id, at: '' } } : binding;
303
+ }
304
+
305
+ /**
306
+ * Write lines into an open window's inbox: an `auth` line with its peer token, then one `user` message. The inbox is not
307
+ * a public interface of Claude Code, so a failure says so; the window wraps every message as one from another session.
308
+ */
309
+ async function post_inbox(inbox, text) {
310
+ const lines = [{ type: 'auth', token: inbox.token }, { type: 'user', message: { role: 'user', content: text } }];
311
+ await new Promise((resolve_sent, reject) => {
312
+ let written = false;
313
+ const socket = connect(inbox.socket, () => {
314
+ socket.end(lines.map(line => `${JSON.stringify(line)}\n`).join(''), () => { written = true; resolve_sent(); });
315
+ });
316
+ socket.on('error', error => written ? undefined : reject(not_sent(new Error(
317
+ `无法投递到 Claude 原窗口:它的跨会话收件箱不是 Claude Code 的公开接口,可能已随版本变化或被关闭(${error.message})`))));
318
+ });
319
+ }
320
+
321
+ /** Post one task into an open Claude window; it starts a turn there, or between tool calls of the turn it is in. */
322
+ async function inbox_delivery(config, window, task) {
323
+ try { bind_access(task.access_path, config.session_id); }
324
+ catch (error) { throw not_sent(error); }
325
+ // Only what the window writes after this point can be the turn that takes this task.
326
+ const file = session_path(config.session_id);
327
+ const offset = file ? statSync(file).size : 0;
328
+ await post_inbox(window.inbox, `CoDiscuss 本机服务代房间转达(你已注册为该房间成员,这是房间分派给你的任务):\n${task.prompt}`);
329
+ // The discussion runner enters the execution once the session is known, as it does when a process reports it.
330
+ task.on_binding?.(config.session_id);
331
+ watch_window_turn({ file, offset, pid: window.pid, marker: `${task.id}.task.json` }, task);
332
+ return { session_id: config.session_id, status: 'accepted', capabilities: WINDOW };
333
+ }
334
+
335
+ /**
336
+ * The window a manual member's bound session is open in, or null: only a taken-over manual member (`own`) still bound
337
+ * to its original session can be in one.
338
+ */
339
+ function held_window(config, binding) {
340
+ return config.project_access === 'own' && binding.session_id && binding.session_id === config.session_id ? claude_window(config.session_id) : null;
341
+ }
342
+
343
+ // The window shows every inbox message as one from another Claude session, not typed by its user; these leads say whose
344
+ // words they are and that the answer is the turn's own text.
345
+ const CHAT_WINDOW_LEAD = '以下是房主(也就是你的用户)在 CoDiscuss 私聊窗里对你说的原话,由本机服务转达到这个窗口。请像用户在这里直接输入一样处理,在本轮的文字回复里直接回答,不要用 SendMessage 回复。';
346
+ const CHAT_STEER_LEAD = '房主(也就是你的用户)刚在 CoDiscuss 私聊窗里插话,原话如下。这是对你当前这轮工作的追加要求,不是其他会话的来信:请在本轮最后的文字回复里直接回应它,不要用 SendMessage 回复。';
347
+
348
+ /**
349
+ * One private chat turn of a Claude member. With the member's window open, the owner's words go through its inbox and
350
+ * the turn is read from the session log; with no window, the session is resumed in the background, which a closed
351
+ * window sees in full when it is opened again. A window without an inbox fails instead: resuming beside it would split
352
+ * the session into two branches. A window turn stops by an Esc key written into the window's console, when that console
353
+ * can be reached; `options.console` replaces that console in tests.
354
+ */
355
+ async function chat(config, binding, task, spawn_process = spawn, user_home, options = {}) {
356
+ const window = held_window(config, binding);
357
+ if (!window) return deliver(config, binding, task, spawn_process);
358
+ if (!window.inbox) throw not_sent(new Error('这位成员的 Claude 窗口开着,但没有可用的跨会话收件箱(版本不支持或已关闭),私聊无法送进去;请在它的窗口里直接对话,或关闭窗口后再发'));
359
+ const session_id = config.session_id;
360
+ const file = session_path(session_id);
361
+ const offset = file ? statSync(file).size : 0;
362
+ const log_path = resolve(task.directory, `claude-${task.id}.log`);
363
+ const marker = `[codiscuss:${task.id}]`;
364
+ const console_of = options.console || window_console;
365
+ const reached = console_of(window.pid);
366
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.window', terminal: reached.terminal, stoppable: reached.ok, reason: reached.reason })}\n`);
367
+ const handle = new EventEmitter();
368
+ const watcher = watch_window_turn({ file, offset, pid: window.pid, marker, session_id, log_path }, task, {
369
+ chat: true, on_end: () => handle.emit('close', 0),
370
+ stop_key: () => {
371
+ const sent = console_of(window.pid, { escape: true });
372
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.stop', terminal: sent.terminal, sent: sent.ok, reason: sent.reason })}\n`);
373
+ return sent;
374
+ } });
375
+ try { await post_inbox(window.inbox, `${marker} ${CHAT_WINDOW_LEAD}\n\n${task.prompt}`); }
376
+ catch (error) { watcher.cancel(); throw error; }
377
+ if (reached.ok) {
378
+ handle.kill = () => watcher.stop();
379
+ // The Esc key goes into the owner's own window; only the owner's stop sends it, never the runner's shutdown.
380
+ handle.stop_on_shutdown = false;
381
+ task.on_process?.(handle);
382
+ }
383
+ let count = 0;
384
+ // Each interjection carries its own marker; the watch then also waits for the turn that takes it.
385
+ const steer = async text => {
386
+ const tag = `[codiscuss:${task.id}+${++count}]`;
387
+ if (!watcher.expect(tag)) return false;
388
+ try { await post_inbox(window.inbox, `${tag} ${CHAT_STEER_LEAD}\n\n${text}`); }
389
+ catch { watcher.forget(tag); return false; }
390
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
391
+ return true;
392
+ };
393
+ return { session_id, status: 'accepted', capabilities: { stoppable: reached.ok, progress: true }, steer };
394
+ }
395
+
396
+ /**
397
+ * Whether a session-log entry is the window taking a message carrying `marker`: the prompt of a turn it started, or a
398
+ * message it took between the tool calls of a turn already running (`queued_command`).
399
+ */
400
+ function takes(entry, marker) {
401
+ if (entry.type === 'user') return prompt_text(entry.message?.content).includes(marker);
402
+ return entry.type === 'attachment' && entry.attachment?.type === 'queued_command' && prompt_text(entry.attachment.prompt).includes(marker);
403
+ }
404
+
405
+ /** The state an open window last recorded in the session registry (`busy`, `idle`, or `waiting` with `waitingFor`), or null. */
406
+ function window_state(pid, env = process.env) {
407
+ try { return JSON.parse(readFileSync(join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'sessions', `${pid}.json`), 'utf8')); }
408
+ catch { return null; }
409
+ }
410
+
411
+ /**
412
+ * Follow a message posted into an open window through the session log, from `offset` on, until the turn that took it
413
+ * ends (`system/turn_duration`) or the window closes: report the API error that turn ended on as a failure, otherwise its
414
+ * end. For a room task it notes once when the window has not taken it by `unstarted_after`; an answer it never submitted
415
+ * then fails the execution. For a `chat` turn it reports the turn's steps to `log_path` and its texts as notes, waits
416
+ * also for every interjection `expect`ed, and fails with the reason when the window does not take the message in time,
417
+ * waits on a prompt for `waiting_after`, closes, or runs past `turn_limit`. A turn Esc ended (`[Request interrupted by
418
+ * user…]`, which records no `turn_duration`) ends the watch too. `stop()` asks the turn to stop: `stop_key()` sends one
419
+ * Esc key, only while the registry says the window is busy, the turn has not ended, and no tool call waits for its result
420
+ * (Esc during a tool reads as the user refusing that call); it waits at most `stop_tool_wait` for that. `on_end` runs when
421
+ * the watch ends. Returns `{expect, forget, stop, cancel, done}`.
422
+ */
423
+ export function watch_window_turn({ file, offset, pid, marker, session_id = '', log_path = '' }, task, options = {}) {
424
+ const { interval = WINDOW_POLL_MS, unstarted_after = INBOX_CHECK_MS, chat = false, start_after = CHAT_START_MS,
425
+ waiting_after = CHAT_WAITING_MS, turn_limit = CHAT_TURN_MS, env = process.env, on_end, stop_key,
426
+ stop_poll = STOP_POLL_MS, stop_tool_wait = STOP_TOOL_WAIT_MS, stop_end_wait = STOP_END_WAIT_MS } = options;
427
+ const since = Date.now(), awaited = new Set([marker]), open_tools = new Set();
428
+ let pending = Buffer.alloc(0), taken = false, noted = false, error = null, done = false, waiting_since = 0;
429
+ let stop_asked = 0, stop_sent = 0, stop_timer = null;
430
+ const finish = (reason = '') => {
431
+ if (done) return;
432
+ done = true;
433
+ clearInterval(timer); clearInterval(stop_timer);
434
+ if (error) task.on_failure?.(claude_error_reason(error), { retryable: !error.lasting });
435
+ else if (reason) task.on_failure?.(reason);
436
+ else task.on_exit?.();
437
+ on_end?.();
438
+ };
439
+ const tick = () => {
440
+ if (done) return;
441
+ for (const entry of read_appended()) {
442
+ for (const item of awaited) if (takes(entry, item)) { awaited.delete(item); taken = true; }
443
+ if (!taken) continue;
444
+ if (entry.type === 'user' && INTERRUPTED.test(prompt_text(entry.message?.content).trim())) {
445
+ return finish(!chat ? '' : stop_asked ? '已停止' : '这一轮在 Claude 窗口里被中断了');
446
+ }
447
+ const api_error = claude_api_error(entry);
448
+ error = api_error || error;
449
+ if (chat && !api_error) report(entry);
450
+ if (!entry.isSidechain) track_tools(entry);
451
+ if (entry.type === 'system' && entry.subtype === 'turn_duration' && !awaited.size) return finish();
452
+ }
453
+ if (!process_alive(pid)) return finish(chat ? '这位成员的 Claude 窗口在这轮私聊结束前关闭了' : '');
454
+ if (stop_asked) return try_stop();
455
+ const elapsed = Date.now() - since;
456
+ if (!chat) {
457
+ if (!taken && !noted && elapsed >= unstarted_after) {
458
+ noted = true;
459
+ task.on_note?.('已投递到原窗口,但它还没开始处理:原窗口可能处于跳过审批模式(需在窗口中批准这条消息)或仍在忙。');
460
+ }
461
+ return;
462
+ }
463
+ const state = window_state(pid, env);
464
+ waiting_since = state?.status === 'waiting' ? waiting_since || Date.now() : 0;
465
+ if (waiting_since && Date.now() - waiting_since >= waiting_after) {
466
+ return finish(`这位成员的 Claude 窗口停在“${state.waitingFor || '等待确认'}”超过 ${Math.round(waiting_after / 1000)} 秒(可能在等你批准一项操作),请到窗口里处理后重新发送`);
467
+ }
468
+ if (!taken && elapsed >= start_after) {
469
+ return finish(`已投递到这位成员的 Claude 窗口,但 ${Math.round(start_after / 1000)} 秒内它没有开始处理:窗口可能在等你确认这条消息、仍在忙,或跨会话收件箱(非公开接口)已变化`);
470
+ }
471
+ if (elapsed >= turn_limit) finish(`这轮私聊在 Claude 窗口里超过 ${Math.round(turn_limit / 60_000)} 分钟仍未结束,已停止等待`);
472
+ };
473
+ const timer = setInterval(tick, interval);
474
+ timer.unref();
475
+ /** Pass one entry of the turn on: its steps to the process log in the stream-json shape, its text as a remark. */
476
+ function report(entry) {
477
+ if (entry.isSidechain || !['assistant', 'user'].includes(entry.type)) return;
478
+ if (log_path) task.on_output?.(log_path, `${JSON.stringify({ type: entry.type, message: entry.message })}\n`);
479
+ const note = events.note(entry);
480
+ if (note) task.on_note?.(note);
481
+ }
482
+ /** Whole lines the log gained since the last read; a line still being written waits for the next. */
483
+ function read_appended() {
484
+ // A window that has not written its session yet creates the log with the first message it takes.
485
+ if (!file && session_id) file = session_path(session_id, env);
486
+ let size;
487
+ try { size = file ? statSync(file).size : 0; } catch { return []; }
488
+ if (size <= offset) return [];
489
+ const chunk = Buffer.alloc(size - offset), handle = openSync(file, 'r');
490
+ try { readSync(handle, chunk, 0, chunk.length, offset); } finally { closeSync(handle); }
491
+ offset = size;
492
+ pending = Buffer.concat([pending, chunk]);
493
+ const end = pending.lastIndexOf(0x0a);
494
+ if (end < 0) return [];
495
+ const lines = pending.subarray(0, end).toString('utf8').split('\n');
496
+ pending = pending.subarray(end + 1);
497
+ return lines.map(json_line).filter(Boolean);
498
+ }
499
+ /** Note the tool calls of the turn that have not returned yet. */
500
+ function track_tools(entry) {
501
+ for (const block of Array.isArray(entry.message?.content) ? entry.message.content : []) {
502
+ if (entry.type === 'assistant' && block?.type === 'tool_use') open_tools.add(block.id);
503
+ if (entry.type === 'user' && block?.type === 'tool_result') open_tools.delete(block.tool_use_id);
504
+ }
505
+ }
506
+ /** Send the one Esc key of a stop once the turn can take it, or say why the turn was not stopped. */
507
+ function try_stop() {
508
+ const now = Date.now();
509
+ if (stop_sent) {
510
+ if (now - stop_sent >= stop_end_wait) finish('已向 Claude 窗口发送停止键,但这一轮仍未结束');
511
+ return;
512
+ }
513
+ const ready = taken && !open_tools.size && window_state(pid, env)?.status === 'busy';
514
+ if (!ready) {
515
+ if (now - stop_asked >= stop_tool_wait) finish(open_tools.size ? '工具仍在执行,未能停止' : !taken ? '消息还在 Claude 窗口的队列里,未能停止' : 'Claude 窗口一直没有处于执行中,未能停止');
516
+ return;
517
+ }
518
+ stop_sent = now;
519
+ const sent = stop_key?.() || { ok: false, reason: '无法向 Claude 窗口发送停止键' };
520
+ if (!sent.ok) finish(sent.reason);
521
+ }
522
+ return {
523
+ get done() { return done; },
524
+ expect(item) { if (done) return false; awaited.add(item); return true; },
525
+ forget(item) { awaited.delete(item); },
526
+ stop() {
527
+ if (done) return false;
528
+ if (!stop_asked) { stop_asked = Date.now(); stop_timer = setInterval(tick, stop_poll); stop_timer.unref(); setImmediate(tick); }
529
+ return true;
530
+ },
531
+ cancel() { done = true; clearInterval(timer); clearInterval(stop_timer); },
532
+ };
533
+ }
534
+
535
+ /** One user message as a stream-json input line. */
536
+ function claude_input(text) {
537
+ return `${JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text }] } })}\n`;
538
+ }
539
+
540
+ function process_alive(pid) {
541
+ try { process.kill(pid, 0); return true; } catch { return false; }
542
+ }
543
+
544
+ /** Use one official Claude process per turn and resume the persisted session, or post into the member's open window. */
545
+ async function deliver(config, binding, task, spawn_process = spawn) {
546
+ const window = held_window(config, binding);
547
+ // Only a task written for the window names its credential file; a background process gets it through its environment.
548
+ if (window?.inbox && task.inbox) return inbox_delivery(config, window, task);
549
+ binding = adopted_fork(config, binding, Boolean(window));
550
+ const session_id = binding.session_id || randomUUID();
551
+ try { bind_access(task.access_path, session_id); }
552
+ catch (error) { throw not_sent(error); }
553
+ // Streamed events show the turn's progress; the final line is still the result that decides success.
554
+ // A rewound or forked member first forks its earlier session into the ID it is now bound to, cut at `at` when given.
555
+ const fork = binding.fork ? ['--resume', binding.fork.from, '--fork-session', ...(binding.fork.at ? ['--resume-session-at', binding.fork.at] : []), '--session-id', session_id]
556
+ : [binding.session_id ? '--resume' : '--session-id', session_id];
557
+ // The prompt goes in as the first stdin message and stdin stays open, so an interjection can follow while the turn runs.
558
+ const args = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', ...fork,
559
+ ...(config.model ? ['--model', config.model] : []), ...(config.effort ? ['--effort', config.effort] : []), ...claude_permissions(config, task)];
560
+ let child;
561
+ try {
562
+ child = spawn_process(config.executable, args, {
563
+ cwd: launch_directory(config, task), windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'],
564
+ env: { ...standalone_claude_env(), DISCUSS_ACCESS_FILE: task.access_path },
565
+ });
566
+ } catch (error) { throw not_sent(error); }
567
+ tree_killable(child);
568
+ let spawned = false;
569
+ const log_path = resolve(task.directory, `claude-${task.id}.log`);
570
+ let output = '';
571
+ let partial_line = '';
572
+ child.stdout.on('data', chunk => {
573
+ output += chunk;
574
+ task.on_output(log_path, chunk);
575
+ // With streamed input Claude waits for more after its result; closing stdin lets it exit.
576
+ const lines = (partial_line + chunk).split('\n');
577
+ partial_line = lines.pop();
578
+ if (!child.stdin.writableEnded && lines.some(line => json_line(line)?.type === 'result')) child.stdin.end();
579
+ });
580
+ child.stdin.on('error', () => { /* A process that already exited takes no more input. */ });
581
+ child.stderr.on('data', chunk => task.on_output(log_path, chunk));
582
+ watch_events(claude, child.stdout, task);
583
+ child.once('close', code => {
584
+ if (!spawned) return;
585
+ const denials = claude_denials(output);
586
+ if (denials.length) task.on_denials?.(denials);
587
+ const error = claude_exit_error(code, output);
588
+ const api_error = error ? output.split(/\r?\n/).map(json_line).map(claude_api_error).filter(Boolean).at(-1) : null;
589
+ if (api_error) task.on_failure(claude_error_reason(api_error), { retryable: !api_error.lasting });
590
+ else if (error) task.on_failure(error);
591
+ else task.on_exit?.();
592
+ });
593
+ task.on_process(child);
594
+ await new Promise((resolve_spawn, reject) => {
595
+ child.once('spawn', () => { spawned = true; resolve_spawn(); });
596
+ child.once('error', error => spawned ? task.on_failure(error.message) : reject(not_sent(error)));
597
+ });
598
+ child.stdin.write(claude_input(task.prompt));
599
+ // A failed spawn creates no session; only a successfully started process can be resumed.
600
+ task.on_binding(session_id);
601
+ // An interjection reaches the turn at its next tool call; text written in one go without tools waits for the next turn.
602
+ const steer = text => {
603
+ if (child.stdin.writableEnded || child.exitCode !== null) return false;
604
+ child.stdin.write(claude_input(text));
605
+ task.on_output(log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
606
+ return true;
607
+ };
608
+ return { session_id, status: 'accepted', capabilities: PROCESS, steer };
609
+ }
610
+
611
+ /** Where Claude keeps one session's log, or '' when this machine has none by that ID. */
612
+ function session_path(session_id, env = process.env, home = homedir()) {
613
+ const projects = join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'projects');
614
+ if (!existsSync(projects)) return '';
615
+ return readdirSync(projects).map(dir => join(projects, dir, `${session_id}.jsonl`)).find(existsSync) || '';
616
+ }
617
+
618
+ /** Whether Claude stored a session by that ID on this machine, e.g. whether a pending fork already happened. */
619
+ function session_exists(session_id, { env = process.env, home = homedir() } = {}) {
620
+ return Boolean(session_id && session_path(session_id, env, home));
621
+ }
622
+
623
+ /** The directory a session was made in, from its log; Claude resumes a session only there. '' when it recorded none. */
624
+ function session_cwd(session_id, { env = process.env, home = homedir() } = {}) {
625
+ const file = session_path(session_id, env, home);
626
+ if (!file) return '';
627
+ return readFileSync(file, 'utf8').split('\n').map(line => { try { return JSON.parse(line).cwd; } catch { return undefined; } }).find(Boolean) || '';
628
+ }
629
+
630
+ /** Fork on the next turn at the last answer before the first marked prompt; a cut before any answer starts anew. */
631
+ function branch(profile, session_id, markers, { always, env, home }) {
632
+ const file = session_path(session_id, env, home);
633
+ if (!file) throw new Error(`本机找不到 Claude 会话 ${session_id}`);
634
+ const entries = log_entries(file);
635
+ const index = entries.findIndex(entry => entry.type === 'user' && marked(prompt_text(entry.message?.content), markers));
636
+ if (index < 0) return always ? { session_id: randomUUID(), fork: { from: session_id, at: '' } } : null;
637
+ const at = entries.slice(0, index).findLast(entry => entry.type === 'assistant' && entry.uuid)?.uuid;
638
+ return at ? { session_id: randomUUID(), fork: { from: session_id, at } } : { session_id: '' };
639
+ }
640
+
641
+ /** Claude's user settings: what it runs with when the card leaves model or effort empty. */
642
+ function defaults(profile, { env = process.env, home = homedir() } = {}) {
643
+ try {
644
+ const settings = JSON.parse(readFileSync(join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), 'settings.json'), 'utf8'));
645
+ return { model: typeof settings.model === 'string' ? settings.model : '', effort: typeof settings.effortLevel === 'string' ? settings.effortLevel : '' };
646
+ } catch { return { model: '', effort: '' }; }
647
+ }
648
+
649
+ /** The model and effort a session last ran with, from its own log; no turn is started. */
650
+ function session_settings(session_id, { env = process.env, home = homedir() } = {}) {
651
+ const file = session_path(session_id, env, home);
652
+ if (!file) return null;
653
+ return newest_record(file, '"type":"api-request"', record => record.type === 'api-request' && CLAUDE_MAIN_SOURCES.includes(record.querySource)
654
+ && typeof record.params?.model === 'string' ? { model: record.params.model, effort: String(record.params.output_config?.effort || '') } : null);
655
+ }
656
+
657
+ /** Claude's initialization exposes its model picker; the query process never persists a session or loads MCP servers. */
658
+ function models(profile, options) {
659
+ const args = ['--safe-mode', '-p', '--input-format', 'stream-json', '--output-format', 'stream-json',
660
+ '--verbose', '--no-session-persistence', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'];
661
+ return query_catalog(profile, args, (send, finish) => ({
662
+ start: () => send({ type: 'control_request', request_id: 'catalog', request: { subtype: 'initialize' } }),
663
+ line: line => {
664
+ const reply = json_line(line);
665
+ if (reply?.type !== 'control_response' || reply.response?.request_id !== 'catalog') return;
666
+ if (reply.response.subtype !== 'success') return finish(new Error('Claude 模型目录查询失败,请检查 CLI 版本与登录'));
667
+ finish(null, (reply.response.response?.models || []).map(model => model_entry(model.value, model.displayName,
668
+ model.supportedEffortLevels || (model.supportsEffort ? undefined : []))));
669
+ },
670
+ }), options);
671
+ }
672
+
673
+ /** Claude Code's behaviour; its static facts are in profiles.mjs. */
674
+ export const claude = {
675
+ id: 'claude', catalog_source: 'claude-cli',
676
+ into_window: claude_inbox_ready,
677
+ deliver, chat, events,
678
+ session: { path: session_path, exists: session_exists, owns: session_exists, cwd: session_cwd, branch, settings: session_settings },
679
+ models: { list: models, defaults },
680
+ };