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
@@ -1,19 +1,19 @@
1
1
  /** Free-room delivery: one live execution per member, carrying all of that member's open requests. */
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
- import { basename, join, resolve } from 'node:path';
6
- import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, chosen_settings, cleanup_room, deliver_task, delivery_receipt, recover_turn, session_exists, session_settings, stored_delivery, takes_images } from './adapters/index.mjs';
7
- import { api as raw_api, overlapping_directories, read_rule } from './discussion_runner.mjs';
4
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
+ import { basename, dirname, join, posix, relative, resolve, win32 } from 'node:path';
6
+ import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, chosen_settings, cleanup_room, deliver_task, delivery_receipt, preflight_stoppable, recover_turn, session_exists, session_settings, stored_delivery, takes_images } from './adapters/index.mjs';
7
+ import { api as raw_api, overlapping_directories, read_rule, room_draft_key } from './discussion_runner.mjs';
8
8
  import { SegmentLog } from './execution_progress.mjs';
9
9
  import { capture_base, file_diffs } from './file_diff.mjs';
10
10
  import { correctable_refusals, free_task_text, MAX_REFUSAL_RETRIES, refusal_retry_prompt, restart_resume_prompt, TASK_SUBCOMMANDS, with_expert_prompt } from './expert_prompts.mjs';
11
11
  import { entry_access, site_fetch } from './entry_client.mjs';
12
12
  import { atomic_json } from './files.mjs';
13
13
  import { image_settings } from './image_service.mjs';
14
- import { outside_directory, room_directories } from './project_files.mjs';
14
+ import { outside_directory, room_directories, room_directory_entries } from './project_files.mjs';
15
15
  import { SessionDriver } from './session_driver.mjs';
16
- import { slash_names } from './slash_names.mjs';
16
+ import { parse_slash_workflow, slash_names } from './slash_names.mjs';
17
17
  import { effective_profile, load_room_workflow, member_knowledge, workflow_directory, workflow_execution_binding, workflow_in_use, workflow_task_field } from './workflows.mjs';
18
18
  import { GOAL_CONFIDENCE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, ROUTE_GUIDED_PROMPT_VERSION, ROUTE_WIDE_CONFIDENCE, SCHEDULER_MODE, decide_review_completion, route_free_message, some_members } from './scheduler.mjs';
19
19
  import { room_text, room_payload } from './room_text.mjs';
@@ -53,7 +53,7 @@ const RESTART_REASON = room_text("重启后无法确认上次执行结果");
53
53
  // Recognize older versions' pending restart retries so upgrading cannot redeliver them.
54
54
  const RESTART_REASON_CODE = 'runner_restarted';
55
55
  const MAX_RETRY_REASON = 500;
56
- const LIVE = ['reserving', 'delivering', 'sidecar_pending', 'running', 'retry_wait'];
56
+ const LIVE = ['reserving', 'delivering', 'sidecar_pending', 'running', 'retry_wait', 'storage_stopping'];
57
57
  // The longest private chat reply the site keeps.
58
58
  const CHAT_REPLY_LIMIT = 20000;
59
59
  const MAX_HASHED_BYTES = 5 * 1024 * 1024;
@@ -88,6 +88,38 @@ export function member_drafts(config, name) {
88
88
  return join(base, createHash('sha256').update(String(name)).digest('hex').slice(0, 16));
89
89
  }
90
90
 
