ai_co_discuss 0.4.85 → 0.4.86

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.
@@ -381,19 +381,53 @@ async function post_inbox(inbox, text) {
381
381
  });
382
382
  }
383
383
 
384
- /** Post one task into an open Claude window; it starts a turn there, or between tool calls of the turn it is in. */
385
- async function inbox_delivery(config, window, task) {
384
+ // An interjection into a room task's window turn; the window shows it as a message from another session.
385
+ const ROOM_STEER_LEAD = 'CoDiscuss 本机服务代房间转达,这是对你当前房间任务的追加要求,不是其他会话的来信:请在本次任务的回答里一并处理,不要用 SendMessage 回复。';
386
+
387
+ /**
388
+ * Post one task into an open Claude window; it starts a turn there, or between tool calls of the turn it is in. As in a
389
+ * private chat turn, an interjection is one more inbox message with its own marker, and the turn stops by an Esc key
390
+ * written into the window's console when that console can be reached; `options.console` replaces it in tests.
391
+ */
392
+ async function inbox_delivery(config, window, task, options = {}) {
386
393
  try { bind_access(task.access_path, config.session_id); }
387
394
  catch (error) { throw not_sent(error); }
388
395
  // Only what the window writes after this point can be the turn that takes this task.
389
396
  const file = session_path(config.session_id);
390
397
  const offset = file ? statSync(file).size : 0;
391
- await post_inbox(window.inbox, `CoDiscuss 本机服务代房间转达(你已注册为该房间成员,这是房间分派给你的任务):\n${task.prompt}`);
398
+ const log_path = resolve(task.directory, `claude-${task.id}.log`);
399
+ const console_of = options.console || window_console;
400
+ const reached = console_of(window.pid);
401
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.window', terminal: reached.terminal, stoppable: reached.ok, reason: reached.reason })}\n`);
402
+ const handle = new EventEmitter();
403
+ // The turn's steps, read from the session log, are the execution's process log, so the private chat can show them.
404
+ const watcher = watch_window_turn({ file, offset, pid: window.pid, marker: `${task.id}.task.json`, log_path }, task, {
405
+ on_end: () => handle.emit('close', 0),
406
+ stop_key: () => {
407
+ const sent = console_of(window.pid, { escape: true });
408
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.stop', terminal: sent.terminal, sent: sent.ok, reason: sent.reason })}\n`);
409
+ return sent;
410
+ } });
411
+ try { await post_inbox(window.inbox, `CoDiscuss 本机服务代房间转达(你已注册为该房间成员,这是房间分派给你的任务):\n${task.prompt}`); }
412
+ catch (error) { watcher.cancel(); throw error; }
392
413
  // The discussion runner enters the execution once the session is known, as it does when a process reports it.
393
414
  task.on_binding?.(config.session_id);
394
- // The turn's steps, read from the session log, are the execution's process log, so the private chat can show them.
395
- watch_window_turn({ file, offset, pid: window.pid, marker: `${task.id}.task.json`, log_path: resolve(task.directory, `claude-${task.id}.log`) }, task);
396
- return { session_id: config.session_id, status: 'accepted', capabilities: { ...WINDOW, progress: true } };
415
+ if (reached.ok) {
416
+ handle.kill = () => watcher.stop();
417
+ // The Esc key goes into the owner's own window; only the owner's stop sends it, never the runner's shutdown.
418
+ handle.stop_on_shutdown = false;
419
+ task.on_process?.(handle);
420
+ }
421
+ let count = 0;
422
+ const steer = async text => {
423
+ const tag = `[codiscuss:${task.id}+${++count}]`;
424
+ if (!watcher.expect(tag)) return false;
425
+ try { await post_inbox(window.inbox, `${tag} ${ROOM_STEER_LEAD}\n\n${text}`); }
426
+ catch { watcher.forget(tag); return false; }
427
+ task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.interjection', text })}\n`);
428
+ return true;
429
+ };
430
+ return { session_id: config.session_id, status: 'accepted', capabilities: { ...WINDOW, stoppable: reached.ok, progress: true }, steer };
397
431
  }
398
432
 
399
433
  /**
@@ -598,17 +632,27 @@ export function watch_window_turn({ file, offset, pid, marker, session_id = '',
598
632
  function try_stop() {
599
633
  const now = Date.now();
600
634
  if (stop_sent) {
601
- if (now - stop_sent >= stop_end_wait) finish('已向 Claude 窗口发送停止键,但这一轮仍未结束');
635
+ if (now - stop_sent >= stop_end_wait) unstopped('已向 Claude 窗口发送停止键,但这一轮仍未结束');
602
636
  return;
603
637
  }
604
638
  const ready = taken && !open_tools.size && window_state(pid, env)?.status === 'busy';
605
639
  if (!ready) {
606
- if (now - stop_asked >= stop_tool_wait) finish(open_tools.size ? '工具仍在执行,未能停止' : !taken ? '消息还在 Claude 窗口的队列里,未能停止' : 'Claude 窗口一直没有处于执行中,未能停止');
640
+ if (now - stop_asked >= stop_tool_wait) unstopped(open_tools.size ? '工具仍在执行,未能停止' : !taken ? '消息还在 Claude 窗口的队列里,未能停止' : 'Claude 窗口一直没有处于执行中,未能停止');
607
641
  return;
608
642
  }
609
643
  stop_sent = now;
610
644
  const sent = stop_key?.() || { ok: false, reason: '无法向 Claude 窗口发送停止键' };
611
- if (!sent.ok) finish(sent.reason);
645
+ if (!sent.ok) unstopped(sent.reason);
646
+ }
647
+ /**
648
+ * A stop that did not take: a chat turn fails with the reason. A room task's turn goes on in the window, so the watch
649
+ * keeps following it until it really ends (the runner's next stop request tries again), and only its log says why.
650
+ */
651
+ function unstopped(reason) {
652
+ if (chat) return finish(reason);
653
+ clearInterval(stop_timer);
654
+ stop_timer = null; stop_asked = 0; stop_sent = 0;
655
+ if (log_path) task.on_output?.(log_path, `${JSON.stringify({ type: 'codiscuss.stop', sent: false, reason })}\n`);
612
656
  }
613
657
  return {
614
658
  get done() { return done; },
@@ -651,10 +695,10 @@ function process_alive(pid) {
651
695
  }
652
696
 
653
697
  /** Use one official Claude process per turn and resume the persisted session, or post into the member's open window. */
654
- async function deliver(config, binding, task, spawn_process = spawn) {
698
+ async function deliver(config, binding, task, spawn_process = spawn, user_home, options = {}) {
655
699
  const window = held_window(config, binding);
656
700
  // Only a task written for the window names its credential file; a background process gets it through its environment.
657
- if (window?.inbox && task.inbox) return inbox_delivery(config, window, task);
701
+ if (window?.inbox && task.inbox) return inbox_delivery(config, window, task, options);
658
702
  binding = adopted_fork(config, binding, Boolean(window));
659
703
  const session_id = binding.session_id || randomUUID();
660
704
  try { bind_access(task.access_path, session_id); }
@@ -867,7 +911,7 @@ function skills(profile, options = {}) {
867
911
  const commands = reply.response.response?.commands;
868
912
  if (reply.response.subtype !== 'success' || !Array.isArray(commands)) return finish(new Error('Claude 未返回技能目录'));
869
913
  finish(null, commands.filter(command => !command.builtin).map(command => ({
870
- id: command.name, label: command.name, description: command.description || '', prompt: `请调用技能「${command.name}」:`,
914
+ id: command.name, label: command.name, description: command.description || '', prompt: `/${command.name} `,
871
915
  })));
872
916
  },
873
917
  }), { ...options, cwd: profile.cwd || homedir(), catalog_label: '技能' });
@@ -83,21 +83,63 @@ function app_steer(config, thread_id) {
83
83
  };
84
84
  }
