ai_co_discuss 0.5.21 → 0.5.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.agents/skills/codiscuss-draft-cleanup/SKILL.md +16 -0
  2. package/.agents/skills/codiscuss-draft-cleanup/cleanup.py +70 -0
  3. package/.agents/skills/codiscuss-draft-cleanup/scan.py +70 -0
  4. package/.agents/skills/discuss-host/references/control.md +2 -2
  5. package/.agents/skills/discuss-host/references/workflow.md +4 -2
  6. package/.agents/skills/discuss-participant/SKILL.md +2 -0
  7. package/.agents/skills/local-stt-setup/SKILL.md +9 -8
  8. package/.agents/skills/local-tts-setup/SKILL.md +10 -9
  9. package/.agents/skills/share-card/SKILL.md +7 -6
  10. package/.agents/skills/share-card/references/share-card.md +34 -8
  11. package/.agents/skills/workflow-creator/SKILL.md +22 -14
  12. package/README.md +2 -0
  13. package/README.zh-CN.md +2 -0
  14. package/backend/free_room.py +64 -8
  15. package/backend/message_queue.py +9 -0
  16. package/backend/schema.sql +13 -1
  17. package/backend/server.py +289 -59
  18. package/docs/en/guide/admin.md +18 -0
  19. package/docs/en/guide/members.md +7 -1
  20. package/docs/en/guide/remote.md +1 -1
  21. package/docs/en/guide/rooms.md +14 -6
  22. package/docs/en/guide/voice.md +2 -0
  23. package/docs/en/guide/workflows.md +9 -5
  24. package/docs/en/guide/working.md +6 -4
  25. package/docs/guide/admin.md +18 -0
  26. package/docs/guide/members.md +7 -1
  27. package/docs/guide/remote.md +1 -1
  28. package/docs/guide/rooms.md +13 -6
  29. package/docs/guide/voice.md +2 -0
  30. package/docs/guide/workflows.md +9 -5
  31. package/docs/guide/working.md +6 -4
  32. package/frontend/locales/en/admin.json +58 -1
  33. package/frontend/locales/en/app.json +18 -1
  34. package/frontend/locales/en/backend.json +6 -0
  35. package/frontend/locales/en/core.json +4 -2
  36. package/frontend/locales/en/discussion.json +4 -1
  37. package/frontend/locales/en/room.json +85 -1
  38. package/gateway/gateway.mjs +49 -9
  39. package/package.json +3 -1
  40. package/runner/account_space.mjs +10 -0
  41. package/runner/adapters/antigravity_app.mjs +31 -4
  42. package/runner/adapters/antigravity_cli.mjs +9 -2
  43. package/runner/adapters/api.mjs +3 -2
  44. package/runner/adapters/api_pi.mjs +3 -2
  45. package/runner/adapters/api_pi_extension.mjs +5 -3
  46. package/runner/adapters/claude.mjs +32 -9
  47. package/runner/adapters/cli.mjs +2 -2
  48. package/runner/adapters/codex_app.mjs +192 -69
  49. package/runner/adapters/codex_cli.mjs +10 -5
  50. package/runner/adapters/common.mjs +414 -11
  51. package/runner/adapters/index.mjs +6 -0
  52. package/runner/admin_cli.mjs +22 -5
  53. package/runner/admin_panel.mjs +118 -5
  54. package/runner/admin_storage.mjs +105 -0
  55. package/runner/discussion_launch.mjs +328 -128
  56. package/runner/discussion_runner.mjs +12 -3
  57. package/runner/discussion_service.mjs +224 -37
  58. package/runner/discussion_skills.mjs +1 -1
  59. package/runner/expert_prompts.mjs +2 -2
  60. package/runner/experts.mjs +227 -0
  61. package/runner/file_diff.mjs +1 -1
  62. package/runner/free_runner.mjs +236 -51
  63. package/runner/i18n_en.mjs +39 -0
  64. package/runner/os_users.mjs +33 -1
  65. package/runner/project_files.mjs +7 -1
  66. package/runner/project_migration.mjs +245 -0
  67. package/runner/relay_channel.mjs +1 -1
  68. package/runner/remote_launch.mjs +4 -3
  69. package/runner/share_card.mjs +17 -1
  70. package/runner/share_shared.mjs +26 -9
  71. package/runner/site_deploy.mjs +2 -1
  72. package/runner/slash_names.mjs +12 -1
  73. package/runner/speech_directories.mjs +20 -0
  74. package/runner/storage_guard.mjs +383 -0
  75. package/runner/tts_providers.mjs +22 -21
  76. package/runner/workflows.mjs +211 -57
  77. package/web/admin.css +1 -1
  78. package/web/admin.js +8 -8
  79. package/web/app.js +589 -80
  80. package/web/i18n.js +4 -4
  81. package/web/markdown.css +1 -1
  82. package/web/modern.css +1 -1
  83. package/web/modern.js +68 -66
  84. package/workflows/decision-council/flow.json +216 -25
  85. package/workflows/trpg-classic/flow.json +151 -21
