ai_co_discuss 0.3.71 → 0.3.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/free_room.py +81 -9
- package/backend/schema.sql +1675 -1645
- package/backend/server.py +19 -8
- package/docs/runner.md +12 -1
- package/package.json +1 -1
- package/runner/adapters/antigravity_cli.mjs +37 -7
- package/runner/adapters/api.mjs +25 -4
- package/runner/adapters/api_files.mjs +36 -19
- package/runner/adapters/claude.mjs +448 -385
- package/runner/adapters/cli.mjs +175 -155
- package/runner/adapters/codex_app.mjs +19 -3
- package/runner/adapters/codex_bridge.mjs +123 -0
- package/runner/adapters/codex_cli.mjs +47 -10
- package/runner/adapters/index.mjs +34 -2
- package/runner/adapters/profiles.mjs +5 -3
- package/runner/device_auth.mjs +39 -21
- package/runner/discussion_launch.mjs +83 -21
- package/runner/discussion_local.mjs +2 -0
- package/runner/discussion_runner.mjs +34 -1
- package/runner/discussion_service.mjs +6 -3
- package/runner/expert_prompts.mjs +21 -11
- package/runner/free_runner.mjs +73 -14
- package/runner/project_files.mjs +57 -5
- package/runner/relay_channel.mjs +4 -3
- package/runner/remote_launch.mjs +268 -268
- package/runner/remote_policy.mjs +2 -1
- package/web/app.js +4955 -4862
- package/web/backup.js +1 -1
- package/web/modern.css +1 -1
- package/web/modern.js +9793 -9187
package/runner/adapters/cli.mjs
CHANGED
|
@@ -1,155 +1,175 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One headless CLI turn, shared by the CLI adapters (Codex CLI, agy CLI). The adapter supplies what differs:
|
|
3
|
-
* `invocation(config, binding, task, user_home)` → `{args, input?, check?, on_session?}`, `lifecycle(state, event, task, bind)`
|
|
4
|
-
* for its documented events, `events` for progress (and optionally `events.edits(event)` for files edited with the agent's own tools), and optionally `on_stderr(state, text)` and `exit_error(state)`.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
14
|
-
//
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (
|
|
42
|
-
if (
|
|
43
|
-
if (
|
|
44
|
-
if (
|
|
45
|
-
return
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if (
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
child
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
first
|
|
154
|
-
|
|
155
|
-
|
|
1
|
+
/**
|
|
2
|
+
* One headless CLI turn, shared by the CLI adapters (Codex CLI, agy CLI). The adapter supplies what differs:
|
|
3
|
+
* `invocation(config, binding, task, user_home)` → `{args, input?, check?, on_session?, executable?, steer?}`, `lifecycle(state, event, task, bind)`
|
|
4
|
+
* for its documented events, `events` for progress (and optionally `events.edits(event)` for files edited with the agent's own tools), and optionally `on_stderr(state, text)` and `exit_error(state)`.
|
|
5
|
+
* `executable` runs another program in place of the software (a bridge to it); `steer(text)` → the stdin line that passes
|
|
6
|
+
* an interjection into the running turn, and with it stdin stays open after `input` and the delivery can be steered.
|
|
7
|
+
*/
|
|
8
|
+
import { resolve } from 'node:path';
|
|
9
|
+
import { createInterface } from 'node:readline';
|
|
10
|
+
import { bind_access, launch_directory, not_sent, report_edits, track_edits, tree_killable } from './common.mjs';
|
|
11
|
+
import { adapter_capabilities } from './profiles.mjs';
|
|
12
|
+
|
|
13
|
+
const CLI_DIAGNOSTIC_CHARS = 1000;
|
|
14
|
+
// A hung CLI keeps its lease renewed forever when the room sets no execution limit, so cap every process.
|
|
15
|
+
const CLI_MAX_RUN_MS = 2 * 60 * 60_000;
|
|
16
|
+
// Immediate restarts of a CLI that failed before any turn ran, before the runner's slower retry takes over.
|
|
17
|
+
const CLI_START_RETRIES = 2;
|
|
18
|
+
|
|
19
|
+
/** Persist an emitted identity before the agent reads its execution credential file. */
|
|
20
|
+
function bind_cli_session(state, session_id, task) {
|
|
21
|
+
if (typeof session_id !== 'string' || !session_id) throw new Error('CLI 未返回实际会话 ID');
|
|
22
|
+
if (state.session_id && state.session_id !== session_id) throw new Error('CLI 返回的会话 ID 与绑定不符,已停止本次执行');
|
|
23
|
+
task.on_binding(session_id);
|
|
24
|
+
bind_access(task.access_path, session_id);
|
|
25
|
+
state.session_id = session_id;
|
|
26
|
+
state.initialized = true;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Record lifecycle events and tool commands with timestamps so slow stages can be located from the trace file. */
|
|
30
|
+
function trace_cli_event(event, task) {
|
|
31
|
+
if (!task.on_trace) return;
|
|
32
|
+
const item = event.item;
|
|
33
|
+
const command = item?.command ? String(item.command).replace(/^.*?-Command\s+/, '').slice(0, 100) : '';
|
|
34
|
+
const type = event.type ?? event.event ?? 'unknown';
|
|
35
|
+
task.on_trace(item ? `${type}:${item.type}` : type, command ? { command } : {});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Distinguish process completion from successful CLI output and saved website work. */
|
|
39
|
+
function cli_exit_error(adapter, state, code, signal) {
|
|
40
|
+
const own = adapter.exit_error?.(state);
|
|
41
|
+
if (own) return own;
|
|
42
|
+
if (state.error) return state.error;
|
|
43
|
+
if (state.finished && state.completed) return '';
|
|
44
|
+
if (code !== 0) return `CLI ${signal ? `被信号 ${signal} 终止` : `退出码 ${code}`}:${state.diagnostic}`;
|
|
45
|
+
if (!state.initialized) return `CLI 未确认实际会话 ID:${state.diagnostic}`;
|
|
46
|
+
if (!state.completed) return `CLI 未返回成功结束事件:${state.diagnostic}`;
|
|
47
|
+
return '';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Parse complete UTF-8 JSON lines while keeping raw output in the private task log. */
|
|
51
|
+
function monitor_cli(adapter, child, binding, task, restart) {
|
|
52
|
+
const state = { child, session_id: binding.session_id || '', initialized: false, completed: false, error: '', diagnostic: '', responses: new Map(), denials: [] };
|
|
53
|
+
const log_path = resolve(task.directory, `${adapter.id}-${task.id}.log`);
|
|
54
|
+
state.log_path = log_path;
|
|
55
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
56
|
+
const max_run_ms = Number(process.env.CODISCUSS_CLI_MAX_MS) || CLI_MAX_RUN_MS;
|
|
57
|
+
track_edits(adapter, task);
|
|
58
|
+
state.limit_timer = setTimeout(() => { state.error = `CLI 运行超过 ${Math.round(max_run_ms / 1000)} 秒仍未结束,已终止`; child.kill(); }, max_run_ms);
|
|
59
|
+
child.stdout.on('data', chunk => task.on_output(log_path, chunk));
|
|
60
|
+
child.stderr.setEncoding('utf8');
|
|
61
|
+
child.stderr.on('data', chunk => {
|
|
62
|
+
adapter.on_stderr?.(state, state.diagnostic + chunk);
|
|
63
|
+
state.diagnostic = (state.diagnostic + chunk).slice(-CLI_DIAGNOSTIC_CHARS).trim();
|
|
64
|
+
task.on_output(log_path, chunk);
|
|
65
|
+
});
|
|
66
|
+
lines.on('line', line => {
|
|
67
|
+
if (!line.trim()) return;
|
|
68
|
+
let event;
|
|
69
|
+
try { event = JSON.parse(line); }
|
|
70
|
+
catch { state.diagnostic = 'CLI 输出中存在无效 JSON,详情见本机日志'; return; }
|
|
71
|
+
trace_cli_event(event, task);
|
|
72
|
+
const phase = adapter.events.phase(event);
|
|
73
|
+
if (phase) task.on_activity?.(phase, adapter.events.tool(event));
|
|
74
|
+
const note = adapter.events.note(event, state.responses);
|
|
75
|
+
if (note) task.on_note?.(note);
|
|
76
|
+
report_edits(adapter, event, task);
|
|
77
|
+
try { adapter.lifecycle(state, event, task, session_id => bind_cli_session(state, session_id, task)); }
|
|
78
|
+
catch (error) { state.error = error.message; child.kill(); }
|
|
79
|
+
});
|
|
80
|
+
child.once('close', (code, signal) => {
|
|
81
|
+
clearTimeout(state.finish_timer);
|
|
82
|
+
clearTimeout(state.limit_timer);
|
|
83
|
+
task.on_trace?.('cli_closed', { code, signal, killed_after_completed: Boolean(state.finished) });
|
|
84
|
+
if (!state.spawned) return;
|
|
85
|
+
if (state.denials.length) task.on_denials?.(state.denials);
|
|
86
|
+
const error = cli_exit_error(adapter, state, code, signal);
|
|
87
|
+
if (error && state.not_started && !state.stopped && restart?.()) return;
|
|
88
|
+
// `not_started`: the adapter saw the CLI fail before any turn ran, so the runner may deliver the same task again.
|
|
89
|
+
if (error) task.on_failure(error, { not_started: Boolean(state.not_started) });
|
|
90
|
+
else task.on_exit?.(state.denial);
|
|
91
|
+
});
|
|
92
|
+
return state;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Start one headless CLI turn as the adapter describes it; resolves once the process runs. */
|
|
96
|
+
export async function cli_delivery(adapter, config, binding, task, spawn_process, user_home) {
|
|
97
|
+
if (binding.session_id) {
|
|
98
|
+
try { bind_access(task.access_path, binding.session_id); }
|
|
99
|
+
catch (error) { throw not_sent(error); }
|
|
100
|
+
}
|
|
101
|
+
let invocation;
|
|
102
|
+
try { invocation = adapter.invocation(config, binding, task, user_home); }
|
|
103
|
+
catch (error) { throw not_sent(error); }
|
|
104
|
+
if (invocation.check) {
|
|
105
|
+
task.on_trace?.('permission_check_start');
|
|
106
|
+
await invocation.check(spawn_process);
|
|
107
|
+
task.on_trace?.('permission_check_done');
|
|
108
|
+
}
|
|
109
|
+
if (task.before_model_start) {
|
|
110
|
+
try { await task.before_model_start(); }
|
|
111
|
+
catch (error) { throw not_sent(error); }
|
|
112
|
+
}
|
|
113
|
+
if (invocation.on_session) {
|
|
114
|
+
const on_binding = task.on_binding;
|
|
115
|
+
task = { ...task, on_binding: session_id => { invocation.on_session(session_id); on_binding(session_id); } };
|
|
116
|
+
}
|
|
117
|
+
let restarts = 0;
|
|
118
|
+
// The process an interjection goes to: the first one, or the one a restart started in its place.
|
|
119
|
+
let current;
|
|
120
|
+
// A CLI that failed before any turn ran (agy's startup eligibility check on a dropped connection) starts again at
|
|
121
|
+
// once, since nothing was done; a process the runner stopped is never restarted.
|
|
122
|
+
const restart = () => {
|
|
123
|
+
if (restarts >= CLI_START_RETRIES) return false;
|
|
124
|
+
restarts += 1;
|
|
125
|
+
task.on_trace?.('cli_restart', { attempt: restarts });
|
|
126
|
+
let launched;
|
|
127
|
+
try { launched = launch(); }
|
|
128
|
+
catch (error) { task.on_failure(error.message, { not_started: true }); return true; }
|
|
129
|
+
current = launched;
|
|
130
|
+
launched.child.once('spawn', () => { launched.state.spawned = true; launched.send(); });
|
|
131
|
+
launched.child.once('error', error => task.on_failure(error.message, { not_started: !launched.state.spawned }));
|
|
132
|
+
return true;
|
|
133
|
+
};
|
|
134
|
+
const launch = () => {
|
|
135
|
+
const child = spawn_process(invocation.executable || config.executable, invocation.args, {
|
|
136
|
+
cwd: launch_directory(config, task), windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'],
|
|
137
|
+
env: { ...process.env, DISCUSS_ACCESS_FILE: task.access_path },
|
|
138
|
+
});
|
|
139
|
+
tree_killable(child);
|
|
140
|
+
const state = monitor_cli(adapter, child, binding, task, restart);
|
|
141
|
+
const kill = child.kill;
|
|
142
|
+
child.kill = (...args) => { state.stopped = true; return kill(...args); };
|
|
143
|
+
task.on_process(child);
|
|
144
|
+
const send = () => {
|
|
145
|
+
child.stdin.on('error', error => { if (error.code !== 'EPIPE') task.on_failure(error.message); });
|
|
146
|
+
if (invocation.steer) child.stdin.write(invocation.input);
|
|
147
|
+
else child.stdin.end(invocation.input);
|
|
148
|
+
task.on_trace?.('prompt_sent');
|
|
149
|
+
};
|
|
150
|
+
return { child, state, send };
|
|
151
|
+
};
|
|
152
|
+
let first;
|
|
153
|
+
try { first = launch(); }
|
|
154
|
+
catch (error) { throw not_sent(error); }
|
|
155
|
+
current = first;
|
|
156
|
+
const { child, state } = first;
|
|
157
|
+
await new Promise((resolve_spawn, reject) => {
|
|
158
|
+
child.once('spawn', () => { state.spawned = true; task.on_trace?.('cli_spawned'); resolve_spawn(); });
|
|
159
|
+
child.once('error', error => state.spawned ? task.on_failure(error.message) : reject(not_sent(error)));
|
|
160
|
+
});
|
|
161
|
+
first.send();
|
|
162
|
+
const steer = invocation.steer && (text => steer_cli(current, invocation, task, text));
|
|
163
|
+
return { session_id: state.session_id, status: 'accepted', capabilities: adapter_capabilities(adapter.id).delivery, ...(steer ? { steer } : {}) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Pass one interjection into a running CLI turn as the adapter's stdin line, and mark it in the log so the execution's
|
|
168
|
+
* details show it where it happened. False when the turn already ended or the process is gone.
|
|
169
|
+
*/
|
|
170
|
+
function steer_cli({ child, state }, invocation, task, text) {
|
|
171
|
+
if (state.completed || state.stopped || state.error || child.exitCode !== null || child.stdin.destroyed || child.stdin.writableEnded) return false;
|
|
172
|
+
child.stdin.write(invocation.steer(text));
|
|
173
|
+
task.on_output(state.log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
@@ -29,6 +29,22 @@ async function unloaded(config, thread_id) {
|
|
|
29
29
|
finally { app.close(); }
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* Pass an interjection into the chat's running turn through the App itself, which takes it at the turn's next step.
|
|
34
|
+
* Sent only while the chat is active: in an idle chat the same message would start a turn the room never asked for.
|
|
35
|
+
*/
|
|
36
|
+
function app_steer(config, thread_id) {
|
|
37
|
+
return async text => {
|
|
38
|
+
const app = new CodexAppClient(config.pipe_path);
|
|
39
|
+
try {
|
|
40
|
+
await app.open();
|
|
41
|
+
if (await app.thread_status(thread_id) !== 'active') return false;
|
|
42
|
+
await app.send_message(thread_id, text);
|
|
43
|
+
return true;
|
|
44
|
+
} finally { app.close(); }
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
32
48
|
/** Deliver one task to Codex's real App, with the original chat reused afterward. */
|
|
33
49
|
async function deliver(config, binding, task) {
|
|
34
50
|
if (binding.session_id) {
|
|
@@ -40,10 +56,10 @@ async function deliver(config, binding, task) {
|
|
|
40
56
|
const app = new CodexAppClient(config.pipe_path);
|
|
41
57
|
try { await app.open(); await app.send_message(binding.session_id, task.prompt); }
|
|
42
58
|
finally { app.close(); }
|
|
43
|
-
return { session_id: binding.session_id, status: 'accepted', capabilities: IN_APP };
|
|
59
|
+
return { session_id: binding.session_id, status: 'accepted', capabilities: IN_APP, steer: app_steer(config, binding.session_id) };
|
|
44
60
|
}
|
|
45
61
|
const receipt = await run_program(config.executable, ['queue', '--thread', binding.session_id, '--message', task.prompt], { timeout: CALL_TIMEOUT_MS });
|
|
46
|
-
return { session_id: binding.session_id, status: 'accepted', receipt, capabilities: IN_APP };
|
|
62
|
+
return { session_id: binding.session_id, status: 'accepted', receipt, capabilities: IN_APP, steer: app_steer(config, binding.session_id) };
|
|
47
63
|
}
|
|
48
64
|
const app = new CodexAppClient(config.pipe_path);
|
|
49
65
|
try {
|
|
@@ -53,7 +69,7 @@ async function deliver(config, binding, task) {
|
|
|
53
69
|
const result = await app.create_thread(config.source_thread_id, task.prompt, `CoDiscuss · ${task.participant}`, target);
|
|
54
70
|
task.on_binding(result.thread_id);
|
|
55
71
|
bind_access(task.access_path, result.thread_id);
|
|
56
|
-
return { session_id: result.thread_id, status: 'accepted', capabilities: IN_APP };
|
|
72
|
+
return { session_id: result.thread_id, status: 'accepted', capabilities: IN_APP, steer: app_steer(config, result.thread_id) };
|
|
57
73
|
} finally { app.close(); }
|
|
58
74
|
}
|
|
59
75
|
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run one Codex turn through `codex app-server` and speak `codex exec --json` on stdout, so the Codex CLI adapter keeps
|
|
3
|
+
* its event handling while the owner can interject mid-turn (`turn/steer`), which `codex exec` cannot take.
|
|
4
|
+
*
|
|
5
|
+
* usage: node codex_bridge.mjs <codex executable> [codex app-server options...]
|
|
6
|
+
* stdin: first line `{prompt, thread_id?, cwd, model?, effort?, full?}`; every later line `{steer: text}`.
|
|
7
|
+
* stdout: `thread.started`, `turn.started`, `item.started|completed`, `turn.completed|failed`, `error` events in the
|
|
8
|
+
* shape `codex exec --json` prints. The process exits when the turn ends; exit 1 with the reason on stderr otherwise.
|
|
9
|
+
* One process per execution: an app-server keeps the thread it loaded as its writer until it exits.
|
|
10
|
+
*/
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { createInterface } from 'node:readline';
|
|
13
|
+
|
|
14
|
+
const [executable, ...server_args] = process.argv.slice(2);
|
|
15
|
+
const pending = new Map();
|
|
16
|
+
let next_id = 0;
|
|
17
|
+
let thread_id = '';
|
|
18
|
+
let turn_id = '';
|
|
19
|
+
let finished = false;
|
|
20
|
+
const queued_steers = [];
|
|
21
|
+
|
|
22
|
+
const server = spawn(executable, ['app-server', ...server_args], { windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
23
|
+
server.stderr.pipe(process.stderr);
|
|
24
|
+
server.once('error', error => fail(error.message));
|
|
25
|
+
server.once('close', code => { if (!finished) fail(`Codex app-server 意外退出(${code})`); });
|
|
26
|
+
|
|
27
|
+
/** Print one exec-shaped event. */
|
|
28
|
+
function emit(event) { process.stdout.write(`${JSON.stringify(event)}\n`); }
|
|
29
|
+
|
|
30
|
+
/** End with a reason; a thread another process holds says so the way `codex exec` does, so the adapter recognizes it. */
|
|
31
|
+
function fail(message) {
|
|
32
|
+
if (finished) return;
|
|
33
|
+
finished = true;
|
|
34
|
+
const conflict = /active writer/i.test(message) ? 'thread-store conflict: this thread already has an active writer — ' : '';
|
|
35
|
+
process.stderr.write(`${conflict}${message}\n`);
|
|
36
|
+
server.kill();
|
|
37
|
+
process.exitCode = 1;
|
|
38
|
+
setTimeout(() => process.exit(1), 200).unref();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One JSON-RPC request; rejects with the server's error message. */
|
|
42
|
+
function request(method, params) {
|
|
43
|
+
const id = ++next_id;
|
|
44
|
+
server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);
|
|
45
|
+
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The status `codex exec` names for an item's state. */
|
|
49
|
+
const exec_status = status => ({ inProgress: 'in_progress', completed: 'completed', failed: 'failed', declined: 'failed' }[status] || status);
|
|
50
|
+
|
|
51
|
+
/** An app-server thread item in the shape `codex exec` prints it; null for items exec does not show. */
|
|
52
|
+
function exec_item(item) {
|
|
53
|
+
if (item.type === 'agentMessage') return { id: item.id, type: 'agent_message', text: item.text || '' };
|
|
54
|
+
if (item.type === 'reasoning') return { id: item.id, type: 'reasoning', text: (item.summary || []).join('\n') };
|
|
55
|
+
if (item.type === 'commandExecution') return { id: item.id, type: 'command_execution', command: item.command || '',
|
|
56
|
+
aggregated_output: item.aggregatedOutput || '', exit_code: item.exitCode ?? null, status: exec_status(item.status) };
|
|
57
|
+
if (item.type === 'fileChange') return { id: item.id, type: 'file_change', changes: item.changes || [], status: exec_status(item.status) };
|
|
58
|
+
if (item.type === 'webSearch') return { id: item.id, type: 'web_search', query: item.query || '' };
|
|
59
|
+
if (item.type === 'mcpToolCall') return { id: item.id, type: 'mcp_tool_call', server: item.server, tool: item.tool,
|
|
60
|
+
arguments: item.arguments, result: item.result, error: item.error, status: exec_status(item.status) };
|
|
61
|
+
if (item.type === 'plan') return { id: item.id, type: 'todo_list', items: [{ text: item.text || '', completed: false }] };
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Translate one server notification; the turn's end ends this process. */
|
|
66
|
+
function notification({ method, params = {} }) {
|
|
67
|
+
if (params.threadId && params.threadId !== thread_id) return;
|
|
68
|
+
if (method === 'turn/started') emit({ type: 'turn.started' });
|
|
69
|
+
else if (method === 'item/started' || method === 'item/completed') {
|
|
70
|
+
const item = exec_item(params.item || {});
|
|
71
|
+
if (item) emit({ type: method === 'item/started' ? 'item.started' : 'item.completed', item });
|
|
72
|
+
} else if (method === 'error') emit({ type: 'error', message: params.error?.message || params.message || 'Codex 返回错误' });
|
|
73
|
+
else if (method === 'turn/completed') {
|
|
74
|
+
const turn = params.turn || {};
|
|
75
|
+
if (turn.status === 'completed') emit({ type: 'turn.completed', usage: params.usage || {} });
|
|
76
|
+
else emit({ type: 'turn.failed', error: { message: turn.error?.message || (turn.status === 'interrupted' ? '本轮已中断' : 'Codex 本轮失败') } });
|
|
77
|
+
finished = true;
|
|
78
|
+
server.kill();
|
|
79
|
+
process.stdout.write('', () => process.exit(0));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
createInterface({ input: server.stdout, crlfDelay: Infinity }).on('line', line => {
|
|
84
|
+
let message;
|
|
85
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
86
|
+
if (message.id && pending.has(message.id) && !message.method) {
|
|
87
|
+
const { resolve, reject } = pending.get(message.id);
|
|
88
|
+
pending.delete(message.id);
|
|
89
|
+
message.error ? reject(new Error(message.error.message || 'Codex 请求失败')) : resolve(message.result);
|
|
90
|
+
} else if (message.method && message.id === undefined) notification(message);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
/** Pass an interjection into the running turn; before the turn exists it waits, after the turn it is refused. */
|
|
94
|
+
async function steer(text) {
|
|
95
|
+
if (finished) return;
|
|
96
|
+
if (!turn_id) { queued_steers.push(text); return; }
|
|
97
|
+
try { await request('turn/steer', { threadId: thread_id, expectedTurnId: turn_id, input: [{ type: 'text', text }] }); }
|
|
98
|
+
catch (error) { process.stderr.write(`插话未送达:${error.message}\n`); }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Open or resume the thread, then start the turn with the prompt. */
|
|
102
|
+
async function start(task) {
|
|
103
|
+
await request('initialize', { clientInfo: { name: 'codiscuss', version: '0.1.0' } });
|
|
104
|
+
server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'initialized', params: {} })}\n`);
|
|
105
|
+
// 全放开 has no permission profile; the thread itself runs without sandbox or approval.
|
|
106
|
+
const access = task.full ? { sandbox: 'danger-full-access', approvalPolicy: 'never' } : {};
|
|
107
|
+
const opened = task.thread_id ? await request('thread/resume', { threadId: task.thread_id, cwd: task.cwd, ...access })
|
|
108
|
+
: await request('thread/start', { cwd: task.cwd, ...access });
|
|
109
|
+
thread_id = opened.thread.id;
|
|
110
|
+
emit({ type: 'thread.started', thread_id });
|
|
111
|
+
const started = await request('turn/start', { threadId: thread_id, input: [{ type: 'text', text: task.prompt }],
|
|
112
|
+
...(task.model ? { model: task.model } : {}), ...(task.effort ? { effort: task.effort } : {}) });
|
|
113
|
+
turn_id = started.turn.id;
|
|
114
|
+
for (const text of queued_steers.splice(0)) await steer(text);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
let first = true;
|
|
118
|
+
createInterface({ input: process.stdin, crlfDelay: Infinity }).on('line', line => {
|
|
119
|
+
let input;
|
|
120
|
+
try { input = JSON.parse(line); } catch { return; }
|
|
121
|
+
if (first) { first = false; start(input).catch(error => fail(error.message)); }
|
|
122
|
+
else if (typeof input.steer === 'string') steer(input.steer);
|
|
123
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Codex CLI adapter: one headless
|
|
3
|
-
*
|
|
2
|
+
* Codex CLI adapter: one headless turn per execution resuming the bound thread, under a per-run permission profile, run
|
|
3
|
+
* through `codex app-server` by `codex_bridge.mjs` so the owner can interject mid-turn; the bridge prints the events
|
|
4
|
+
* `codex exec --json` would. Its rollout files and app server also serve the Codex App adapter for sessions and models.
|
|
4
5
|
*/
|
|
5
6
|
import { spawn } from 'node:child_process';
|
|
6
7
|
import { randomUUID } from 'node:crypto';
|
|
@@ -8,6 +9,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
|
8
9
|
import { homedir } from 'node:os';
|
|
9
10
|
import { join, resolve } from 'node:path';
|
|
10
11
|
import { createInterface } from 'node:readline';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
11
13
|
import { cli_delivery } from './cli.mjs';
|
|
12
14
|
import { CALL_TIMEOUT_MS, launch_directory, log_entries, marked, model_entry, json_line, newest_record, not_sent,
|
|
13
15
|
project_directory, prompt_text, query_catalog } from './common.mjs';
|
|
@@ -16,8 +18,12 @@ import { CALL_TIMEOUT_MS, launch_directory, log_entries, marked, model_entry, js
|
|
|
16
18
|
const CLI_EXIT_GRACE_MS = 1500;
|
|
17
19
|
const CODEX_PERMISSIONS_MIN_MINOR = 163;
|
|
18
20
|
const FORK_TIMEOUT_MS = 60_000;
|
|
21
|
+
const CODEX_BRIDGE = fileURLToPath(new URL('./codex_bridge.mjs', import.meta.url));
|
|
19
22
|
|
|
20
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* Build a per-invocation profile without inheriting a user's custom profile of the same name. The room's other project
|
|
25
|
+
* directories (`task.extra_directories`) get their own read or write entry.
|
|
26
|
+
*/
|
|
21
27
|
export function codex_permissions(config, task, platform = process.platform) {
|
|
22
28
|
// 全放开 runs without approval or sandbox, so there is no profile to build or check.
|
|
23
29
|
if (config.project_access === 'full') return { name: '', args: ['--dangerously-bypass-approvals-and-sandbox'] };
|
|
@@ -26,7 +32,8 @@ export function codex_permissions(config, task, platform = process.platform) {
|
|
|
26
32
|
const base = ['auto', 'own'].includes(config.project_access) || (project_directory(config) && config.project_access === 'write')
|
|
27
33
|
? ':workspace' : ':read-only';
|
|
28
34
|
const drafts = resolve(task.draft_directory).replaceAll('\\', '/');
|
|
29
|
-
const
|
|
35
|
+
const extras = Object.fromEntries((task.extra_directories || []).map(item => [resolve(item.path).replaceAll('\\', '/'), item.access]));
|
|
36
|
+
const filesystem = { ':root': 'read', ...extras, [resolve(task.directory).replaceAll('\\', '/')]: 'read', [drafts]: 'write' };
|
|
30
37
|
const rules = Object.entries(filesystem).map(([path, access]) => `${JSON.stringify(path)}=${JSON.stringify(access)}`).join(',');
|
|
31
38
|
const profile = `{extends=${JSON.stringify(base)},filesystem={${rules}},network={enabled=true}}`;
|
|
32
39
|
// The Windows sandbox account cannot write the user's TEMP, so PowerShell starts in ConstrainedLanguage and Codex's
|
|
@@ -92,14 +99,18 @@ async function check_codex_permissions(config, task, permissions, spawn_process)
|
|
|
92
99
|
}
|
|
93
100
|
}
|
|
94
101
|
|
|
95
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* One turn through `codex_bridge.mjs`, which runs `codex app-server` under the per-run permission profile and prints
|
|
104
|
+
* `codex exec --json` events, so an interjection can enter the running turn. Every continuation names the exact bound
|
|
105
|
+
* thread; 全放开 has no profile and opens the thread without sandbox or approval instead.
|
|
106
|
+
*/
|
|
96
107
|
function invocation(config, binding, task) {
|
|
97
108
|
const permissions = codex_permissions(config, task);
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
109
|
+
const full = config.project_access === 'full';
|
|
110
|
+
const input = `${JSON.stringify({ prompt: task.prompt, thread_id: binding.session_id || '', cwd: launch_directory(config, task),
|
|
111
|
+
model: config.model || '', effort: config.effort || '', full })}\n`;
|
|
112
|
+
return { executable: process.execPath, args: [CODEX_BRIDGE, config.executable, ...(full ? [] : permissions.args)], input,
|
|
113
|
+
steer: text => `${JSON.stringify({ steer: text })}\n`,
|
|
103
114
|
...(permissions.name ? { check: spawn_process => check_codex_permissions(config, task, permissions, spawn_process) } : {}) };
|
|
104
115
|
}
|
|
105
116
|
|
|
@@ -142,8 +153,34 @@ const events = {
|
|
|
142
153
|
if (event.type !== 'item.completed' || event.item?.type !== 'file_change') return [];
|
|
143
154
|
return (event.item.changes || []).map(change => String(change?.path || '')).filter(Boolean);
|
|
144
155
|
},
|
|
156
|
+
detail: codex_detail,
|
|
145
157
|
};
|
|
146
158
|
|
|
159
|
+
// Codex runs each command through a shell wrapper; the page shows the command the agent wrote.
|
|
160
|
+
const SHELL_WRAPPER = /^"?[^"]*?(?:powershell|pwsh|cmd|bash|sh)(?:\.exe)?"?\s+(?:-Command|\/c|-lc|-c)\s+(["'])([\s\S]*)\1\s*$/i;
|
|
161
|
+
|
|
162
|
+
/** One `codex exec --json` event as execution-detail entries; an item keeps its id so its completion updates the start. */
|
|
163
|
+
function codex_detail(event) {
|
|
164
|
+
if (event.type === 'turn.failed') return [{ kind: 'error', body: String(event.error?.message || '本轮失败') }];
|
|
165
|
+
const item = event.item;
|
|
166
|
+
if (!item || !['item.started', 'item.updated', 'item.completed'].includes(event.type)) return [];
|
|
167
|
+
const done = event.type === 'item.completed';
|
|
168
|
+
const state = !done ? 'running' : item.status === 'failed' || (item.exit_code != null && item.exit_code !== 0) ? 'failed' : 'done';
|
|
169
|
+
const id = `item-${item.id}`;
|
|
170
|
+
if (item.type === 'agent_message' && done) return [{ id, kind: 'message', body: String(item.text || '') }];
|
|
171
|
+
if (item.type === 'reasoning' && item.text) return [{ id, kind: 'thinking', body: String(item.text) }];
|
|
172
|
+
if (item.type === 'command_execution') {
|
|
173
|
+
const command = String(item.command || '');
|
|
174
|
+
return [{ id, kind: 'command', title: command.match(SHELL_WRAPPER)?.[2] ?? command, state, body: done ? String(item.aggregated_output || '') : undefined }];
|
|
175
|
+
}
|
|
176
|
+
if (item.type === 'web_search') return [{ id, kind: 'search', title: String(item.query || ''), state }];
|
|
177
|
+
if (item.type === 'file_change') return [{ id, kind: 'edit', title: (item.changes || []).map(change => change?.path).filter(Boolean).join('\n'), state }];
|
|
178
|
+
if (item.type === 'mcp_tool_call') return [{ id, kind: 'tool', title: [item.server, item.tool].filter(Boolean).join('.'), state,
|
|
179
|
+
body: done ? JSON.stringify(item.result ?? item.error ?? '', null, 1) : JSON.stringify(item.arguments ?? '', null, 1) }];
|
|
180
|
+
if (item.type === 'todo_list') return [{ id, kind: 'plan', body: (item.items || []).map(step => `${step.completed ? '☑' : '☐'} ${step.text}`).join('\n') }];
|
|
181
|
+
return [];
|
|
182
|
+
}
|
|
183
|
+
|
|
147
184
|
/** Where Codex keeps one thread's rollout, or '' when this machine has none by that ID; shared by the App adapter. */
|
|
148
185
|
export function session_path(session_id, env = process.env, home = homedir()) {
|
|
149
186
|
const sessions = join(env.CODEX_HOME || join(home, '.codex'), 'sessions');
|