85
85
 
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.
88
+ const ROOM_POLL_MS = 2000;
89
+ const ROOM_READ = { turnLimit: 3 };
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(); }
97
+ }
98
+
99
+ /**
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.
102
+ * `options` (`connect`, `poll_ms`, `timeout_ms`) replace the App and the timings in tests.
103
+ */
104
+ export async function watch_room_turn(config, thread_id, seen, task, options = {}) {
105
+ const connect = options.connect || (() => open_app(config));
106
+ const deadline = Date.now() + (options.timeout_ms ?? CHAT_TIMEOUT_MS);
107
+ let app = null, failures = 0;
108
+ try {
109
+ while (Date.now() < deadline) {
110
+ await sleep(options.poll_ms ?? ROOM_POLL_MS);
111
+ let snapshot;
112
+ try { app ||= await connect(); snapshot = await app.read_thread(thread_id, ROOM_READ); failures = 0; }
113
+ 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?.();
116
+ }
117
+ } finally { app?.close(); }
118
+ }
119
+
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 };
125
+ }
126
+
86
127
  /** Deliver one task to Codex's real App, with the original chat reused afterward. */
87
128
  async function deliver(config, binding, task, _spawn, user_home = homedir()) {
88
129
  if (binding.session_id) {
89
130
  try { bind_access(task.access_path, binding.session_id); }
90
131
  catch (error) { throw not_sent(error); }
132
+ const seen = await turns_before(config, binding.session_id);
91
133
  // `codex queue` reaches only a chat the App has loaded; a fork made after a rewind, or a chat after the App restarted,
92
134
  // is not loaded until a message is sent through the App itself (tested on App tools, 2026-10).
93
135
  if (await unloaded(config, binding.session_id)) {
94
136
  const app = new CodexAppClient(config.pipe_path);
95
137
  try { await app.open(); await app.send_message(binding.session_id, task.prompt); }
96
138
  finally { app.close(); }
97
- return { session_id: binding.session_id, status: 'accepted', capabilities: IN_APP, steer: app_steer(config, binding.session_id) };
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) };
98
140
  }
99
141
  const receipt = await run_program(config.executable, ['queue', '--thread', binding.session_id, '--message', task.prompt], { timeout: CALL_TIMEOUT_MS });
100
- return { session_id: binding.session_id, status: 'accepted', receipt, capabilities: IN_APP, steer: app_steer(config, binding.session_id) };
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) };
101
143
  }
102
144
  const app = new CodexAppClient(config.pipe_path);
103
145
  try {
@@ -110,7 +152,7 @@ async function deliver(config, binding, task, _spawn, user_home = homedir()) {
110
152
  const result = await app.create_thread(source, task.prompt, `CoDiscuss · ${task.participant}`, target);
111
153
  task.on_binding(result.thread_id);
112
154
  bind_access(task.access_path, result.thread_id);
113
- return { session_id: result.thread_id, status: 'accepted', capabilities: IN_APP, steer: app_steer(config, 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) };
114
156
  } finally { app.close(); }
115
157
  }
116
158
 
@@ -5,7 +5,9 @@
5
5
  * the web page reads as well;
6
6
  * - its behaviour in its own module, a descriptor with the same shape for every software:
7
7
  * - `deliver(config, binding, task, spawn_process, user_home)` → `{session_id, status, capabilities, steer?}`, where