91
+ /** Remove only the execution subdirectory, refusing redirected ancestors. */
92
+ function remove_scratch(config, { member, id }) {
93
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Invalid scratch execution id');
94
+ const directory = resolve(member_drafts(config, member), '.scratch', String(id));
95
+ try {
96
+ const root = config.draft_directory && resolve(config.draft_directory, '..', '..');
97
+ let expected = directory;
98
+ if (root && config.directory && !relative(join(root, 'drafts', room_draft_key(config.directory)), config.draft_directory)) {
99
+ expected = resolve(realpathSync.native(root), relative(root, directory));
100
+ for (let part = directory; relative(root, part); part = dirname(part)) {
101
+ if (lstatSync(part, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`Redirected scratch path: ${part}`);
102
+ }
103
+ }
104
+ if (relative(realpathSync.native(directory), expected)) throw new Error(`Redirected scratch path: ${directory}`);
105
+ rmSync(directory, { recursive: true });
106
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
107
+ }
108
+
109
+ /** Claim and retire the oldest confirmed failed scratch record under the same database lock as other cleaners. */
110
+ export function reclaim_failed_scratch(db, config, key = null) {
111
+ db.exec('BEGIN IMMEDIATE');
112
+ try {
113
+ const row = db.prepare("SELECT key,value FROM metadata WHERE key LIKE 'failed-scratch:%' AND (? IS NULL OR key=?) ORDER BY json_extract(value,'$.ended'),key LIMIT 1").get(key, key);
114
+ if (row) {
115
+ remove_scratch(config, JSON.parse(row.value));
116
+ db.prepare('DELETE FROM metadata WHERE key=?').run(row.key);
117
+ }
118
+ db.exec('COMMIT');
119
+ return Boolean(row);
120
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
121
+ }
122
+
91
123
  // The file name of a taken-over member's proactive credential inside its runtime folder; mirrored in runner/discuss.py.
92
124
  export const PROACTIVE_ACCESS_FILE = 'proactive.access.json';
93
125
 
@@ -125,14 +157,20 @@ export function cwd_key(directory) {
125
157
  */
126
158
  export function workspace_snapshot(directory) {
127
159
  if (!directory) return null;
128
- const result = spawnSync('git', ['-C', directory, 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
160
+ const options = { encoding: 'utf8', windowsHide: true, timeout: GIT_TIMEOUT_MS };
161
+ const prefix = spawnSync('git', ['-C', directory, 'rev-parse', '--show-prefix'], options);
162
+ if (prefix.status !== 0) return null;
163
+ const folder = prefix.stdout.replace(/[\r\n]+$/, '');
164
+ const result = spawnSync('git', ['-C', directory, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.'],
129
165
  { encoding: 'utf8', windowsHide: true, timeout: GIT_TIMEOUT_MS });
130
166
  if (result.status !== 0) return null;
131
167
  const entries = new Map();
132
168
  const fields = result.stdout.split('\0').filter(Boolean);
133
169
  for (let index = 0; index < fields.length; index++) {
134
- const status = fields[index].slice(0, 2), path = fields[index].slice(3);
170
+ const status = fields[index].slice(0, 2), name = fields[index].slice(3);
135
171
  if (status[0] === 'R' || status[0] === 'C') index++; // The original path of a rename follows.
172
+ if (!name.startsWith(folder)) continue;
173
+ const path = name.slice(folder.length);
136
174
  let content = 'missing';
137
175
  try {
138
176
  const file = join(directory, path);
@@ -152,16 +190,16 @@ export function changed_between(before, after) {
152
190
 
153
191
  /**
154
192
  * The changed paths (relative, as git lists them) that the agent edited with its own tools, given the paths those tools
155
- * named (absolute or relative to the working directory). Matched by path suffix, so a working directory below the
156
- * repository root still matches; Windows paths compare case-insensitively.
193
+ * named, resolved against the execution working directory.
157
194
  */
158
- export function edited_changes(changes, claimed, platform = process.platform) {
195
+ export function edited_changes(changes, claimed, directory, platform = process.platform) {
196
+ const paths = platform === 'win32' ? win32 : posix;
159
197
  const normal = path => {
160
- const text = `/${String(path).replaceAll('\\', '/').replace(/^\.\//, '')}`;
161
- return platform === 'win32' ? text.toLowerCase() : text;
198
+ const absolute = paths.resolve(directory, path);
199
+ return platform === 'win32' ? absolute.toLowerCase() : absolute;
162
200
  };
163
- const named = [...claimed].map(normal);
164
- return changes.filter(path => named.some(item => item.endsWith(normal(path))));
201
+ const named = new Set([...claimed].map(normal));
202
+ return changes.filter(path => named.has(normal(path)));
165
203
  }
166
204
 
167
205
  /**
@@ -174,11 +212,16 @@ export function member_extra_directories(config, profile) {
174
212
  // '' marks a member that joined before the room had a project: it reaches every room directory at its own access.
175
213
  const cwd = profile.cwd ?? config.cwd;
176
214
  const access = outside_directory(config, profile) || profile.project_access === 'read' ? 'read' : 'write';
177
- return room_directories(config).filter(path => !(cwd && overlapping_directories(path, cwd)) && existsSync(path))
178
- .map(path => ({ path, access }));
215
+ return room_directory_entries(config).filter(({ path }) => !(cwd && overlapping_directories(path, cwd)) && existsSync(path))
216
+ .map(item => ({ path: item.path, access: item.access === 'read' ? 'read' : access }));
179
217
  }
180
218
 
181
219
  /** A changed path in an extra directory, reported in full so it cannot be mistaken for one in the main directory. */
220
+ function extra_snapshot(directory) {
221
+ const before = workspace_snapshot(directory);
222
+ return { directory, before, base: capture_base(directory, before) };
223
+ }
224
+
182
225
  function extra_change(directory, path) {
183
226
  return `${cwd_key(directory)}/${path}`;
184
227
  }
@@ -197,7 +240,12 @@ export async function user_request_texts(config, execution) {
197
240
  for (const message_id of message_ids) {
198
241
  try {
199
242
  const message = await api(config, `/messages/${message_id}`);
200
- if (message.author === '用户' && message.text) texts.push(message.text);
243
+ if (message.relay_room) {
244
+ for (const request of execution.requests.filter(item => item.message_id === message_id)) {
245
+ request.relay = { from_room: message.relay_room, title: message.relay_title, host: message.relay_host,
246
+ relation: message.relay_relation, note: '来自关联房间主持人的跨房消息,不代表用户本人新授权' };
247
+ }
248
+ } else if (message.author === '用户' && message.text) texts.push(message.text);
201
249
  } catch { /* The host still reads the message itself. */ }
202
250
  }
203
251
  return texts;
@@ -210,18 +258,37 @@ export async function user_request_texts(config, execution) {
210
258
  */
211
259
  export function named_workflows(texts, { sub_workflows = [], current = '', in_library = () => false } = {}) {
212
260
  const named = { workflows: [], sub_workflows: [] };
213
- for (const name of new Set(texts.flatMap(slash_names))) {
214
- if (sub_workflows.includes(name)) named.sub_workflows.push(name);
215
- else if (name !== current && in_library(name)) named.workflows.push(name);
261
+ const binding = typeof current === 'string' ? { id: current } : current;
262
+ for (const token of new Set(texts.flatMap(slash_names))) {
263
+ const target = parse_slash_workflow(token);
264
+ if (!target.scope && sub_workflows.includes(target.id)) {
265
+ named.sub_workflows.push(target.id);
266
+ continue;
267
+ }
268
+ const found = in_library(target.id, target);
269
+ if (!found) continue;
270
+ const selected = typeof found === 'object' ? found : target;
271
+ if (binding?.id === selected.id && (!selected.scope || ((binding.scope || 'global') === selected.scope
272
+ && (binding.project_id || '') === (selected.project_id || '')))) continue;
273
+ if (!named.workflows.includes(target.id)) named.workflows.push(target.id);
274
+ if (target.scope) (named.workflow_targets ||= []).push({ id: target.id, scope: target.scope,
275
+ ...(target.project_id ? { project_id: target.project_id } : {}) });
216
276
  }
217
277
  const kept = Object.fromEntries(Object.entries(named).filter(([, names]) => names.length));
218
278
  return Object.keys(kept).length ? kept : null;
219
279
  }
220
280
 
221
281
  /** Whether this computer's workflow library has a workflow with this ID. */
222
- function library_has(config, id) {
223
- try { return Boolean(config.api_home) && existsSync(join(workflow_directory(config.api_home, id), 'SKILL.md')); }
224
- catch { return false; }
282
+ function library_has(config, id, target) {
283
+ try {
284
+ if (target.scope !== 'global') for (const path of room_directories(config)) {
285
+ const project_id = createHash('sha256').update(resolve(path).toLowerCase()).digest('hex').slice(0, 16);
286
+ if (target.project_id && target.project_id !== project_id) continue;
287
+ if (existsSync(join(workflow_directory(join(path, '.codiscuss'), id), 'SKILL.md'))) return { id, scope: 'project', project_id };
288
+ }
289
+ if (target.scope !== 'project' && config.api_home && existsSync(join(workflow_directory(config.api_home, id), 'SKILL.md'))) return { id, scope: 'global' };
290
+ } catch { /* Invalid workflow name. */ }
291
+ return false;
225
292
  }
226
293
 
227
294
  /**
@@ -284,11 +351,27 @@ export function room_goal(room) {
284
351
  note: '这是整个房间的任务;一次 Goal 或讨论结束不等于它完成。Goal 完成后对照这里判断还剩什么,没有目标文字时读首条用户消息。' };
285
352
  }
286
353
 
354
+ async function linked_room_summaries(config) {
355
+ const describe = async room_id => {
356
+ try {
357
+ const room = await api({ ...config, room: room_id }, '');
358
+ return { room_id, title: room.title, latest_id: room.latest_id,
359
+ running: (room.free?.members || []).some(member => ['started', 'dispatched'].includes(member.execution?.status)) };
360
+ } catch { return { room_id }; }
361
+ };
362
+ const [parent, children] = await Promise.all([
363
+ config.spawned_from ? describe(config.spawned_from) : null,
364
+ Promise.all((config.spawned_rooms || []).map(item => describe(item.room))),
365
+ ]);
366
+ return { parent, children };
367
+ }
368
+
287
369
  export function free_task_files(config, member, execution, binding, { session = null, suggestions = [], reviews = [], stopped = [], process_access = true,
288
- workflow = null, room_members = [], goal = null, attachments = [], room = null, model_change = null, request_texts = [] } = {}) {
370
+ workflow = null, room_members = [], goal = null, attachments = [], room = null, model_change = null, request_texts = [], linked_rooms = null } = {}) {
289
371
  const id = `free-${execution.id}`;
290
372
  const draft_directory = member_drafts(config, member.name);
291
- mkdirSync(draft_directory, { recursive: true });
373
+ const scratch_directory = join(draft_directory, '.scratch', String(execution.id));
374
+ const scratch_created = mkdirSync(scratch_directory, { recursive: true }) !== undefined;
292
375
  const member_directory = member_runtime(config, member.name);
293
376
  const access_path = join(member_directory, `${id}.access.json`);
294
377
  const task_path = join(member_directory, `${id}.task.json`);
@@ -301,7 +384,9 @@ export function free_task_files(config, member, execution, binding, { session =
301
384
  const adapter = adapter_of(profile.adapter);
302
385
  const extra_directories = member_extra_directories(config, profile);
303
386
  // The expert this member plays keeps its own knowledge, which only it may write (its project access stays as set).
304
- const knowledge_directory = member_knowledge(config.api_home, member.name, workflow);
387
+ const knowledge_directory = member_knowledge(config.api_home, member.name, workflow, room_directories(config), profile);
388
+ const readonly_knowledge = knowledge_directory && (config.extra_directories || []).some(item =>
389
+ item.access === 'read' && overlapping_directories(item.path, knowledge_directory));
305
390
  const cli = process.platform === 'win32' ? adapter?.windows_command || 'codiscuss.cmd' : 'codiscuss';
306
391
  const inbox = Boolean(adapter?.into_window?.(profile, binding));
307
392
  const bound_access = process_access && !inbox && Boolean(adapter?.capabilities.access_env);
@@ -313,7 +398,7 @@ export function free_task_files(config, member, execution, binding, { session =
313
398
  discussion_request, profile, cli,
314
399
  room: config.room, messages, read_after: execution.read_until, execution_id: execution.id, task_path,
315
400
  access_file: bound_access ? '' : access_path, read_rule: read_rule(profile.adapter), inbox, extra_directories, attachments, requests, workflow: Boolean(host_workflow),
316
- knowledge: Boolean(knowledge_directory) });
401
+ knowledge: Boolean(knowledge_directory && !readonly_knowledge) });
317
402
  // Software that declares it takes images gets them with the prompt, like a screenshot pasted into its own window.
318
403
  const images = takes_images(profile) && !inbox
319
404
  ? attachments.filter(item => item.path && IMAGE_TYPES.has(item.content_type)).map(item => ({ path: item.path, content_type: item.content_type, size: item.size }))
@@ -353,20 +438,20 @@ export function free_task_files(config, member, execution, binding, { session =
353
438
  // Relay, question and image rules are read only when the task carries them, keeping the everyday path short.
354
439
  if (image || requests.some(item => item.sequence || item.question || item.question_needed)) skills.push('discuss-participant/references/situations.md');
355
440
  const named = member.role === 'host' ? named_workflows(request_texts, { sub_workflows: host_workflow?.sub_workflows.map(sub => sub.id) || [],
356
- current: host_workflow?.id || '', in_library: id => library_has(config, id) }) : null;
441
+ current: host_workflow ? config.workflow : '', in_library: (id, target) => library_has(config, id, target) }) : null;
357
442
  // The host's occasional pages likewise: relays and question cards, room control on a notice, the workflow (also when
358
443
  // the user named one to enable), pre-set reviews.
359
444
  if (member.role === 'host') {
360
445
  if (requests.some(item => item.sequence || item.question?.task || item.question_needed)) skills.push('discuss-host/references/relay.md');
361
446
  // A notice, or a hand-back where someone failed or was cancelled, is what calls for diagnosing and recovering.
362
- if (requests.some(item => item.purpose === 'notice' || (item.outcome || []).some(entry => ['failed', 'cancelled'].includes(entry.status)))) {
447
+ if (linked_rooms || requests.some(item => item.purpose === 'notice' || (item.outcome || []).some(entry => ['failed', 'cancelled'].includes(entry.status)))) {
363
448
  skills.push('discuss-host/references/control.md');
364
449
  }
365
450
  if (workflow_field || named?.workflows) skills.push('discuss-host/references/workflow.md');
366
451
  if (reviews.length) skills.push('discuss-host/references/dev-flow.md');
367
452
  }
368
453
  atomic_json(task_path, { site: config.site, room: config.room, mode: 'free', member: member.name,
369
- execution_id: execution.id, requests, request_messages: execution.requests.map(item => item.message_id),
454
+ execution_id: execution.id, requests, ...(linked_rooms ? { linked_rooms } : {}), request_messages: execution.requests.map(item => item.message_id),
370
455
  ...(attachments.length ? { attachments } : {}),
371
456
  request_purposes: execution.requests.map(item => item.purpose || 'ask'),
372
457
  ...(discussion_request ? { discussion_request } : {}),
@@ -387,6 +472,7 @@ export function free_task_files(config, member, execution, binding, { session =
387
472
  // Only where the adapter declares capture: without it, only a submitted answer is saved, as the skill already says.
388
473
  ...(adapter?.capabilities.capture ? { answer_capture: '正常结束且本次没有提交时,你最后一段文字收为本次回答(标自动收录,不派活);已提交或被拒则不收录' } : {}),
389
474
  read_after: execution.read_until, cwd: profile.cwd || null, project_access: profile.project_access, draft_directory,
475
+ scratch_directory,
390
476
  ...(knowledge_directory ? { knowledge_directory } : {}),
391
477
  ...(extra_directories.length ? { extra_directories } : {}),
392
478
  skills: skills.map(file => join(config.project, '.agents/skills', file)),
@@ -397,12 +483,12 @@ export function free_task_files(config, member, execution, binding, { session =
397
483
  ...(image ? { image: { model: image.model, command: `${cli} launch image --file REQUEST.json` } } : {}),
398
484
  cli, subcommands: TASK_SUBCOMMANDS,
399
485
  ...(bound_access ? { access_env: 'DISCUSS_ACCESS_FILE' } : { access_file: access_path }), instructions });
400
- return { id, participant: member.name, directory: config.directory, member_directory, task_path, draft_directory, extra_directories,
401
- ...(knowledge_directory ? { knowledge_directory } : {}), ...(goal_field ? { goal: goal_field } : {}),
486
+ return { id, participant: member.name, directory: config.directory, member_directory, task_path, draft_directory, scratch_directory, scratch_created, extra_directories,
487
+ ...(knowledge_directory && !readonly_knowledge ? { knowledge_directory } : {}), ...(goal_field ? { goal: goal_field } : {}),
402
488
  ...(goal_of_room ? { room_goal: goal_of_room } : {}),
403
489
  // Every member may read the folder of the room's workflow (templates, tools, a review of the workflow itself), also
404
490
  // while its members are away and the host no longer follows it; only the host's task names it.
405
- skill_directories: [skills_directory, ...(workflow && !workflow.error ? [workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox, images,
491
+ skill_directories: [skills_directory, ...(readonly_knowledge ? [knowledge_directory] : []), ...(workflow && !workflow.error ? [workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox, images,
406
492
  profile, ...(workflow_field ? { workflow: { ...workflow_field, skill: host_workflow.skill, ...api_sub_workflows(workflow_field, host_workflow) } } : {}) };
407
493
  }
408
494
 
@@ -491,6 +577,8 @@ function route_host_label(decision, host, members) {
491
577
  export class FreeRoomRunner {
492
578
  constructor(config, store, deliver = deliver_task, log = () => {}, fetch_impl = fetch, session_driver = null) {
493
579
  this.config = config;
580
+ this.storage_reports = new Map();
581
+ this.storage_reason = null; // Managed rooms share the service's asynchronous storage check.
494
582
  this.store = store;
495
583
  this.deliver = deliver;
496
584
  this.log = log;
@@ -917,7 +1005,7 @@ export class FreeRoomRunner {
917
1005
  // Manual members are listed apart; they are never delivered to but may host or be recommended.
918
1006
  const everyone = [...inbox.members, ...(inbox.observers || [])];
919
1007
  const host = everyone.find(member => member.role === 'host');
920
- const waiting = host?.pending.filter(request => request.purpose === 'route' && !request.group_action
1008
+ const waiting = host?.pending.filter(request => request.purpose === 'route' && !request.relay_room && !request.group_action
921
1009
  && !this.routed.has(request.id) && !this.saved_suggestion(request.id)) || [];
922
1010
  for (const request of waiting) {
923
1011
  this.routed.add(request.id);
@@ -1076,13 +1164,20 @@ export class FreeRoomRunner {
1076
1164
  catch (error) { return this.reject_review(member, execution, error.message); }
1077
1165
  }
1078
1166
  if (!adapter) return this.fail(member.name, execution.id, room_text("未配置 {value1} 的本机接入", { value1: member.name }));
1167
+ let reason;
1168
+ try {
1169
+ const stoppable = preflight_stoppable(adapter, this.store.binding(member.name));
1170
+ reason = await this.storage_reason?.(stoppable);
1171
+ }
1172
+ catch (error) { reason = error.message; }
1173
+ if (reason) return this.fail(member.name, execution.id, reason);
1079
1174
  if (this.context_errors.has(member.name)) return this.fail(member.name, execution.id, this.context_errors.get(member.name));
1080
1175
  const directory = capabilities_of(adapter.adapter).project ? adapter.cwd ?? this.config.cwd : undefined;
1081
1176
  // A read-only member's software cannot write the project, so files changing meanwhile were written by someone else.
1082
1177
  const before = adapter.project_access === 'read' ? null : workspace_snapshot(directory);
1083
1178
  // The room's other directories this member may write are watched as well; their changes are reported with full paths.
1084
1179
  const extras = member_extra_directories(this.config, adapter).filter(item => item.access === 'write')
1085
- .map(item => ({ directory: item.path, before: workspace_snapshot(item.path) })).filter(item => item.before);
1180
+ .map(item => extra_snapshot(item.path)).filter(item => item.before);
1086
1181
  // A resumed execution keeps the snapshot of its first delivery, so changes made before the pause are reported too.
1087
1182
  // One with nothing to watch (read-only, no git) is still tracked, so its end reports an empty list and the page stops
1088
1183
  // waiting for one (user 2026-11-20, #5956).
@@ -1122,11 +1217,15 @@ export class FreeRoomRunner {
1122
1217
  const attachments = await request_attachments(this.config, execution, member_runtime(this.config, member.name));
1123
1218
  const request_texts = member.role === 'host' ? await user_request_texts(this.config, execution) : [];
1124
1219
  const model_change = this.model_change(member.name);
1220
+ const linked_rooms = member.role === 'host' && (this.config.spawned_from || this.config.spawned_rooms?.length)
1221
+ ? await linked_room_summaries(this.config) : null;
1125
1222
  const task = free_task_files(this.config, member, execution, binding, {
1126
1223
  session, suggestions: scheduler_suggestions, reviews: review_handoffs, stopped, workflow, room_members: this.room?.members,
1127
- goal: this.room?.goal_state?.goal || null, attachments, room: this.room, model_change, request_texts,
1224
+ goal: this.room?.goal_state?.goal || null, attachments, room: this.room, model_change, request_texts, linked_rooms,
1128
1225
  });
1129
1226
  this.store.db.prepare('DELETE FROM metadata WHERE key IN (?,?)').run(`recovery:${execution.id}`, `recovery-denied:${execution.id}`);
1227
+ if (task.scratch_created) this.store.db.prepare('INSERT OR IGNORE INTO metadata VALUES (?,?)')
1228
+ .run(`scratch:${execution.id}`, JSON.stringify({ member: member.name, id: execution.id }));
1130
1229
  invoked = true;
1131
1230
  this.segments.start(execution.id);
1132
1231
  this.record_diagnostics(execution.id, { workflow: workflow_execution_binding(workflow, member, Boolean(task.workflow)) });
@@ -1345,6 +1444,7 @@ export class FreeRoomRunner {
1345
1444
  this.stop_member(member.name);
1346
1445
  return this.save(member.name, { status: 'idle', error: '' });
1347
1446
  }
1447
+ if (row.status === 'storage_stopping') return this.report_storage_stop(row);
1348
1448
  if (row.status === 'retry_wait') {
1349
1449
  const reason_code = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`retry-reason:${execution.id}`)?.value;
1350
1450
  if (reason_code === RESTART_REASON_CODE) return this.recover_orphan(member, row, execution);
@@ -1443,7 +1543,7 @@ export class FreeRoomRunner {
1443
1543
  const moved_before = snapshot?.before ? workspace_snapshot(snapshot.directory) : null;
1444
1544
  if (snapshot) this.snapshots.set(id, { member: snapshot.member, directory: snapshot.directory,
1445
1545
  before: moved_before, base: capture_base(snapshot.directory, moved_before),
1446
- extras: (snapshot.extras || []).map(item => ({ directory: item.directory, before: workspace_snapshot(item.directory) })),
1546
+ extras: (snapshot.extras || []).map(item => extra_snapshot(item.directory)),
1447
1547
  ...(snapshot.edited ? { edited: new Set() } : {}) });
1448
1548
  for (const prefix of ['owner', 'delivery']) {
1449
1549
  const value = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`${prefix}:${old}`)?.value;
@@ -1451,11 +1551,12 @@ export class FreeRoomRunner {
1451
1551
  this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`${prefix}:${id}`, value);
1452
1552
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`${prefix}:${old}`);
1453
1553
  }
1554
+ this.store.db.prepare('UPDATE metadata SET key=? WHERE key=?').run(`scratch:${id}`, `scratch:${old}`);
1454
1555
  const workflow = this.diagnostics.get(old)?.workflow;
1455
1556
  await this.report_segments(old, true);
1456
1557
  if (workflow) this.record_diagnostics(id, { workflow });
1457
1558
  this.segments.start(id);
1458
- this.save(name, { execution_id: id, last_renew: 0 });
1559
+ this.save(name, { execution_id: id, last_renew: 0, ...(this.row(name)?.status === 'storage_stopping' ? { status: 'running', error: '' } : {}) });
1459
1560
  }
1460
1561
  /**
1461
1562
  * An execution the owner paused from the private chat, or that takes an interjection only by a pause: stop its
@@ -1493,6 +1594,8 @@ export class FreeRoomRunner {
1493
1594
  async report_delivery(execution_id, { stoppable, progress, ends = false, steer = false, resume = false }, member) {
1494
1595
  // `ends`: the adapter cannot stop or follow this turn but reports when it ends (`on_turn_end`); kept locally only.
1495
1596
  this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`delivery:${execution_id}`, JSON.stringify({ stoppable, progress, ends, member }));
1597
+ this.store.db.prepare("UPDATE metadata SET value=json_set(value,'$.stoppable',?) WHERE key=?")
1598
+ .run(stoppable ? 1 : 0, `scratch:${execution_id}`);
1496
1599
  await api(this.config, `/executions/${execution_id}`, { action: 'delivery', stoppable, progress, steer, resume,
1497
1600
  diagnostics: this.diagnostics.get(execution_id) })
1498
1601
  .catch(error => this.log(`执行 #${execution_id} 的投递能力未能上报:${error.message}`));
@@ -1531,6 +1634,9 @@ export class FreeRoomRunner {
1531
1634
  const seen_end = ended || this.turn_ended.has(execution_id);
1532
1635
  const result = delivery.pending_result && !['unconfirmed', 'unstoppable'].includes(delivery.pending_result) ? delivery.pending_result
1533
1636
  : !delivery.stoppable ? (followed && seen_end ? 'stopped' : 'unstoppable') : ended ? 'stopped' : 'unconfirmed';
1637
+ if (this.turn_ended.has(execution_id) || this.exited.has(execution_id) || (delivery.stoppable && ended)) {
1638
+ this.store.db.prepare("UPDATE metadata SET value=json_set(value,'$.closed',1) WHERE key=?").run(`scratch:${execution_id}`);
1639
+ }
1534
1640
  if (delivery.stop_result === result) {
1535
1641
  // Past the site's hold (HOLD_SECONDS in backend/free_room.py) an unstoppable turn's end changes nothing.
1536
1642
  if (result === 'unstoppable' && Date.now() - (delivery.reported_at || 0) > UNSTOPPABLE_FOLLOW_MS) this.forget_stop(execution_id);
@@ -1539,7 +1645,8 @@ export class FreeRoomRunner {
1539
1645
  // An execution that left the inbox by finishing normally has no stop to report; only a voided one does.
1540
1646
  if (['completed', 'failed'].includes((await api(this.config, `/executions/${execution_id}`)).status)) {
1541
1647
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1542
- this.execution_processes.delete(execution_id);
1648
+ this.release_process_tracking(execution_id);
1649
+ this.forget_owner(execution_id);
1543
1650
  return;
1544
1651
  }
1545
1652
  // Keep the observed outcome before sending: a restart after a lost response must retry the same fact.
@@ -1552,7 +1659,8 @@ export class FreeRoomRunner {
1552
1659
  // A conflict is not necessarily normal completion: keep cancelled reports until an idempotent receipt arrives.
1553
1660
  if (!['completed', 'failed'].includes(latest.status)) throw error;
1554
1661
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1555
- this.execution_processes.delete(execution_id);
1662
+ this.release_process_tracking(execution_id);
1663
+ this.forget_owner(execution_id);
1556
1664
  return;
1557
1665
  }
1558
1666
  this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)')
@@ -1568,7 +1676,7 @@ export class FreeRoomRunner {
1568
1676
  /** Drop what this runner keeps for one voided execution's stop report. */
1569
1677
  forget_stop(execution_id) {
1570
1678
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`delivery:${execution_id}`);
1571
- this.execution_processes.delete(execution_id);
1679
+ this.release_process_tracking(execution_id);
1572
1680
  this.turn_ended.delete(execution_id);
1573
1681
  this.forget_owner(execution_id);
1574
1682
  }
@@ -1590,9 +1698,16 @@ export class FreeRoomRunner {
1590
1698
  if (Number.isInteger(pid) && !pids.includes(pid)) pids.push(pid);
1591
1699
  this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify({ instance: this.instance, pids }));
1592
1700
  }
1701
+ /** Retain process handles while scratch still needs a close observation. */
1702
+ release_process_tracking(id) {
1703
+ if (!this.store.db.prepare('SELECT 1 FROM metadata WHERE key=?').get(`scratch:${id}`)) this.execution_processes.delete(id);
1704
+ }
1705
+
1593
1706
  /** Drop the records an ended execution leaves: its process owners and whether a restart already resumed it. */
1594
1707
  forget_owner(execution_id) {
1595
- this.store.db.prepare('DELETE FROM metadata WHERE key IN (?,?,?)').run(`owner:${execution_id}`, `restart-resumed:${execution_id}`, `retry-reason:${execution_id}`);
1708
+ this.store.db.prepare('DELETE FROM metadata WHERE key IN (?,?)').run(`restart-resumed:${execution_id}`, `retry-reason:${execution_id}`);
1709
+ this.store.db.prepare('DELETE FROM metadata WHERE key=? AND NOT EXISTS (SELECT 1 FROM metadata WHERE key=?)')
1710
+ .run(`owner:${execution_id}`, `scratch:${execution_id}`);
1596
1711
  }
1597
1712
  /** Once a new task received the stop reminders, retire acknowledged unconfirmed reports for its old turns. */
1598
1713
  clear_stopped(name) {
@@ -1600,7 +1715,7 @@ export class FreeRoomRunner {
1600
1715
  const key = `delivery:${id}`, value = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
1601
1716
  if (value && stored_delivery(value).stop_result === 'unconfirmed') {
1602
1717
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1603
- this.execution_processes.delete(id);
1718
+ this.release_process_tracking(id);
1604
1719
  }
1605
1720
  }
1606
1721
  this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`stopped:${name}`);
@@ -1679,6 +1794,7 @@ export class FreeRoomRunner {
1679
1794
  * card to list without the wait (user 2026-11-19, #5669); the report after its processes have exited replaces it.
1680
1795
  */
1681
1796
  async report_finished(active) {
1797
+ await this.finish_scratch(active);
1682
1798
  for (const [execution_id, snapshot] of this.snapshots) {
1683
1799
  if (active.has(execution_id)) continue;
1684
1800
  const running = this.execution_processes.get(execution_id)?.size > 0;
@@ -1699,15 +1815,24 @@ export class FreeRoomRunner {
1699
1815
  });
1700
1816
  if (!workspace_observed) continue;
1701
1817
  const own = after ? changed_between(snapshot.before, after) : [];
1702
- const changes = [...own, ...extra].slice(0, 200);
1818
+ const observed = [...new Set([...own, ...extra])];
1819
+ const attributed = new Set(edited_changes(observed, snapshot.edited || [], snapshot.directory));
1820
+ const changes = [...attributed, ...observed.filter(path => !attributed.has(path))].slice(0, 200);
1703
1821
  // `edited` is sent only when the adapter tracked edits; without it the site cannot tell who wrote a shared file.
1704
- const edited = snapshot.edited ? { edited: edited_changes(changes, snapshot.edited) } : {};
1822
+ const edited = snapshot.edited ? { edited: changes.filter(path => attributed.has(path)) } : {};
1705
1823
  const diagnostics = { ...(this.diagnostics.get(execution_id) || snapshot.diagnostics),
1706
1824
  file_attribution: { tracked: Boolean(snapshot.edited), provisional: running,
1707
1825
  omitted: Math.max(0, own.length + extra.length - changes.length) } };
1708
1826
  // Line counts and patches of the files in the member's own working tree, for the card's "edited N files".
1709
1827
  let diffs = [];
1710
- if (own.length) try { diffs = file_diffs(snapshot.directory, own.slice(0, 200), snapshot.base); } catch { /* The card then lists names only. */ }
1828
+ const files = edited.edited || [];
1829
+ for (const tree of [snapshot, ...(snapshot.extras || [])]) {
1830
+ const prefix = tree === snapshot ? '' : extra_change(tree.directory, '');
1831
+ const paths = files.filter(path => prefix ? path.startsWith(prefix) : own.includes(path)).map(path => path.slice(prefix.length));
1832
+ try {
1833
+ diffs.push(...file_diffs(tree.directory, paths, tree.base).map(item => ({ ...item, path: prefix + item.path })));
1834
+ } catch { /* The card then lists names only. */ }
1835
+ }
1711
1836
  try { await api(this.config, `/executions/${execution_id}`, { action: 'report', ...(running ? { provisional: true } : {}),
1712
1837
  changes, ...edited, ...(diffs.length ? { diffs } : {}), diagnostics }); }
1713
1838
  catch (error) { if (!/HTTP (404|409)/.test(error.message)) throw error; }
@@ -1800,7 +1925,66 @@ export class FreeRoomRunner {
1800
1925
  catch (error) { if (!/HTTP 409/.test(error.message)) throw error; }
1801
1926
  this.save(name, { status: 'idle', error: '' });
1802
1927
  }
1803
- async fail(name, execution_id, reason) {
1928
+ /** Only stop handles of still-running executions with a confirmed stoppable delivery. */
1929
+ async stop_for_storage(reason) {
1930
+ if (!reason) return;
1931
+ const stopped = [];
1932
+ for (const row of this.store.db.prepare("SELECT * FROM free_deliveries WHERE status='running'").all()) {
1933
+ const id = row.execution_id;
1934
+ const delivery = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`delivery:${id}`);
1935
+ const children = this.execution_processes.get(id);
1936
+ if (!delivery || !stored_delivery(delivery.value).stoppable || !children?.size) continue;
1937
+ stopped.push(this.save(row.member, { status: 'storage_stopping', error: reason }));
1938
+ for (const child of children) this.request_stop(child);
1939
+ }
1940
+ const reports = await Promise.allSettled(stopped.map(row => this.report_storage_stop(row)));
1941
+ const failed = reports.find(result => result.status === 'rejected');
1942
+ if (failed) throw failed.reason;
1943
+ }
1944
+
1945
+ /** Retry only the bound failure report, including after a restart or lost response. */
1946
+ report_storage_stop(row) {
1947
+ const id = row.execution_id;
1948
+ if (!this.storage_reports.has(id)) {
1949
+ const report = this.fail(row.member, id, row.error, true).finally(() => this.storage_reports.delete(id));
1950
+ this.storage_reports.set(id, report);
1951
+ }
1952
+ return this.storage_reports.get(id);
1953
+ }
1954
+
1955
+ /** Classify finished tasks from the site's receipt. Unregistered draft directories are never candidates. */
1956
+ async finish_scratch(active) {
1957
+ for (const { key, value } of this.store.db.prepare("SELECT key,value FROM metadata WHERE key LIKE 'scratch:%'").all()) {
1958
+ const id = Number(key.slice('scratch:'.length));
1959
+ const record = JSON.parse(value);
1960
+ if (active.has(id) || this.execution_processes.get(id)?.size || this.orphan(id)?.alive) continue;
1961
+ try {
1962
+ const latest = await api(this.config, `/executions/${id}`);
1963
+ if (latest.status === 'completed') remove_scratch(this.config, record);
1964
+ else if (['failed', 'cancelled'].includes(latest.status)) {
1965
+ const delivery = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`delivery:${id}`);
1966
+ const stoppable = record.stoppable || (delivery && stored_delivery(delivery.value).stoppable);
1967
+ const closed = stoppable && (this.execution_processes.get(id)?.size === 0 || this.orphan(id)?.alive === false);
1968
+ if (!record.closed && !closed && !this.exited.has(id) && !this.turn_ended.has(id)) continue;
1969
+ this.store.db.prepare('UPDATE OR REPLACE metadata SET key=?,value=? WHERE key=?')
1970
+ .run(`failed-scratch:${id}`, JSON.stringify({ ...record, ended: latest.finished_at * 1000 || Date.now() }), key);
1971
+ } else continue;
1972
+ this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
1973
+ await this.on_drafts_finished?.(record.member);
1974
+ if (!this.store.db.prepare('SELECT 1 FROM metadata WHERE key=?').get(`delivery:${id}`)) {
1975
+ this.execution_processes.delete(id);
1976
+ this.forget_owner(id);
1977
+ }
1978
+ } catch (error) { this.log(`scratch #${id}: ${error.message}`); }
1979
+ }
1980
+ }
1981
+
1982
+ /** Recover the oldest confirmed failed directory in this room per pressure check. */
1983
+ reclaim_failed_scratch() {
1984
+ return reclaim_failed_scratch(this.store.db, this.config);
1985
+ }
1986
+
1987
+ async fail(name, execution_id, reason, locally_stopped = false) {
1804
1988
  const diagnostics = this.diagnostics.get(execution_id);
1805
1989
  this.activity.delete(execution_id);
1806
1990
  this.not_started.delete(execution_id);
@@ -1815,8 +1999,9 @@ export class FreeRoomRunner {
1815
1999
  try { this.on_failed({ member: name, execution_id, reason, room: this.config.room, title: this.room_title || '' }); }
1816
2000
  catch (error) { this.log(`失败通知未记录:${error.message}`); }
1817
2001
  }
1818
- this.save(name, { status: 'idle', error: reason });
1819
- this.stop_member(name);
2002
+ if (locally_stopped && !recorded) return;
2003
+ if (!locally_stopped || this.row(name)?.execution_id === execution_id) this.save(name, { status: 'idle', error: reason });
2004
+ if (!locally_stopped) this.stop_member(name);
1820
2005
  this.forget_owner(execution_id);
1821
2006
  }
1822
2007
  /**