@@ -13,7 +13,7 @@ import { dirname, join, resolve } from 'node:path';
13
13
  import { runs_commands } from '../expert_prompts.mjs';
14
14
  import { bind_access, carve_protected, cli_max_run_ms, cli_timeout_reason, DENIAL_FIELD, EDIT_TOOLS, edge_entries, launch_directory, log_entries, marked, MAX_DENIALS, model_entry, json_line,
15
15
  clock_reset_at, newest_record, not_sent, page_sessions, preview_messages, project_directory, prompt_text, prompt_title, query_catalog,
16
- remove_session_files, same_path, TASK_SUBCOMMANDS, tree_killable, typed_prompt, watch_events, shell_written_paths } from './common.mjs';
16
+ remove_session_files, report_edits, same_path, TASK_SUBCOMMANDS, track_edits, tree_killable, typed_prompt, watch_events, shell_written_paths } from './common.mjs';
17
17
 
18
18
  // A message posted to an open Claude window that has not started by then is reported, not failed.
19
19
  const INBOX_CHECK_MS = 90_000;
@@ -264,13 +264,31 @@ const events = {
264
264
  if (event.type !== 'assistant') return '';
265
265
  return (event.message?.content || []).filter(block => block.type === 'text').map(block => block.text).join('\n').trim();
266
266
  },
267
- edits(event) {
268
- if (event.type !== 'assistant') return [];
269
- // Edit tools name their file; a shell command that writes is taken to have written the paths it names (Claude often
270
- // edits by script), else its own files would read as someone else's on the card (user 2026-11-17).
271
- return (event.message?.content || []).filter(block => block.type === 'tool_use')
272
- .flatMap(block => EDIT_TOOL_NAMES.test(block.name) ? [String(block.input?.file_path || block.input?.notebook_path || '')]
273
- : SHELL_TOOL_NAMES.test(block.name) ? shell_written_paths(block.input?.command) : []).filter(Boolean);
267
+ edits(event, pending) {
268
+ // Edit tools name their file; a writing shell command claims only its write targets. When `pending` is given (a
269
+ // live stream or window log), candidate paths wait for the matching tool_result and are dropped on `is_error`.
270
+ const blocks = Array.isArray(event.message?.content) ? event.message.content : [];
271
+ if (event.type === 'assistant') {
272
+ const direct = [];
273
+ for (const block of blocks.filter(item => item?.type === 'tool_use')) {
274
+ const paths = (EDIT_TOOL_NAMES.test(block.name) ? [String(block.input?.file_path || block.input?.notebook_path || '')]
275
+ : SHELL_TOOL_NAMES.test(block.name) ? shell_written_paths(block.input?.command) : []).filter(Boolean);
276
+ if (!paths.length) continue;
277
+ if (pending && block.id) pending.set(block.id, paths);
278
+ else direct.push(...paths);
279
+ }
280
+ return direct;
281
+ }
282
+ if (pending && event.type === 'user') {
283
+ const confirmed = [];
284
+ for (const block of blocks.filter(item => item?.type === 'tool_result')) {
285
+ const paths = pending.get(block.tool_use_id);
286
+ pending.delete(block.tool_use_id);
287
+ if (paths && !block.is_error) confirmed.push(...paths);
288
+ }
289
+ return confirmed;
290
+ }
291
+ return [];
274
292
  },
275
293
  detail: claude_detail,
276
294
  };