8
- * `capabilities` `{stoppable, progress}` says what this one delivery can do, and `steer(text)` (when the running
8
+ * `capabilities` `{stoppable, progress, ends?}` says what this one delivery can do (`ends`: a turn it can neither stop
9
+ * nor follow is still watched, and `task.on_turn_end()` reports when it ended, saying nothing about an answer; the
10
+ * runner uses it only to tell the site a voided turn is over), and `steer(text)` (when the running
9
11
  * software can take an interjection without ending its turn) passes one in, resolving false once the turn is over;
10
12
  * - `session`: `{path, exists, branch, settings}` for the software's own session store, or null; with `list(options)`
11
13
  * and `preview(session_id, options)` when its stored conversations can be browsed (see `software_sessions`);
@@ -25,6 +25,9 @@
25
25
  * `browse_sessions`: its stored conversations can be listed and previewed on this machine, so the owner picks the one a
26
26
  * new member resumes from a browsing window instead of typing its ID; a picked conversation may be bound even without
27
27
  * `host_existing`.
28
+ * `copy_bound`: a woken member bound to an existing conversation (picked in that window, given by ID or restored)
29
+ * works in a copy of it made at its first turn, so the original stays as it was: resuming it in the background beside
30
+ * a window still open on it would split it. A taken-over manual member (`own`) keeps its original conversation.
28
31
  * - `defaults_by_query`: its default model is read by running it (seconds), so a quick read leaves it for later.
29
32
  * - `capabilities`: `delivery` `{stoppable, progress}` of a usual delivery (each delivery reports its own); `rewind`: `cut`
30
33
  * (the runner cuts the session), `fresh` (context rebuilt each time) or `kept` (cannot be cut here); `project` (works in
@@ -89,7 +92,7 @@ export const ADAPTER_PROFILES = {
89
92
  efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], models: true, access_levels: ALL_ACCESS, per_tool_allow: false,
90
93
  access_hints: { read: '只读沙箱', write: '项目可写的沙箱,命令在沙箱内运行、可联网',
91
94
  auto: '沙箱外的操作由模型申请提权,Codex 自动审核代替人工批准', full: '无沙箱、无审批(--dangerously-bypass-approvals-and-sandbox)' },
92
- client: 'codex', adopt: 'session', host_existing: true, session_family: 'codex', browse_sessions: true,
95
+ client: 'codex', adopt: 'session', host_existing: true, session_family: 'codex', browse_sessions: true, copy_bound: true,
93
96
  lockdown_hint: '沙箱只读档仍可读整个磁盘、运行任意只读命令,无法只放行 codiscuss 命令',
94
97
  sandbox_needs_desktop: true,
95
98
  capabilities: { delivery: PROCESS, rewind: 'cut', project: true, access_env: true, enforces_read_only: true, limits_directories: true, ripgrep: true, chat: true, resume: true, images: true, capture: FINAL_REMARK,
@@ -109,7 +112,7 @@ export const ADAPTER_PROFILES = {
109
112
  efforts: ['low', 'medium', 'high', 'xhigh', 'max'], models: true, access_levels: ALL_ACCESS, per_tool_allow: true,
110
113
  access_hints: { read: '只放行网站命令与草稿,不改项目文件、不跑其他命令', write: '可改项目文件,Bash / PowerShell 命令全部放行(无沙箱)',
111
114
  auto: 'Claude auto 模式:由分类器判断,实测项目外写入和联网都会放行', full: 'bypassPermissions:跳过全部权限检查' },
112
- client: 'claude', adopt: 'own_cwd', host_existing: true, restore_manual: true, browse_sessions: true,
115
+ client: 'claude', adopt: 'own_cwd', host_existing: true, restore_manual: true, browse_sessions: true, copy_bound: true,
113
116
  resume_command: session_id => `claude --resume ${session_id}`,
114
117
  // Claude Code runs commands through bash on Windows too, where the npm shim works without .cmd.
115
118
  windows_command: 'codiscuss',
@@ -125,7 +128,7 @@ export const ADAPTER_PROFILES = {
125
128
  full: '跳过全部权限确认(--dangerously-skip-permissions),并放开沙箱外命令与 MCP 工具' },
126
129
  unsupported_hints: { auto: 'agy 只在交互窗口提供自动模式,后台运行(-p)不支持' },
127
130
  // Only a conversation this tool created gets its session rules; an existing one keeps its own project and permissions.
128
- client: 'antigravity', adopt: 'session', host_existing: false, own_project_when_bound: true, browse_sessions: true,
131
+ client: 'antigravity', adopt: 'session', host_existing: false, own_project_when_bound: true, browse_sessions: true, copy_bound: true,
129
132
  // Confined by session rules that allow only the codiscuss commands and deny MCP and web reads (agy_lockdown_grants).
130
133
  capabilities: { delivery: PROCESS, rewind: 'cut', project: true, access_env: true, chat: true, capture: FINAL_REMARK, tool_lockdown: true },
131
134
  // A read-only agy session allows only codiscuss commands and headless agy ends the turn on a denied one; agy streams no
@@ -1596,8 +1596,10 @@ function switch_codex_adapter(context, name, profile, adapter) {
1596
1596
  const store = new DiscussionStore(current.directory);
1597
1597
  try {
1598
1598
  const binding = store.binding(name).session_id;
1599
- if (session && binding && session !== binding) throw new Error('原会话绑定不一致,请先核对原会话');
1600
- session = binding || session;
1599
+ // A member invited with a conversation the CLI copies works in that copy, and keeps naming the original it came from.
1600
+ const copied = Boolean(session && binding && session !== binding && adapter_profile(profile.adapter)?.copy_bound);
1601
+ if (session && binding && session !== binding && !copied) throw new Error('原会话绑定不一致,请先核对原会话');
1602
+ if (!copied) session = binding || session;
1601
1603
  } finally { store.close(); }
1602
1604
  }
1603
1605
  if (!session) throw new Error('尚无实际 Codex 会话,不能切换;请先完成首次接入');
@@ -168,8 +168,9 @@ export class DiscussionStore {
168
168
  const next = entries[index];
169
169
  if (JSON.stringify(item) === JSON.stringify(next)) return true;
170
170
  const session = this.binding(item[0]).session_id || item[6];
171
+ // A member working in a copy of its invited conversation keeps naming the original, so that may stay as it was.
171
172
  return item[0] === next[0] && same_session_family(item[1], next[1])
172
- && session && next[6] === session && (!item[6] || item[6] === session)
173
+ && (next[6] === item[6] || session && next[6] === session && (!item[6] || item[6] === session))
173
174
  && JSON.stringify(item.slice(2, 6)) === JSON.stringify(next.slice(2, 6));
174
175
  });
175
176
  // Experts invited during a run only add entries; every existing binding must stay as it was.
@@ -444,19 +444,31 @@ export async function join_invite(home, input, deps = {}) {
444
444
  throw failure('join_incomplete', '对方返回的加入结果不完整');
445
445
  }
446
446
  return with_store(home, (store, secrets, now) => {
447
- const id = attempt.id;
448
447
  const name = joined.machine?.name || keys.name || invite.machine_name;
449
- // Accepting the invitation is the consent: a new record answers at once, confined.
450
448
  const machine = store.machines[keys.fingerprint] ||= {};
451
449
  Object.assign(machine, { machine: keys.id, site: invite.site, machine_name: name, updated_at: now });
452
- store.records[id] = { id, site: invite.site, machine: keys.id, machine_name: name, machine_fingerprint: keys.fingerprint,
450
+ // Invited back as the same member of the same room: the record this computer still keeps carries on, with its
451
+ // history and settings; once deleted, a new record starts.
452
+ const previous = Object.values(store.records).find(record => record.id !== attempt.id && record.machine_fingerprint === keys.fingerprint
453
+ && record.room === joined.room.id && record.member === joined.member.name && (record.member_id ?? null) === (joined.member.id ?? null));
454
+ const id = previous?.id || attempt.id;
455
+ const fresh = { id, site: invite.site, machine: keys.id, machine_name: name, machine_fingerprint: keys.fingerprint,
453
456
  machine_key: keys.public_key, fingerprint_checked: Boolean(invite.fingerprint), room: joined.room.id, room_title: String(joined.room.name || invite.room_name),
454
457
  member: joined.member.name, member_id: joined.member.id ?? null, key_id, open_level: joined.level || invite.level || 'read',
455
458
  directories: Array.isArray(joined.directories) ? joined.directories : [],
456
- expires_at: Number(joined.expires_at) ? Number(joined.expires_at) * 1000 : null, ai, ai_reported: JSON.stringify(identity), wake: 'auto', confined: true,
457
- limits: null, wakes: 0, last_wake_at: null, paused: false,
458
- status: 'active', contact: { at: now, state: 'online', error: '' }, approvals: [], history: [], running: null, joined_at: now };
459
- secrets.get()[id] = { private_key: pair.private_key, token: joined.token };
459
+ expires_at: Number(joined.expires_at) ? Number(joined.expires_at) * 1000 : null, ai, ai_reported: JSON.stringify(identity),
460
+ limits: null, paused: false, status: 'active', contact: { at: now, state: 'online', error: '' }, approvals: [], running: null };
461
+ if (previous) {
462
+ const { end_reason, leave_pending, ...kept } = previous;
463
+ store.records[id] = { ...kept, ...fresh, rejoined_at: now };
464
+ } else {
465
+ // Accepting the invitation is the consent: a new record answers at once, confined.
466
+ store.records[id] = { ...fresh, wake: 'auto', confined: true, wakes: 0, last_wake_at: null, history: [], joined_at: now };
467
+ }
468
+ const values = secrets.get();
469
+ values[id] = { private_key: pair.private_key, token: joined.token };
470
+ // A retry of this join finds the record it ended up in.
471
+ values[attempt_key] = { ...values[attempt_key], id };
460
472
  secrets.changed = true;
461
473
  return { record: record_view(store.records[id], store) };
462
474
  });
@@ -197,8 +197,14 @@ async function invite_site(home, site_url) {
197
197
  export async function create_invite(home, { room_id, token, level = 'read', folders, duration = '1h', site_url, member_id, by = 'computer' }, { fetcher } = {}) {
198
198
  const room = await owned_room(home, room_id, token, fetcher);
199
199
  if (member_id) {
200
- const current = await local_call(room, 'GET', `/api/rooms/${encodeURIComponent(room_id)}/external-members/${member_id}`, { token, fetcher });
200
+ const path = `/api/rooms/${encodeURIComponent(room_id)}/external-members/${member_id}`;
201
+ let current = await local_call(room, 'GET', path, { token, fetcher });
201
202
  if (current.status !== 200) throw new GatewayError(current.status, current.body?.error || '外部成员不存在');
203
+ // A member that has ended is invited back as itself: its seat awaits check-in again, with the settings it had.
204
+ if (current.body.status === 'removed') {
205
+ current = await local_call(room, 'POST', path, { token, fetcher, body: { action: 'reopen' } });
206
+ if (current.status !== 200) throw new GatewayError(current.status, current.body?.error || '外部成员不存在');
207
+ }
202
208
  level = current.body.scope;
203
209
  duration = current.body.duration;
204
210
  folders = current.body.directories.map(path => room.directories.indexOf(path));
@@ -13,7 +13,8 @@ import { atomic_json } from './files.mjs';
13
13
  import { image_settings } from './image_service.mjs';
14
14
  import { outside_directory, room_directories } from './project_files.mjs';
15
15
  import { SessionDriver } from './session_driver.mjs';
16
- import { effective_profile, load_room_workflow, workflow_in_use, workflow_task_field } from './workflows.mjs';
16
+ import { slash_names } from './slash_names.mjs';
17
+ import { effective_profile, load_room_workflow, workflow_directory, workflow_in_use, workflow_task_field } from './workflows.mjs';
17
18
  import { DEFAULT_SCHEDULER_MODE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, decide_review_completion, route_free_message, route_prompt_version, scheduler_thresholds, some_members } from './scheduler.mjs';
18
19
  import { room_text, room_payload } from './room_text.mjs';
19
20
  import { question_notice } from './question_weixin.mjs';
@@ -41,6 +42,8 @@ const NOTICE_EXCERPT = 300;
41
42
  // A manual member's session that refuses a delivery is retried in the same execution, after a wait the owner can cut short.
42
43
  const MAX_DELIVERY_RETRIES = 3;
43
44
  const RETRY_DELAY_SECONDS = 60;
45
+ // How long a voided turn the runner cannot stop is still watched for its end: a little past the site's 600-second hold.
46
+ const UNSTOPPABLE_FOLLOW_MS = 15 * 60_000;
44
47
  // The failure classes an adapter may report (adapter contract `on_failure(reason, {failure_class, ...})`).
45
48
  const FAILURE_CLASSES = ['quota', 'auth', 'output_truncated', 'compaction_failed', 'policy_blocked'];
46
49
  const RESTART_REASON = room_text("重启后无法确认上次执行结果");
@@ -184,6 +187,40 @@ export function attachment_placeholder(file, number) {
184
187
  return `[${IMAGE_TYPES.has(file.content_type) ? '图片' : '文件'} #${number}]`;
185
188
  }
186
189
 
190
+ /** The text of the user's own messages among those that woke this execution; an unreadable one is skipped. */
191
+ export async function user_request_texts(config, execution) {
192
+ const message_ids = [...new Set((execution.requests || []).map(item => item.message_id).filter(Number.isInteger))];
193
+ const texts = [];
194
+ for (const message_id of message_ids) {
195
+ try {
196
+ const message = await api(config, `/messages/${message_id}`);
197
+ if (message.author === '用户' && message.text) texts.push(message.text);
198
+ } catch { /* The host still reads the message itself. */ }
199
+ }
200
+ return texts;
201
+ }
202
+
203
+ /**
204
+ * The workflows and sub-workflows the user named with "/" for the host: a sub-workflow of the workflow in use, or a
205
+ * workflow in this computer's library other than that one. The task carries them, so the host never has to recognise
206
+ * the syntax. Other "/" words are left to the message. Null when nothing was named.
207
+ */
208
+ export function named_workflows(texts, { sub_workflows = [], current = '', in_library = () => false } = {}) {
209
+ const named = { workflows: [], sub_workflows: [] };
210
+ for (const name of new Set(texts.flatMap(slash_names))) {
211
+ if (sub_workflows.includes(name)) named.sub_workflows.push(name);
212
+ else if (name !== current && in_library(name)) named.workflows.push(name);
213
+ }
214
+ const kept = Object.fromEntries(Object.entries(named).filter(([, names]) => names.length));
215
+ return Object.keys(kept).length ? kept : null;
216
+ }
217
+
218
+ /** Whether this computer's workflow library has a workflow with this ID. */
219
+ function library_has(config, id) {
220
+ try { return Boolean(config.api_home) && existsSync(join(workflow_directory(config.api_home, id), 'SKILL.md')); }
221
+ catch { return false; }
222
+ }
223
+
187
224
  /**
188
225
  * Download the attachments of the messages that woke this execution into its own folder, checked against their SHA-256,
189
226
  * so the member reads local copies and software that takes images gets them with the task. A file that cannot be fetched
@@ -245,7 +282,7 @@ export function room_goal(room) {
245
282
  }
246
283
 
247
284
  export function free_task_files(config, member, execution, binding, { session = null, suggestions = [], reviews = [], stopped = [], process_access = true,
248
- workflow = null, room_members = [], goal = null, attachments = [], room = null, model_change = null } = {}) {
285
+ workflow = null, room_members = [], goal = null, attachments = [], room = null, model_change = null, request_texts = [] } = {}) {
249
286
  const id = `free-${execution.id}`;
250
287
  const draft_directory = member_drafts(config, member.name);
251
288
  mkdirSync(draft_directory, { recursive: true });
@@ -280,7 +317,7 @@ export function free_task_files(config, member, execution, binding, { session =
280
317
  ...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-session/references/host.md'] : [],
281
318
  ...direct_question ? ['discuss-participant/references/room.md'] : []]
282
319
  : ['discuss-participant/SKILL.md', 'discuss-participant/references/room.md',
283
- ...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-host/references/room.md'] : []];
320
+ ...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-host/references/room.md', 'discuss-host/references/members.md'] : []];
284
321
  // The host works a goal while it is open, and also handles the request that opens it or the wrap-up after it ends.
285
322
  const goal_task = member.role === 'host' && (['active', 'paused'].includes(goal?.status)
286
323
  || requests.some(item => ['goal_start', 'goal_continue'].includes(item.purpose)));
@@ -309,14 +346,17 @@ export function free_task_files(config, member, execution, binding, { session =
309
346
  const image = config.image_generation && image_settings(config.api_home).configured ? image_settings(config.api_home) : null;
310
347
  // Relay, question and image rules are read only when the task carries them, keeping the everyday path short.
311
348
  if (image || requests.some(item => item.sequence || item.question || item.question_needed)) skills.push('discuss-participant/references/situations.md');
312
- // The host's occasional pages likewise: relays and question cards, room control on a notice, the workflow, pre-set reviews.
349
+ const named = member.role === 'host' ? named_workflows(request_texts, { sub_workflows: host_workflow?.sub_workflows.map(sub => sub.id) || [],
350
+ current: host_workflow?.id || '', in_library: id => library_has(config, id) }) : null;
351
+ // The host's occasional pages likewise: relays and question cards, room control on a notice, the workflow (also when
352
+ // the user named one to enable), pre-set reviews.
313
353
  if (member.role === 'host') {
314
354
  if (requests.some(item => item.sequence || item.question?.task || item.question_needed)) skills.push('discuss-host/references/relay.md');
315
355
  // A notice, or a hand-back where someone failed or was cancelled, is what calls for diagnosing and recovering.
316
356
  if (requests.some(item => item.purpose === 'notice' || (item.outcome || []).some(entry => ['failed', 'cancelled'].includes(entry.status)))) {
317
357
  skills.push('discuss-host/references/control.md');
318
358
  }
319
- if (workflow_field) skills.push('discuss-host/references/workflow.md');
359
+ if (workflow_field || named?.workflows) skills.push('discuss-host/references/workflow.md');
320
360
  if (reviews.length) skills.push('discuss-host/references/dev-flow.md');
321
361
  }
322
362
  atomic_json(task_path, { site: config.site, room: config.room, mode: 'free', member: member.name,
@@ -333,6 +373,7 @@ export function free_task_files(config, member, execution, binding, { session =
333
373
  ...(model_change ? { model_change: { ...model_change, note: `你的模型已从 ${model_change.from} 换为 ${model_change.to};不要按之前的自述判断自己用的是哪个模型。` } } : {}),
334
374
  // What became of the @s in this member's previous answer: quoted, waiting, queued for the host or picked up.
335
375
  ...(execution.mentions?.length ? { mentions: execution.mentions } : {}),
376
+ ...(named ? { named_workflows: named } : {}),
336
377
  ...(stopped.length ? { stopped_executions: stopped } : {}),
337
378
  role: member.role || 'member',
338
379
  // Only where the adapter declares capture: without it, only a submitted answer is saved, as the skill already says.
@@ -480,6 +521,8 @@ export class FreeRoomRunner {
480
521
  this.not_started = new Set();
481
522
  // Executions whose software failed in a way a retry meets again (a used-up limit, a lost login), as its adapter reported.
482
523
  this.not_retryable = new Set();
524
+ // Executions whose turn an adapter that cannot stop it saw end (`on_turn_end`); only a voided one's stop report reads it.
525
+ this.turn_ended = new Set();
483
526
  this.failure_classes = new Map();
484
527
  this.snapshots = new Map();
485
528
  // Execution id -> { phase, at, sent_phase, sent_at }: what the member's software last showed it doing.
@@ -1031,12 +1074,12 @@ export class FreeRoomRunner {
1031
1074
  const live = () => this.live_id(execution.id);
1032
1075
  const current = () => this.generations.get(live()) === generation;
1033
1076
  const binding = this.store.binding(member.name);
1034
- // A member whose session a rewind restarted is bound to '' and must not fall back to the session it was invited with.
1035
- if (binding.session_id === undefined && adapter.session_id) binding.session_id = adapter.session_id;
1036
1077
  let invoked = false;
1037
1078
  // Remarks before the software shows any work (an adapter's own "not started yet") are never its reply.
1038
1079
  let worked = false;
1039
1080
  try {
1081
+ // A member whose session a rewind restarted is bound to '' and must not fall back to the session it was invited with.
1082
+ await this.bind_invited(member.name, adapter, binding);
1040
1083
  // A resumed execution's session was already cut at its first delivery.
1041
1084
  const warning = resume ? '' : await this.cut_rewound(member.name, adapter, binding, execution);
1042
1085
  const session_request = execution.requests?.find(item => item.session_request_id && ['discuss', 'discuss_host'].includes(item.purpose));
@@ -1055,10 +1098,11 @@ export class FreeRoomRunner {
1055
1098
  if (workflow?.error && this.workflow_error !== workflow.error) this.log(`工作流 ${workflow.id} 不可用:${workflow.error}`);
1056
1099
  this.workflow_error = workflow?.error || '';
1057
1100
  const attachments = await request_attachments(this.config, execution, member_runtime(this.config, member.name));
1101
+ const request_texts = member.role === 'host' ? await user_request_texts(this.config, execution) : [];
1058
1102
  const model_change = this.model_change(member.name);
1059
1103
  const task = free_task_files(this.config, member, execution, binding, {
1060
1104
  session, suggestions: scheduler_suggestions, reviews: review_handoffs, stopped, workflow, room_members: this.room?.members,
1061
- goal: this.room?.goal_state?.goal || null, attachments, room: this.room, model_change,
1105
+ goal: this.room?.goal_state?.goal || null, attachments, room: this.room, model_change, request_texts,
1062
1106
  });
1063
1107
  this.store.db.prepare('DELETE FROM metadata WHERE key IN (?,?)').run(`recovery:${execution.id}`, `recovery-denied:${execution.id}`);
1064
1108
  invoked = true;
@@ -1106,6 +1150,8 @@ export class FreeRoomRunner {
1106
1150
  ...(Number.isSafeInteger(reset_at) && reset_at > 0 ? { reset_at } : {}) });
1107
1151
  try { if (this.row(member.name)?.execution_id === live()) this.save(member.name, { error }); } catch { /* Store may already be closed at shutdown. */ }
1108
1152
  },
1153
+ // The turn was seen to end in a window or App the runner cannot stop; unlike on_exit it says nothing about an answer.
1154
+ on_turn_end: () => { if (current()) this.turn_ended.add(live()); },
1109
1155
  on_exit: denial => {
1110
1156
  if (!current()) return;
1111
1157
  this.exited.set(live(), denial || '');
@@ -1173,20 +1219,40 @@ export class FreeRoomRunner {
1173
1219
  * session could not be cut and the member continues in the old one.
1174
1220
  */
1175
1221
  async cut_rewound(name, adapter, binding, execution) {
1176
- const key = `session-fork:${name}`;
1177
- const pending = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
1178
- if (pending && !session_exists(adapter.adapter, binding.session_id)) { binding.fork = JSON.parse(pending); return ''; }
1179
- if (pending) this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1222
+ if (this.pending_fork(name, adapter, binding)) return '';
1180
1223
  if (!binding.session_id || !execution.rewound_executions?.length || !BRANCHABLE_ADAPTERS.includes(adapter.adapter)) return '';
1181
1224
  try {
1182
1225
  const cut = await branch_session(adapter, binding.session_id, execution.rewound_executions);
1183
1226
  if (!cut) return '';
1184
- if (cut.fork) this.store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, JSON.stringify(cut.fork));
1185
- this.store.bind(name, cut.session_id);
1186
- Object.assign(binding, cut);
1227
+ this.rebind(name, binding, cut);
1187
1228
  return '';
1188
1229
  } catch (error) { return `会话未能回退(${error.message}),本次沿用原会话,它可能仍记得已回退的内容`; }
1189
1230
  }
1231
+ /** Ask a fork that has not happened yet (a Claude fork happens on its next turn) again; true while it is pending. */
1232
+ pending_fork(name, adapter, binding) {
1233
+ const key = `session-fork:${name}`;
1234
+ const pending = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
1235
+ if (pending && !session_exists(adapter.adapter, binding.session_id)) { binding.fork = JSON.parse(pending); return true; }
1236
+ if (pending) this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1237
+ return false;
1238
+ }
1239
+ /** Bind a member to a branch of its session, keeping a fork its software makes on the next turn pending. */
1240
+ rebind(name, binding, branch) {
1241
+ if (branch.fork) this.store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(`session-fork:${name}`, JSON.stringify(branch.fork));
1242
+ this.store.bind(name, branch.session_id);
1243
+ Object.assign(binding, branch);
1244
+ }
1245
+ /**
1246
+ * A member not yet bound starts in the conversation it was invited with. Where the adapter declares `copy_bound`, its
1247
+ * first turn works in a copy of that conversation instead, so the original, possibly still open in a window, is never
1248
+ * written; a taken-over manual member (`own`) keeps its original.
1249
+ */
1250
+ async bind_invited(name, adapter, binding) {
1251
+ if (binding.session_id !== undefined || !adapter.session_id) return;
1252
+ if (adapter.project_access === 'own' || !adapter_of(adapter.adapter)?.copy_bound) { binding.session_id = adapter.session_id; return; }
1253
+ try { this.rebind(name, binding, await branch_session(adapter, adapter.session_id, [], { always: true })); }
1254
+ catch (error) { throw Object.assign(new Error(`未能复制历史会话:${error.message}`), { delivery_status: 'not_sent' }); }
1255
+ }
1190
1256
  /**
1191
1257
  * After an execution completed normally, its software may run on for the close window its adapter declares, so the
1192
1258
  * receipt of the answer it just submitted is recorded in its own session before it is stopped (spec #3262 item 8:
@@ -1286,7 +1352,7 @@ export class FreeRoomRunner {
1286
1352
  for (const map of [this.generations, this.steers, this.activity, this.replies, this.exited, this.execution_processes]) {
1287
1353
  if (map.has(old)) { map.set(id, map.get(old)); map.delete(old); }
1288
1354
  }
1289
- for (const set of [this.denied, this.not_started, this.not_retryable]) if (set.delete(old)) set.add(id);
1355
+ for (const set of [this.denied, this.not_started, this.not_retryable, this.turn_ended]) if (set.delete(old)) set.add(id);
1290
1356
  if (this.failure_classes.has(old)) { this.failure_classes.set(id, this.failure_classes.get(old)); this.failure_classes.delete(old); }
1291
1357
  const snapshot = this.snapshots.get(old);
1292
1358
  const moved_before = snapshot?.before ? workspace_snapshot(snapshot.directory) : null;
@@ -1336,8 +1402,9 @@ export class FreeRoomRunner {
1336
1402
  * progress. Kept locally until the execution ends so a restarted runner still knows whether it could stop it.
1337
1403
  * A lost report is retained for the final stop result; sites and runners must use the same capability protocol.
1338
1404
  */
1339
- async report_delivery(execution_id, { stoppable, progress, steer = false, resume = false }, member) {
1340
- this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`delivery:${execution_id}`, JSON.stringify({ stoppable, progress, member }));
1405
+ async report_delivery(execution_id, { stoppable, progress, ends = false, steer = false, resume = false }, member) {
1406
+ // `ends`: the adapter cannot stop or follow this turn but reports when it ends (`on_turn_end`); kept locally only.
1407
+ this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`delivery:${execution_id}`, JSON.stringify({ stoppable, progress, ends, member }));
1341
1408
  await api(this.config, `/executions/${execution_id}`, { action: 'delivery', stoppable, progress, steer, resume })
1342
1409
  .catch(error => this.log(`执行 #${execution_id} 的投递能力未能上报:${error.message}`));
1343
1410
  }
@@ -1363,9 +1430,17 @@ export class FreeRoomRunner {
1363
1430
  if (!value) return;
1364
1431
  const delivery = stored_delivery(value), processes = this.execution_processes.get(execution_id);
1365
1432
  const ended = processes ? processes.size === 0 : this.exited.has(execution_id) || this.orphan(execution_id)?.alive === false;
1366
- const result = delivery.pending_result && delivery.pending_result !== 'unconfirmed' ? delivery.pending_result
1367
- : !delivery.stoppable ? 'unstoppable' : ended ? 'stopped' : 'unconfirmed';
1368
- if (delivery.stop_result === result) return;
1433
+ // A turn this runner could not stop but follows (`progress`) or hears end (`ends`) is still watched: once it ends, in
1434
+ // its window or App by the owner or on its own, `stopped` lifts the site's hold on the next delivery.
1435
+ const followed = Boolean(delivery.progress || delivery.ends);
1436
+ const seen_end = ended || this.turn_ended.has(execution_id);
1437
+ const result = delivery.pending_result && !['unconfirmed', 'unstoppable'].includes(delivery.pending_result) ? delivery.pending_result
1438
+ : !delivery.stoppable ? (followed && seen_end ? 'stopped' : 'unstoppable') : ended ? 'stopped' : 'unconfirmed';
1439
+ if (delivery.stop_result === result) {
1440
+ // Past the site's hold (HOLD_SECONDS in backend/free_room.py) an unstoppable turn's end changes nothing.
1441
+ if (result === 'unstoppable' && Date.now() - (delivery.reported_at || 0) > UNSTOPPABLE_FOLLOW_MS) this.forget_stop(execution_id);
1442
+ return;
1443
+ }
1369
1444
  // An execution that left the inbox by finishing normally has no stop to report; only a voided one does.
1370
1445
  if (['completed', 'failed'].includes((await api(this.config, `/executions/${execution_id}`)).status)) {
1371
1446
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
@@ -1387,13 +1462,20 @@ export class FreeRoomRunner {
1387
1462
  }
1388
1463
  this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)')
1389
1464
  .run(`stopped:${name}`, JSON.stringify([...new Set([...this.stopped_executions(name), execution_id])]));
1390
- if (result === 'unconfirmed') {
1465
+ if (result === 'unconfirmed' || (result === 'unstoppable' && followed)) {
1391
1466
  this.store.db.prepare('UPDATE metadata SET value=? WHERE key=?')
1392
- .run(JSON.stringify({ ...delivery, member: name, pending_result: result, stop_result: result }), key);
1467
+ .run(JSON.stringify({ ...delivery, member: name, pending_result: result, stop_result: result, reported_at: Date.now() }), key);
1393
1468
  // The site's bounded hold now controls the next delivery; retain handles to observe and retry termination.
1394
1469
  for (const child of processes || []) this.members.get(name)?.delete(child);
1395
1470
  }
1396
- else { this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key); this.execution_processes.delete(execution_id); this.forget_owner(execution_id); }
1471
+ else this.forget_stop(execution_id);
1472
+ }
1473
+ /** Drop what this runner keeps for one voided execution's stop report. */
1474
+ forget_stop(execution_id) {
1475
+ this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`delivery:${execution_id}`);
1476
+ this.execution_processes.delete(execution_id);
1477
+ this.turn_ended.delete(execution_id);
1478
+ this.forget_owner(execution_id);
1397
1479
  }
1398
1480
  /**
1399
1481
  * An execution whose handles an earlier runner process tracked and this one does not: `{alive}` says whether any of its
@@ -1672,6 +1754,8 @@ export class FreeRoomRunner {
1672
1754
  let settle;
1673
1755
  const ended = new Promise(resolve => { settle = resolve; });
1674
1756
  try {
1757
+ await this.bind_invited(member.name, profile, binding);
1758
+ this.pending_fork(member.name, profile, binding);
1675
1759
  const task = chat_task_files(this.config, member, chat, binding);
1676
1760
  // Software without its own session (the model API) takes the earlier lines as its context.
1677
1761
  const history = (await api(this.config, `/members/${member.id}/chat`).catch(() => ({ chats: [] }))).chats
@@ -0,0 +1,19 @@
1
+ /**
2
+ * How a workflow or sub-workflow is named with "/" in a room message, shared by the page that writes it (the input
3
+ * box's "/" menu) and the runner that reads it back for the host's task, so the two cannot drift apart.
4
+ * Pure JavaScript with no Node.js modules: the page imports it too.
5
+ */
6
+
7
+ // `/name` starting a word; a path such as a/b or /a/b names nothing.
8
+ const SLASH_NAME = /(?:^|[\s((,,。;;::])\/([A-Za-z0-9][\w:.-]*)(?![\w:/-])/gu;
9
+
10
+ /** What the "/" menu inserts for a workflow or sub-workflow ID, with a space for the text that follows. */
11
+ export function slash_insertion(id) {
12
+ return `/${id} `;
13
+ }
14
+
15
+ /** The names a message gives with "/", outside code and quotes, each once in order of appearance. */
16
+ export function slash_names(text) {
17
+ const prose = String(text || '').replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, '').replace(/^>.*$/gm, '');
18
+ return [...new Set([...prose.matchAll(SLASH_NAME)].map(match => match[1]))];
19
+ }