@@ -526,7 +544,8 @@ export function watch_window_turn({ file, offset, pid, marker, session_id = '',
526
544
  const { interval = WINDOW_POLL_MS, unstarted_after = INBOX_CHECK_MS, chat = false, start_after = CHAT_START_MS,
527
545
  waiting_after = CHAT_WAITING_MS, turn_limit = CHAT_TURN_MS, env = process.env, on_end, stop_key,
528
546
  stop_poll = STOP_POLL_MS, stop_tool_wait = STOP_TOOL_WAIT_MS, stop_end_wait = STOP_END_WAIT_MS } = options;
529
- const since = Date.now(), awaited = new Set([marker]), open_tools = new Set(), background = new Map();
547
+ const since = Date.now(), awaited = new Set([marker]), open_tools = new Set(), background = new Map(), pending_edits = new Map();
548
+ if (!chat) track_edits(claude, task);
530
549
  let pending = Buffer.alloc(0), taken = false, noted = false, error = null, done = false, waiting_since = 0;
531
550
  let stop_asked = 0, stop_sent = 0, stop_timer = null, last_message = null, idle_since = 0, waiting_noted = false;
532
551
  // `ended` says why a room task's turn ended without finishing (interrupted, window closed): it is an exit, not a
@@ -553,6 +572,7 @@ export function watch_window_turn({ file, offset, pid, marker, session_id = '',
553
572
  const api_error = claude_api_error(entry);
554
573
  error = api_error || error;
555
574
  if ((chat || log_path) && !api_error) report(entry);
575
+ if (!chat && !api_error && !entry.isSidechain) report_edits(claude, entry, task, pending_edits);
556
576
  if (!entry.isSidechain) { track_tools(entry); track_background(entry); }
557
577
  // A turn that left a background task running ends while the window waits for it; its report starts the next turn.
558
578
  if (entry.type === 'system' && entry.subtype === 'turn_duration' && !awaited.size && !background.size) return finish();
@@ -1015,6 +1035,9 @@ export const claude = {
1015
1035
  recover_turn,
1016
1036
  id: 'claude', catalog_source: 'claude-cli',
1017
1037
  into_window: claude_inbox_ready,
1038
+ // An attached window's stop handle is only confirmed during delivery.
1039
+ preflight_stoppable: (profile, binding) => !(profile.project_access === 'own' && profile.session_id
1040
+ && (binding.session_id ?? profile.session_id) === profile.session_id),
1018
1041
  deliver, chat, events,
1019
1042
  session: { path: session_path, exists: session_exists, owns: session_exists, cwd: session_cwd, branch, settings: session_settings,
1020
1043
  list: list_sessions, preview: preview_session, remove: remove_session,
@@ -47,7 +47,7 @@ function cli_exit_error(adapter, state, code, signal) {
47
47
 
48
48
  /** Parse complete UTF-8 JSON lines while keeping raw output in the private task log. */
49
49
  function monitor_cli(adapter, child, binding, task, restart) {
50
- const state = { child, session_id: binding.session_id || '', initialized: false, completed: false, error: '', diagnostic: '', responses: new Map(), denials: [] };
50
+ const state = { child, session_id: binding.session_id || '', initialized: false, completed: false, error: '', diagnostic: '', responses: new Map(), pending_edits: new Map(), denials: [] };
51
51
  const log_path = resolve(task.directory, `${adapter.id}-${task.id}.log`);
52
52
  state.log_path = log_path;
53
53
  const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
@@ -87,7 +87,7 @@ function monitor_cli(adapter, child, binding, task, restart) {
87
87
  if (phase) task.on_activity?.(phase, adapter.events.tool(event), adapter.events.call?.(event));
88
88
  const note = adapter.events.note(event, state.responses);
89
89
  if (note) task.on_note?.(note);
90
- report_edits(adapter, event, task);
90
+ report_edits(adapter, event, task, state.pending_edits);
91
91
  try { adapter.lifecycle(state, event, task, session_id => bind_cli_session(state, session_id, task)); }
92
92
  catch (error) { state.error = error.message; child.kill(); }
93
93
  });
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Codex App adapter: tasks go into a chat of the running Codex desktop, through its app-tools pipe or `codex queue`.
3
- * The turn runs inside the App, so the runner can neither stop it nor see its progress. Threads are stored like the
4
- * CLI's, so sessions and models come from the Codex CLI adapter. A private chat turn is the exception: the runner
5
- * follows it by reading the chat, and can force it to stop.
3
+ * Room turns run inside the App, so the runner cannot stop them; when the chat can be read beforehand, the runner polls
4
+ * `read_thread` for the matched turn's progress, steps, edits and end, degrading to no progress when the App cannot be
5
+ * read. Threads are stored like the CLI's, so sessions and models come from the Codex CLI adapter. A private chat turn
6
+ * also reads the reply back and can force the turn to stop.
6
7
  */
7
8
  import { EventEmitter } from 'node:events';
8
9
  import { mkdirSync, writeFileSync } from 'node:fs';
@@ -11,10 +12,11 @@ import { dirname, join, resolve } from 'node:path';
11
12
  import { setTimeout as sleep } from 'node:timers/promises';
12
13
  import { CodexAppClient } from './codex_app_client.mjs';
13
14
  import { branch, codex_skills, desktop_thread, list_sessions, preview_session, remove_session, session_exists, session_path, session_settings } from './codex_cli.mjs';
14
- import { bind_access, CALL_TIMEOUT_MS, not_sent, read_json, run_program, same_path } from './common.mjs';
15
+ import { bind_access, CALL_TIMEOUT_MS, not_sent, read_json, run_program, same_path, shell_written_paths } from './common.mjs';
15
16
 
16
- // The desktop has no stop or interrupt tool (its tool list, checked 2026-10-30), and the turn's output stays in the App.
17
+ // The desktop has no stop or interrupt tool (its tool list, checked 2026-10-30).
17
18
  const IN_APP = { stoppable: false, progress: false };
19
+ const IN_APP_PROGRESS = { stoppable: false, progress: true };
18
20
 
19
21
  /** Match the real saved project and its directory; a prompt cannot grant file access. */
20
22
  export async function codex_target(app, config) {
@@ -59,101 +61,212 @@ export async function creation_source(app, config, file) {
59
61
  return made.thread_id;
60
62
  }
61
63
 
62
- /** Whether the running App has not loaded a chat; when the App cannot tell, the queue is used as before. */
63
- async function unloaded(config, thread_id) {
64
- const app = new CodexAppClient(config.pipe_path);
65
- try { await app.open(); return await app.thread_status(thread_id) === 'notLoaded'; }
66
- catch { return false; }
67
- finally { app.close(); }
68
- }
69
-
70
64
  /**
71
65
  * Pass an interjection into the chat's running turn through the App itself, which takes it at the turn's next step.
72
66
  * Sent only while the chat is active: in an idle chat the same message would start a turn the room never asked for.
73
67
  */
74
- function app_steer(config, thread_id) {
68
+ function app_steer(config, thread_id, task = null, connect = null) {
69
+ const log_path = task?.directory && task?.id ? resolve(task.directory, `codex-${task.id}.log`) : '';
75
70
  return async text => {
76
- const app = new CodexAppClient(config.pipe_path);
71
+ const app = connect ? await connect() : await open_app(config);
77
72
  try {
78
- await app.open();
79
- if (await app.thread_status(thread_id) !== 'active') return false;
73
+ const status = typeof app.thread_status === 'function'
74
+ ? await app.thread_status(thread_id)
75
+ : (await app.read_thread(thread_id, { turnLimit: 1 })).thread.status.type;
76
+ if (status !== 'active') return false;
80
77
  await app.send_message(thread_id, text);
78
+ if (log_path) task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
81
79
  return true;
82
80
  } finally { app.close(); }
83
81
  };
84
82
  }
85
83
 
86
- // A room turn runs in the App, which the runner cannot stop; it only watches the chat for that turn to end, so a stop the
87
- // owner makes in the App lets the room deliver again at once.
84
+ // A room turn runs in the App, which the runner cannot stop; when the chat can be read beforehand, it follows only the
85
+ // turn matching this task's prompt for progress, steps, edits and end, without pulling in private turns in the same chat.
88
86
  const ROOM_POLL_MS = 2000;
89
- const ROOM_READ = { turnLimit: 3 };
87
+ const ROOM_READ = { turnLimit: 3, includeOutputs: true, maxOutputCharsPerItem: 4000 };
88
+ const ROOM_DELEGATION_NAMES = ['send_message_to_thread', 'create_thread'];
89
+ const TOOL_ITEM_TYPES = new Set(['commandExecution', 'fileChange', 'webSearch', 'mcpToolCall']);
90
90
 
91
- /** The ids of the chat's latest turns before a task goes in, or null when the App cannot be read. */
92
- async function turns_before(config, thread_id) {
93
- const app = new CodexAppClient(config.pipe_path);
94
- try { await app.open(); return new Set((await app.read_thread(thread_id, ROOM_READ)).turns.map(turn => turn.id)); }
95
- catch { return null; }
96
- finally { app.close(); }
91
+ /** The chat's status, latest turns and item ids before a room task goes in, or null when the App cannot be read. */
92
+ async function room_before(config, thread_id, connect) {
93
+ let app;
94
+ try {
95
+ app = await connect();
96
+ const data = await app.read_thread(thread_id, ROOM_READ);
97
+ return {
98
+ status: data.thread.status.type,
99
+ turns: new Set(data.turns.map(turn => turn.id)),
100
+ items: new Set(data.turns.flatMap(turn => (turn.items || []).map(item => item.id)).filter(Boolean)),
101
+ };
102
+ } catch { return null; }
103
+ finally { app?.close(); }
104
+ }
105
+
106
+ /** Literal file paths written by one finished Codex App turn item; running, failed or declined items claim nothing. */
107
+ function app_item_edits(item) {
108
+ if (!item || ['inProgress', 'failed', 'declined'].includes(item.status)) return [];
109
+ if (item.type === 'fileChange') return (item.changes || []).map(change => String(change?.path || '')).filter(Boolean);
110
+ if (item.type === 'commandExecution' && (item.exitCode ?? 0) === 0) return shell_written_paths(item.command);
111
+ return [];
112
+ }
113
+
114
+ /** Map one Codex App turn item to `{phase, tool}` for the execution timeline, or null when it is not an activity step. */
115
+ function app_item_activity(item) {
116
+ if (!item) return null;
117
+ if (item.type === 'commandExecution') return { phase: 'command', tool: '' };
118
+ if (item.type === 'fileChange') return { phase: 'editing', tool: '' };
119
+ if (item.type === 'webSearch') return { phase: 'tool', tool: 'web_search' };
120
+ if (item.type === 'mcpToolCall') return { phase: 'tool', tool: String(item.tool || '') };
121
+ if (item.type === 'reasoning') return { phase: 'thinking', tool: '' };
122
+ if (item.type === 'agentMessage' && item.text) return { phase: 'writing', tool: '' };
123
+ return null;
124
+ }
125
+
126
+ /** Deduplicated `codiscuss.entry` writer shared by room turns and private chat turns. */
127
+ function entry_logger(task) {
128
+ const log_path = task?.directory && task?.id ? resolve(task.directory, `codex-${task.id}.log`) : '';
129
+ const logged = new Map();
130
+ return entry => {
131
+ if (!log_path || !entry) return;
132
+ const line = JSON.stringify({ type: 'codiscuss.entry', entry });
133
+ if (logged.get(entry.id) !== line) { logged.set(entry.id, line); task.on_output?.(log_path, `${line}\n`); }
134
+ };
135
+ }
136
+
137
+ /** Find or follow the one turn matching this room task; ignores unrelated or private turns in the same chat. */
138
+ function resolve_room_turn(snapshot, prompt, seen, matched) {
139
+ const turns = snapshot.turns || [];
140
+ if (!matched) {
141
+ const found = find_turn(snapshot, prompt, seen.items, { allow_user: true, names: ROOM_DELEGATION_NAMES, seen_turns: seen.turns });
142
+ if (!found) return null;
143
+ matched = { turn_id: found.turn.id, item_id: found.item_id, start_index: found.index };
144
+ }
145
+ const turn = turns.find(item => item.id === matched.turn_id);
146
+ if (!turn) return { matched, turn: null, items: [], ended: true };
147
+ const all = turn.items || [];
148
+ // `read_thread` keeps only the latest page of items (default 32), so once our prompt item scrolls off the front of
149
+ // this already-matched turn, every remaining item in `all` occurred after it.
150
+ const anchor = matched.item_id ? all.findIndex(item => item.id === matched.item_id) : matched.start_index;
151
+ const items = anchor >= 0 ? all.slice(anchor + 1) : all;
152
+ const ended = turn.status !== 'inProgress' && (turns[0] !== turn || snapshot.thread?.status?.type !== 'active');
153
+ return { matched, turn, items, ended };
154
+ }
155
+
156
+ /** Report deduplicated steps, timeline activities, progress notes and file edits for the matched room turn. */
157
+ function report_room_items(turn, items, state, task, log) {
158
+ let just_finished_tool = false;
159
+ let last_new_kind = '';
160
+ for (const [index, item] of items.entries()) {
161
+ if (!item) continue;
162
+ const key = item.id || `${turn.id}:${index}`;
163
+ const entry = chat_entry(item, key);
164
+ if (entry) log(entry);
165
+ if (!state.activities.has(key)) {
166
+ const activity = app_item_activity(item);
167
+ if (activity) {
168
+ state.activities.add(key);
169
+ task.on_activity?.(activity.phase, activity.tool, key);
170
+ last_new_kind = item.status === 'inProgress' ? 'inProgress' : activity.phase;
171
+ }
172
+ }
173
+ if (TOOL_ITEM_TYPES.has(item.type) && item.status !== 'inProgress' && !state.finished_tools.has(key)) {
174
+ state.finished_tools.add(key);
175
+ just_finished_tool = true;
176
+ }
177
+ if (item.type === 'agentMessage' && item.phase === 'commentary' && !state.notes.has(key)) {
178
+ const text = String(item.text || '').trim();
179
+ if (text) { state.notes.add(key); task.on_note?.(text); }
180
+ }
181
+ if (item.status !== 'inProgress' && !state.edits.has(key)) {
182
+ state.edits.add(key);
183
+ const paths = app_item_edits(item);
184
+ if (paths.length) task.on_edits?.(paths);
185
+ }
186
+ }
187
+ if (!state.started && !state.activities.size && turn.status === 'inProgress') {
188
+ state.started = true;
189
+ task.on_activity?.('thinking');
190
+ } else if (turn.status === 'inProgress' && just_finished_tool && !['inProgress', 'writing', 'thinking'].includes(last_new_kind)) {
191
+ task.on_activity?.('thinking');
192
+ }
97
193
  }
98
194
 
99
195
  /**
100
- * Read the chat until a turn newer than `seen` has ended and the chat is idle, then report `on_turn_end`. Gives up quietly
101
- * after the private chat's ceiling or when the App stays unreadable; the room then falls back to the site's hold.
196
+ * Poll the chat until the turn matching `task.prompt` ends, logging its steps into `codex-${task.id}.log`, reporting
197
+ * deduplicated timeline activities, notes and file edits along the way, and calling `on_turn_end` when finished.
198
+ * Gives up quietly after the ceiling or when the App stays unreadable; the room then falls back to the site's hold.
102
199
  * `options` (`connect`, `poll_ms`, `timeout_ms`) replace the App and the timings in tests.
103
200
  */
104
- export async function watch_room_turn(config, thread_id, seen, task, options = {}) {
201
+ export async function watch_room_turn(config, thread_id, before, task, options = {}) {
105
202
  const connect = options.connect || (() => open_app(config));
203
+ const seen = before instanceof Set ? { turns: before, items: new Set() }
204
+ : { turns: before?.turns || new Set(), items: before?.items || new Set() };
106
205
  const deadline = Date.now() + (options.timeout_ms ?? CHAT_TIMEOUT_MS);
107
- let app = null, failures = 0;
206
+ const state = { activities: new Set(), finished_tools: new Set(), notes: new Set(), edits: new Set(), started: false };
207
+ const log = entry_logger(task);
208
+ task.on_edits?.([]);
209
+ let app = null, failures = 0, matched = null;
108
210
  try {
109
211
  while (Date.now() < deadline) {
110
212
  await sleep(options.poll_ms ?? ROOM_POLL_MS);
111
213
  let snapshot;
112
214
  try { app ||= await connect(); snapshot = await app.read_thread(thread_id, ROOM_READ); failures = 0; }
113
215
  catch { app?.close(); app = null; if (++failures >= CHAT_READ_FAILURES) return; continue; }
114
- const newest = snapshot.turns[0];
115
- if (newest && !seen.has(newest.id) && newest.status !== 'inProgress' && snapshot.thread.status.type !== 'active') return task.on_turn_end?.();
216
+ const found = resolve_room_turn(snapshot, task.prompt, seen, matched);
217
+ if (!found) continue;
218
+ matched = found.matched;
219
+ if (found.turn) report_room_items(found.turn, found.items, state, task, log);
220
+ if (found.ended) {
221
+ if (found.turn && found.turn.status !== 'completed') {
222
+ const reason = found.turn.status === 'interrupted' ? '这一轮在 Codex App 中被中断' : found.turn.error?.message || 'Codex App 中这一轮未正常结束';
223
+ log({ id: `turn-${found.turn.id}`, kind: 'error', title: reason, state: 'failed' });
224
+ }
225
+ return task.on_turn_end?.();
226
+ }
116
227
  }
117
228
  } finally { app?.close(); }
118
229
  }
119
230
 
120
- /** What a room delivery into this chat can do: never stopped, its end heard when the chat could be read beforehand. */
121
- function room_delivery(config, thread_id, seen, task) {
122
- if (!seen) return IN_APP;
123
- watch_room_turn(config, thread_id, seen, task).catch(() => {});
124
- return { ...IN_APP, ends: true };
231
+ /** What a room delivery into this chat can do: never stopped; progress and end reported when the chat was readable beforehand. */
232
+ function room_delivery(config, thread_id, before, task, options = {}) {
233
+ if (!before) return IN_APP;
234
+ watch_room_turn(config, thread_id, before, task, options).catch(() => {});
235
+ return { ...IN_APP_PROGRESS, ends: true };
125
236
  }
126
237
 
127
238
  /** Deliver one task to Codex's real App, with the original chat reused afterward. */
128
- async function deliver(config, binding, task, _spawn, user_home = homedir()) {
239
+ async function deliver(config, binding, task, _spawn, user_home = homedir(), options = {}) {
240
+ const connect = options.connect || (() => open_app(config));
241
+ const run = options.run || run_program;
129
242
  if (binding.session_id) {
130
243
  try { bind_access(task.access_path, binding.session_id); }
131
244
  catch (error) { throw not_sent(error); }
132
- const seen = await turns_before(config, binding.session_id);
245
+ const before = await room_before(config, binding.session_id, connect);
133
246
  // `codex queue` reaches only a chat the App has loaded; a fork made after a rewind, or a chat after the App restarted,
134
247
  // is not loaded until a message is sent through the App itself (tested on App tools, 2026-10).
135
- if (await unloaded(config, binding.session_id)) {
136
- const app = new CodexAppClient(config.pipe_path);
137
- try { await app.open(); await app.send_message(binding.session_id, task.prompt); }
248
+ if (before?.status === 'notLoaded') {
249
+ const app = await connect();
250
+ try { await app.send_message(binding.session_id, task.prompt); }
138
251
  finally { app.close(); }
139
- return { session_id: binding.session_id, status: 'accepted', capabilities: room_delivery(config, binding.session_id, seen, task), steer: app_steer(config, binding.session_id) };
252
+ return { session_id: binding.session_id, status: 'accepted', capabilities: room_delivery(config, binding.session_id, before, task, options), steer: app_steer(config, binding.session_id, task, options.connect) };
140
253
  }
141
- const receipt = await run_program(config.executable, ['queue', '--thread', binding.session_id, '--message', task.prompt], { timeout: CALL_TIMEOUT_MS });
142
- return { session_id: binding.session_id, status: 'accepted', receipt, capabilities: room_delivery(config, binding.session_id, seen, task), steer: app_steer(config, binding.session_id) };
254
+ const receipt = await run(config.executable, ['queue', '--thread', binding.session_id, '--message', task.prompt], { timeout: CALL_TIMEOUT_MS });
255
+ return { session_id: binding.session_id, status: 'accepted', receipt, capabilities: room_delivery(config, binding.session_id, before, task, options), steer: app_steer(config, binding.session_id, task, options.connect) };
143
256
  }
144
- const app = new CodexAppClient(config.pipe_path);
257
+ let app;
145
258
  try {
146
259
  let target, source;
147
260
  try {
148
- await app.open();
261
+ app = await connect();
149
262
  target = await codex_target(app, config);
150
263
  source = await creation_source(app, config, source_file(process.env, user_home));
151
264
  } catch (error) { throw not_sent(error); }
152
265
  const result = await app.create_thread(source, task.prompt, `CoDiscuss · ${task.participant}`, target);
153
266
  task.on_binding(result.thread_id);
154
267
  bind_access(task.access_path, result.thread_id);
155
- return { session_id: result.thread_id, status: 'accepted', capabilities: room_delivery(config, result.thread_id, new Set(), task), steer: app_steer(config, result.thread_id) };
156
- } finally { app.close(); }
268
+ return { session_id: result.thread_id, status: 'accepted', capabilities: room_delivery(config, result.thread_id, { turns: new Set(), items: new Set() }, task, options), steer: app_steer(config, result.thread_id, task, options.connect) };
269
+ } finally { app?.close(); }
157
270
  }
158
271
 
159
272
  // A private chat turn is read back from the chat itself (remarks and finished steps), and archiving the chat stops it.
@@ -170,21 +283,36 @@ const UNARCHIVE_ATTEMPTS = 3;
170
283
  const XML_ENTITIES = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'", '&amp;': '&' };
171
284
 
172
285
  /** The text one App-delivered message carried in `<codex_delegation><input>`, or null for other items. */
173
- function delegated_input(item) {
174
- if (item?.type !== 'functionCallOutput' || item.name !== 'send_message_to_thread') return null;
286
+ function delegated_input(item, names = ['send_message_to_thread']) {
287
+ if (item?.type !== 'functionCallOutput' || !names.includes(item.name)) return null;
175
288
  const match = /<input>([\s\S]*?)(?:<\/input>|$)/.exec(item.output?.text || '');
176
- return match ? match[1].replace(/&(lt|gt|quot|apos|amp);/g, entity => XML_ENTITIES[entity]).trim() : null;
289
+ return match ? { text: match[1].replace(/&(lt|gt|quot|apos|amp);/g, entity => XML_ENTITIES[entity]).trim(), truncated: Boolean(item.output?.truncated) } : null;
177
290
  }
178
291
 
179
- /** The turn that took this chat line, and the line's place in it; items read before sending are earlier lines. */
180
- function find_turn(snapshot, prompt, seen) {
181
- const text = prompt.trim();
182
- for (const turn of snapshot.turns) {
292
+ /** The text a userMessage item carried (as `codex queue` delivers a room prompt), or null for other items. */
293
+ function user_input(item) {
294
+ if (item?.type !== 'userMessage') return null;
295
+ const parts = Array.isArray(item.content) ? item.content : [];
296
+ const text = parts.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n').trim();
297
+ return text ? { text, truncated: Boolean(item.truncated) } : null;
298
+ }
299
+
300
+ /** Whether an extracted prompt matches the exact text this delivery sent. */
301
+ function matches_prompt(input, prompt) {
302
+ return Boolean(input?.text && prompt && (input.text === prompt || (input.truncated && prompt.startsWith(input.text))));
303
+ }
304
+
305
+ /** The turn that took this prompt, and the prompt's place in it; items read before sending are earlier turns. */
306
+ function find_turn(snapshot, prompt, seen, { allow_user = false, names = ['send_message_to_thread'], seen_turns = null } = {}) {
307
+ const text = String(prompt || '').trim();
308
+ if (!text) return null;
309
+ for (const turn of snapshot.turns || []) {
183
310
  const index = (turn.items || []).findIndex(item => {
184
- const input = !seen.has(item.id) && delegated_input(item);
185
- return input && (input === text || (item.output.truncated && text.startsWith(input)));
311
+ if (item?.id ? seen.has(item.id) : seen_turns?.has(turn.id)) return false;
312
+ const input = delegated_input(item, names) || (allow_user ? user_input(item) : null);
313
+ return matches_prompt(input, text);
186
314
  });
187
- if (index >= 0) return { turn, index };
315
+ if (index >= 0) return { turn, index, item_id: (turn.items || [])[index]?.id || '' };
188
316
  }
189
317
  return null;
190
318
  }
@@ -200,9 +328,9 @@ function step_state(item) {
200
328
  return ['failed', 'declined'].includes(item.status) || (item.exitCode ?? 0) !== 0 ? 'failed' : 'done';
201
329
  }
202
330
 
203
- /** One finished item of the turn as a process log entry, or null for items the chat page does not show. */
204
- function chat_entry(item) {
205
- const id = item.id;
331
+ /** One item of the turn as a process log entry, or null for items the chat page does not show. */
332
+ function chat_entry(item, fallback_id = item?.id) {
333
+ const id = item.id || fallback_id;
206
334
  if (item.type === 'agentMessage') return item.phase === 'commentary' && item.text ? { id, kind: 'message', body: item.text, state: 'done' } : null;
207
335
  if (item.type === 'commandExecution') return { id, kind: 'command', title: command_title(item.command), body: item.output?.text || '', state: step_state(item) };
208
336
  if (item.type === 'webSearch') return { id, kind: 'search', title: item.query || item.action?.query || '', state: 'done' };
@@ -238,7 +366,7 @@ function read_progress(snapshot, context, log) {
238
366
  const found = find_turn(snapshot, context.task.prompt, context.seen);
239
367
  if (!found) return null;
240
368
  const items = found.turn.items.slice(found.index + 1);
241
- for (const item of items) { const entry = chat_entry(item); if (entry) log(entry); }
369
+ for (const [index, item] of items.entries()) { const entry = chat_entry(item, `${found.turn.id}:${index}`); if (entry) log(entry); }
242
370
  const newest = snapshot.turns[0] === found.turn;
243
371
  if (found.turn.status === 'inProgress' || (newest && snapshot.thread.status.type === 'active')) return null;
244
372
  return { turn: found.turn, items };
@@ -247,12 +375,7 @@ function read_progress(snapshot, context, log) {
247
375
  /** Poll the chat until the turn that took this line ends, it is stopped, or the wait runs out. */
248
376
  async function follow_chat(context) {
249
377
  const { task, state, thread_id } = context;
250
- const log_path = resolve(task.directory, `codex-${task.id}.log`);
251
- const logged = new Map();
252
- const log = entry => {
253
- const line = JSON.stringify({ type: 'codiscuss.entry', entry });
254
- if (logged.get(entry.id) !== line) { logged.set(entry.id, line); task.on_output?.(log_path, `${line}\n`); }
255
- };
378
+ const log = entry_logger(task);
256
379
  const deadline = Date.now() + context.timeout_ms;
257
380
  let app = context.app;
258
381
  let failures = 0;
@@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url';
13
13
  import { cli_delivery } from './cli.mjs';
14
14
  import { daemon_chat, daemon_link } from './codex_daemon.mjs';
15
15
  import { CALL_TIMEOUT_MS, edge_entries, launch_directory, log_entries, marked, model_entry, json_line, newest_record, not_sent,
16
- page_sessions, preview_messages, project_directory, prompt_text, prompt_title, query_catalog, remove_session_files, same_path, typed_prompt } from './common.mjs';
16
+ page_sessions, preview_messages, project_directory, prompt_text, prompt_title, query_catalog, remove_session_files, same_path, shell_written_paths, typed_prompt } from './common.mjs';
17
17
  import { adapter_capabilities } from './profiles.mjs';
18
18
 
19
19
  /** Codex exec may linger after its final event; the finished turn is already saved, so stop it to free the session. */
@@ -103,8 +103,9 @@ export function codex_permissions(config, task, platform = process.platform) {
103
103
  const profile = `{extends=${JSON.stringify(base)},filesystem={${rules}},network={enabled=true}}`;
104
104
  // The Windows sandbox account cannot write the user's TEMP, so PowerShell starts in ConstrainedLanguage and Codex's
105
105
  // UTF-8 output setup fails silently, garbling Chinese; a TEMP inside the writable drafts keeps FullLanguage.
106
- const temp = platform === 'win32' ? ['-c', `shell_environment_policy.set.TEMP=${JSON.stringify(drafts)}`,
107
- '-c', `shell_environment_policy.set.TMP=${JSON.stringify(drafts)}`] : [];
106
+ const temp_path = task.scratch_directory ? resolve(task.scratch_directory).replaceAll('\\', '/') : drafts;
107
+ const temp = platform === 'win32' ? ['-c', `shell_environment_policy.set.TEMP=${JSON.stringify(temp_path)}`,
108
+ '-c', `shell_environment_policy.set.TMP=${JSON.stringify(temp_path)}`] : [];
108
109
  // 自动 is what `codex exec --approve-for-me` sets (that flag is missing on `exec resume`): the model asks to escalate
109
110
  // and Codex's automatic review answers instead of a person (tested 0.163).
110
111
  const approval = config.project_access === 'auto' ? ['-c', 'approval_policy="on-request"', '-c', 'approvals_reviewer="auto_review"']
@@ -231,8 +232,12 @@ const events = {
231
232
  },
232
233
  note(event) { return event.type === 'item.completed' && event.item?.type === 'agent_message' ? String(event.item.text || '').trim() : ''; },
233
234
  edits(event) {
234
- if (event.type !== 'item.completed' || event.item?.type !== 'file_change') return [];
235
- return (event.item.changes || []).map(change => String(change?.path || '')).filter(Boolean);
235
+ if (event.type !== 'item.completed') return [];
236
+ const item = event.item;
237
+ if (!item || ['failed', 'declined'].includes(item.status)) return [];
238
+ if (item.type === 'command_execution' && item.exit_code === 0) return shell_written_paths(item.command);
239
+ if (item.type !== 'file_change') return [];
240
+ return (item.changes || []).map(change => String(change?.path || '')).filter(Boolean);
236
241
  },
237
242
  detail: codex_detail,
238
243
  };