ai_co_discuss 0.4.68 → 0.4.69

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.
@@ -9,6 +9,7 @@
9
9
  - 用户未表示可以开始时不派实现。
10
10
  - 共享工作目录不加锁:派活写明每位成员负责的目录或文件,并行的部分不让两人改同一文件。
11
11
  - `room view` 的执行报告列有改动文件,交评审时可据此写明范围。
12
+ - 并行实现交回后看 `room view` 的 `free.conflicts`:列出的文件确实被两位成员在同一时段都改过;没列出不代表没有,成员用命令写的文件不在检测范围内。
12
13
  - 同一问题反复不通过,或本链剩余轮数(`free.chain_rounds` 的 `allowed` 减 `used`;null 即不限)不够完成下一轮时,停下向用户说明分歧与现状。
13
14
  - 向用户汇报时写明仍未验证的部分。
14
15
 
@@ -232,13 +232,15 @@ def migrate_free_tables(connection):
232
232
 
233
233
 
234
234
  def migrate_failure_classes(connection):
235
- """Let development databases created when only 'quota' was a failure class also keep 'auth' and 'output_truncated'."""
235
+ """Widen older failure constraints while preserving recorded failures and reset times."""
236
236
  row = connection.execute("SELECT sql FROM sqlite_master WHERE name='execution_failures'").fetchone()
237
- if not row or "'auth'" in row[0]:
237
+ if not row or all(f"'{kind}'" in row[0] for kind in ("compaction_failed", "policy_blocked")):
238
238
  return
239
239
  connection.execute("DROP TABLE IF EXISTS execution_failures_next") # left over if a previous run stopped mid-migration
240
240
  definition = row[0].replace("execution_failures", "execution_failures_next", 1)
241
- connection.execute(definition.replace("IN ('quota')", "IN ('quota','auth','output_truncated')"))
241
+ definition = re.sub(r"CHECK\s*\(failure_class\s+IN\s*\([^)]*\)\)",
242
+ "CHECK(failure_class IN ('quota','auth','output_truncated','compaction_failed','policy_blocked'))", definition)
243
+ connection.execute(definition)
242
244
  columns = ",".join(item[1] for item in connection.execute("PRAGMA table_info(execution_failures)"))
243
245
  connection.execute(f"INSERT INTO execution_failures_next ({columns}) SELECT {columns} FROM execution_failures")
244
246
  connection.execute("DROP TABLE execution_failures")
@@ -633,7 +635,7 @@ def quota_failure(connection, execution_id):
633
635
 
634
636
 
635
637
  def failure_class_of(connection, execution_id):
636
- """The class the runner's adapter gave this failed execution (`quota`, `auth`, `output_truncated`), or ''."""
638
+ """The supported class the runner's adapter gave this failed execution, or ''."""
637
639
  row = connection.execute("SELECT failure_class FROM execution_failures WHERE execution_id=?", (execution_id,)).fetchone()
638
640
  return row["failure_class"] if row else ""
639
641
 
@@ -967,6 +969,7 @@ def recent_executions(connection, room_id, span=None):
967
969
  (SELECT MIN({LAYOUT_AT_SQL}) FROM member_requests r WHERE r.execution_id=e.id) AS layout_at,
968
970
  (SELECT COUNT(*) FROM execution_notes WHERE execution_id=e.id) AS note_count,
969
971
  (SELECT denials FROM execution_denials WHERE execution_id=e.id) AS denials,{CAPABILITY_COLUMNS},
972
+ (SELECT failure_class FROM execution_failures WHERE execution_id=e.id) AS failure_class,
970
973
  (SELECT json_object('created_at',created_at) FROM late_answers WHERE execution_id=e.id) AS late_answer,
971
974
  {BACKGROUND_SQL} AS background
972
975
  FROM member_executions e JOIN room_members m ON m.id=e.member_id WHERE e.room_id=?"""
@@ -986,7 +989,7 @@ def recent_executions(connection, room_id, span=None):
986
989
  "edited": json.loads(row["edited"]) if row["edited"] else None, "diff_stats": diff_stats(row["diffs"]),
987
990
  "answer_id": row["answer_id"], "request_message_id": row["request_message_id"],
988
991
  "layout_after": row["layout_after"], "layout_at": row["layout_at"] or row["created_at"], "requests": requests,
989
- "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"),
992
+ "notes": row["note_count"], "denials": json.loads(row["denials"] or "[]"), "failure_class": row["failure_class"] or "",
990
993
  "capabilities": reported_capabilities(row), "stop_result": row["stop_result"] or "",
991
994
  "late_answer": json.loads(row["late_answer"]) if row["late_answer"] else None, "background": bool(row["background"]),
992
995
  "retried": bool(row["retried"]),
@@ -1682,6 +1685,10 @@ def wake_after_failure(connection, execution_id, requests, reason):
1682
1685
  text = Text("{name} 额度已用尽,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。重置时间未知,它暂时长期不可用,程序暂停给它投递;请主持人改派其他成员或告知用户,不要重试。", **facts)
1683
1686
  elif failure_class_of(connection, execution_id) == "auth":
1684
1687
  text = Text("{name} 的登录已失效,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。需要用户在本机重新登录该软件后才能再用它;程序不自动重试,请主持人改派其他成员或告知用户。", **facts)
1688
+ elif failure_class_of(connection, execution_id) == "compaction_failed":
1689
+ text = Text("{name} 的上下文压缩失败,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请缩短输入或拆分任务后再决定是否重试;程序不自动重试。", **facts)
1690
+ elif failure_class_of(connection, execution_id) == "policy_blocked":
1691
+ text = Text("{name} 因安全策略拒绝,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请核对请求内容与服务许可要求,不要原样重试;程序不自动重试。", **facts)
1685
1692
  else:
1686
1693
  text = Text("{name} 处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请主持人决定重试、改派还是告知用户。",
1687
1694
  name=name, messages=messages, execution_id=execution_id, reason=str(reason)[:200])
@@ -3591,17 +3598,16 @@ def execution_action(connection, room_id, execution_id, token, payload, member=N
3591
3598
 
3592
3599
 
3593
3600
  def record_failure_class(connection, room_id, execution_id, payload):
3594
- """Keep the runner's classification of a failure: `quota` (with when it resets), `auth` (signed out) or
3595
- `output_truncated` (the model's reply hit its output cap); anything else stays unclassified."""
3601
+ """Keep an explicitly supported adapter failure class; only quota carries reset times."""
3596
3602
  if payload.get("failure_class") is None:
3597
3603
  return
3598
3604
  reset_at = payload.get("reset_at", 0)
3599
- if payload["failure_class"] in ("auth", "output_truncated"):
3605
+ if payload["failure_class"] in ("auth", "output_truncated", "compaction_failed", "policy_blocked"):
3600
3606
  connection.execute("""INSERT OR REPLACE INTO execution_failures (execution_id,room_id,failure_class,resets,failed_at,reset_at)
3601
3607
  VALUES (?,?,?,?,?,0)""", (execution_id, room_id, payload["failure_class"], "", int(time.time())))
3602
3608
  return
3603
3609
  if payload["failure_class"] != "quota" or not isinstance(payload.get("resets", ""), str) or type(reset_at) is not int:
3604
- raise ValueError(Text("failure_class 只能为 quota、auth 或 output_truncated,resets 须为文字,reset_at 须为整数秒"))
3610
+ raise ValueError(Text("failure_class 只能为 quota、auth、output_truncated、compaction_failed 或 policy_blocked,resets 须为文字,reset_at 须为整数秒"))
3605
3611
  now = int(time.time())
3606
3612
  # A reset already past or implausibly far is the adapter misreading the text: hold for the fixed time instead.
3607
3613
  reset_at = reset_at if now < reset_at <= now + MAX_QUOTA_HOLD_SECONDS else 0
@@ -345,7 +345,7 @@ CREATE TABLE IF NOT EXISTS execution_denials (
345
345
  CREATE TABLE IF NOT EXISTS execution_failures (
346
346
  execution_id INTEGER PRIMARY KEY REFERENCES member_executions(id) ON DELETE CASCADE,
347
347
  room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
348
- failure_class TEXT NOT NULL CHECK(failure_class IN ('quota','auth','output_truncated')),
348
+ failure_class TEXT NOT NULL CHECK(failure_class IN ('quota','auth','output_truncated','compaction_failed','policy_blocked')),
349
349
  resets TEXT NOT NULL DEFAULT '',
350
350
  failed_at INTEGER NOT NULL,
351
351
  reset_at INTEGER NOT NULL DEFAULT 0
package/docs/en/runner.md CHANGED
@@ -87,7 +87,7 @@ Invite an AI on another computer into your room: it reads only the project files
87
87
  **Before you start**: both computers install CoDiscuss and run the local service; your computer is [connected to a hosted site](#from-a-hosted-site) with the relay deployed, and the other side reaches your room through that site's encrypted relay. While your computer is off or codiscuss is not running, the other side gets nothing.
88
88
 
89
89
  **Invite (your computer)**:
90
- 1. In the new-room panel or Invite members, choose External → External expert and select the access, folders and membership duration after check-in.
90
+ 1. In the new-room panel or Invite members, click "External expert +" on the External row (once per expert), then on the card's back select the access, folders and membership duration after check-in.
91
91
  2. Choose Add a seat awaiting check-in (automatic when creating the room). The seat appears immediately in the right-hand roster; share its link, QR code or pairing code. The link lasts 10 minutes and binds one member; regenerating it invalidates the previous link. Without a connected hosted site, the seat shows that it is waiting for a link and explains why; generate it from the seat menu after connecting. Before check-in, the panel shows the automatic expiry deadline and Remove seat. Usage, read logs and access adjustments appear after check-in.
92
92
  3. Redemption completes check-in and starts the membership duration, with **no extra approval step**. Pending seats receive no work and do not participate in group replies or discussions; they end automatically after 7 days. An expired link leaves the seat intact.
93
93
  4. `@` it in the room; its answers appear in the conversation as usual. "Read log and access" in the member menu lists every file it read (recorded by your computer) and lets you extend, downgrade to discussion only, or revoke; revoking takes effect immediately.
@@ -163,6 +163,9 @@ After reading the roster, an implementation dispatch may include `--next-review
163
163
  ## Troubleshooting
164
164
 
165
165
  - **A delivery failed** — the room retries automatically up to three times. You can retry immediately or stop it from the failure card. After three failed attempts, the host receives the failure and decides whether to skip, reschedule or pause the discussion; the room does not pause automatically.
166
+ - **The local runner restarted** — it waits if the original app process is still running. Once that process has ended, it checks the site and the exact delivery record without sending the task again. A confirmed completed turn can have its eligible answer captured automatically; no answer is reported as missing, and uncertain outcomes fail with “Unable to confirm the previous run outcome after restart”. You or the host decide whether to retry.
166
167
  - **Codex says the session is in use** — the chat is still held by Codex App; switch the member to the App from the progress board.
167
168
  - **Windows reports two data paths** — manage the service from a regular terminal, or set `DISCUSS_SERVICE_HOME`.
168
169
  - **Uncertain results** — tasks that were delivered but not confirmed are never resent automatically; check the original session and the room first.
170
+
171
+ - **Failure advice** — the card keeps the original reason. For exhausted quota, wait for reset or reassign; for expired login, sign in locally; for output limits, shorten or split the output; for failed context compaction, shorten or split the input (the next run starts a new session); for a policy refusal, review the content and service requirements before retrying. Compaction failures and policy refusals neither trigger automatic retries nor place quota holds.
package/docs/runner.md CHANGED
@@ -118,7 +118,7 @@ codiscuss local connect https://你的站点
118
118
  **前提**:两台电脑都安装共议并运行本机服务;你的电脑已[连接线上网站](#线上网页连接本机)并部署了中转,对方经这个网站的加密中转访问你的房间。你的电脑关机或 codiscuss 未运行时,对方什么也拿不到。
119
119
 
120
120
  **邀请(你的电脑)**:
121
- 1. 建房面板或右栏“邀请成员”里选择“外部 · 外部专家”,设置开放内容、目录和签到后的有效期。
121
+ 1. 建房面板或右栏“邀请成员”里点“外部”一行的“外部专家 +”(可加多位),翻到卡片背面设置开放内容、目录和签到后的有效期。
122
122
  2. 点“添加待签到席位”(建房时自动添加),右栏名单立即显示待签到成员;把席位的链接、二维码或配对码发给对方。链接 10 分钟有效,只能绑定一位成员;重新生成会立即作废旧链接。未绑定线上站点时显示“待生成链接”及原因,绑定站点后从席位菜单生成。待签到面板显示自动结束期限,可“移除席位”;签到后才显示用量、读取记录和授权调整。
123
123
  3. 对方兑换即完成签到,成员有效期从兑换时开始,**没有额外批准步骤**。未签到不收任务、不参与全体回应或讨论,7 天后自动结束;链接过期不会删除席位。
124
124
  4. 在房间里 `@` 它,回答照常出现在对话中。成员菜单的“读取记录与权限”列出它读过的每个文件(由你的电脑记录),可延长、降为只讨论或撤销授权,撤销立即生效。
@@ -221,7 +221,9 @@ API 成员可以担任专家或主持人。房间指定了项目目录时,它
221
221
 
222
222
  ## 常见问题
223
223
 
224
- - **软件送达失败**:查看成员状态与原位失败卡,在对应软件中处理登录或权限;倒计时期间可以立即重试或停止。本机接入程序重启或异常退出、导致进行中的软件进程随之结束时,同样自动重新投递同一执行,间隔缩短为 5 秒,并在原会话里告知成员这是续跑、已做完的部分不必重做。三次重试用尽后,讨论专家的失败交给主持人处理;也可跳过本次发言。
224
+ - **软件送达失败**:查看成员状态与原位失败卡,在对应软件中处理登录或权限;倒计时期间可以立即重试或停止。本机接入程序重启后,若原软件进程已结束,会先查网站与本次投递记录,不自动续跑;确认正常完成且答案符合收录条件时自动收录,没有答案报未提交,无法确认则报“重启后无法确认上次执行结果”,由主持人或你决定是否重试。原进程仍运行时继续等待。三次重试用尽后,讨论专家的失败交给主持人处理;也可跳过本次发言。
225
225
  - **Codex 提示会话被占用**:原聊天仍被 Codex App 占用,可在进度看板切换到 App 接入。
226
226
  - **Windows 报告两处数据路径**:从普通终端管理服务,或设置环境变量 `DISCUSS_SERVICE_HOME`。
227
227
  - **结果不明**:已交付但无法确认的任务不会自动重发,请先在原会话与房间中核对。
228
+
229
+ - **失败处理建议**:失败卡保留原始原因。额度用尽可等待重置或改派;登录失效须在本机重新登录;输出达到上限应缩短输出或拆分任务;上下文压缩失败应缩短输入或拆分任务(下次执行新开会话);安全策略拒绝应核对内容与服务许可要求,不要原样重试。压缩失败和策略拒绝不会自动重试,也不会暂停额度投递。
@@ -1,4 +1,7 @@
1
1
  {
2
+ "会话上下文压缩失败({reason}),下次执行将改用新会话;请缩短输入或拆分任务后重试": "Context compaction failed ({reason}). The next run will use a new session; shorten the input or split the task before retrying",
3
+ "{name} 的上下文压缩失败,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请缩短输入或拆分任务后再决定是否重试;程序不自动重试。": "{name}'s context compaction failed while handling {messages} (run #{execution_id}): {reason}. Shorten the input or split the task before deciding whether to retry; there is no automatic retry.",
4
+ "{name} 因安全策略拒绝,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。请核对请求内容与服务许可要求,不要原样重试;程序不自动重试。": "{name} was blocked by a safety policy while handling {messages} (run #{execution_id}): {reason}. Review the request and service access requirements; do not retry it unchanged. There is no automatic retry.",
2
5
  "备份中的翻译文本没有对应原文": "Translated backup text has no corresponding source text",
3
6
  "备份中的翻译文本与原文不一致": "Translated backup text does not match its source text",
4
7
  "翻译文本数据无效": "Translated text data is invalid",
@@ -550,7 +553,7 @@
550
553
  "该成员额度已用尽,暂停投递;等额度重置后重试它失败的执行,或改派其他成员": "This member is out of quota and its deliveries are on hold. Retry its failed execution after the quota resets, or reassign the work",
551
554
  "这次执行因额度用尽失败(重置时间:{resets});额度重置前重试多半仍会失败,可改派其他成员。": "This execution failed because the quota ran out (resets at: {resets}). A retry before the reset will most likely fail again; consider reassigning the work.",
552
555
  "这次执行因额度用尽失败(重置时间未知);额度重置前重试多半仍会失败,可改派其他成员。": "This execution failed because the quota ran out (reset time unknown). A retry before the reset will most likely fail again; consider reassigning the work.",
553
- "failure_class 只能为 quota、auth 或 output_truncated,resets 须为文字,reset_at 须为整数秒": "failure_class can only be quota, auth or output_truncated, resets must be text, and reset_at must be an integer number of seconds",
556
+ "failure_class 只能为 quota、auth、output_truncated、compaction_failed 或 policy_blocked,resets 须为文字,reset_at 须为整数秒": "failure_class must be quota, auth, output_truncated, compaction_failed or policy_blocked; resets must be text and reset_at must be integer seconds",
554
557
  "{name} 的登录已失效,处理 {messages} 的执行失败(执行 #{execution_id}):{reason}。需要用户在本机重新登录该软件后才能再用它;程序不自动重试,请主持人改派其他成员或告知用户。": "{name} is signed out; its execution for {messages} failed (execution #{execution_id}): {reason}. It can work again only after the user signs that software in again on this computer; it is not retried automatically. Host: reassign the work to another member or tell the user.",
555
558
  "这次执行因登录失效失败;用户在本机重新登录该软件之前,重试仍会失败。": "This execution failed because the member is signed out; retrying will keep failing until the user signs that software in again on this computer.",
556
559
  "模型输出在 {tokens} 个 token 处达到输出上限后结束,未提交结果{reply}": "The model's output stopped at its output limit after {tokens} tokens, without submitting a result{reply}",
@@ -562,7 +565,7 @@
562
565
  "专家 {name} 已回答 #{answer_id},请继续安排本轮尚未发言的专家。": "Expert {name} answered in #{answer_id}. Continue scheduling experts who have not spoken this round.",
563
566
  "第 {round} 轮已完成,请判断是否开始下一轮或收束讨论。": "Round {round} is complete. Decide whether to start another round or conclude the discussion.",
564
567
  "[已隐去]": "[Hidden]",
565
- "本机接入程序重启或异常退出,这次执行的软件进程已结束,未提交回答": "The local runner restarted or exited unexpectedly; the app process for this run ended without submitting a reply",
568
+ "重启后无法确认上次执行结果": "Unable to confirm the previous run outcome after restart",
566
569
  "没有模型判断:{value1}": "No model judgment: {value1}",
567
570
  "自动评审交接结果尚未核验": "Automatic review handoff is unverified",
568
571
  "未自动开始下一圈:{value1}": "Did not start the next pass automatically: {value1}",
@@ -1,4 +1,9 @@
1
1
  {
2
+ "额度已用尽,请等待重置或改派其他成员。": "Usage limit reached. Wait for it to reset or assign another member.",
3
+ "登录已失效,请在本机重新登录后再试。": "Sign-in has expired. Sign in again on this computer before retrying.",
4
+ "输出达到上限,请缩短要求的输出或拆分任务。": "Output limit reached. Request a shorter answer or split the task.",
5
+ "上下文压缩失败,请缩短输入或拆分任务后再试。": "Context compaction failed. Shorten the input or split the task before retrying.",
6
+ "安全策略拒绝,请核对请求内容与服务许可要求,不要原样重试。": "Blocked by a safety policy. Review the request and service access requirements; do not retry it unchanged.",
2
7
  "{value1} 是手动启动,轮到它时需到其 AI 会话触发;不接入可在进度看板点「跳过」本次发言": "{value1} is manually started. Trigger its turn in its AI session, or click Skip on the progress board.",
3
8
  "新消息会在 {value1} 回复后交给主持人;可在进度看板点「跳过」本次发言": "New messages go to the host after {value1} replies. Click Skip on the progress board to skip this turn.",
4
9
  "思考中": "Thinking",
@@ -30,6 +30,8 @@
30
30
  "已退出该房间": "Left the room",
31
31
  "邀请外部专家": "Invite an external expert",
32
32
  "外部专家": "External expert",
33
+ "可读:{dirs}": "Reads: {dirs}",
34
+ "目录": "Folders",
33
35
  "移除这张卡片": "Remove this card",
34
36
  "能做什么": "What it may do",
35
37
  "开放目录": "Open directories",
@@ -759,5 +759,7 @@
759
759
  "读取改动失败:{value1}": "Could not read changes: {value1}",
760
760
  "改动较长,只显示前面一部分": "Long change; only the first part is shown",
761
761
  "这些文件在同一时间被改动,但不是这位成员的编辑工具写的,可能来自其他窗口或成员": "These files changed meanwhile but not through this member's edit tools; another window or member may have changed them",
762
- "同期其他改动:{value1}": "Other changes meanwhile: {value1}"
762
+ "另有 {count} 个文件同期被改动,不是它写的": "{count} more files changed meanwhile, not by this member",
763
+ "正在上传附件 {value1}/{value2}…": "Uploading attachments {value1}/{value2}…",
764
+ "正在上传": "Uploading"
763
765
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.68",
3
+ "version": "0.4.69",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -658,7 +658,7 @@ export const antigravity_cli = {
658
658
  // A deleted room's session records and any legacy private agy projects are removed with it.
659
659
  cleanup: remove_agy_projects, sweep: sweep_legacy_agy_projects,
660
660
  deliver,
661
- invocation, lifecycle, events, failure_class: agy_failure_class,
661
+ invocation, lifecycle, events, failure_class: reason => agy_failure_class(reason),
662
662
  session: { path: session_path, exists: session_exists, owns: session_exists, branch, settings: session_settings,
663
663
  list: list_sessions, preview: preview_session },
664
664
  models: { list: models, effort, defaults, defaults_stamp },
@@ -272,11 +272,12 @@ export function pi_delivery({ cli, profile, key, binding, task, context_file, sy
272
272
  }
273
273
  function settled(event) {
274
274
  if (event.aborted || state.terminal || state.failure) return finish();
275
- if (state.last_error) { fail(`模型请求失败:${state.last_error}`); return finish(); }
276
275
  if (state.compaction_error) {
277
- fail(`会话上下文已满且自动压缩失败(${state.compaction_error}),下次执行将改用新会话;可直接重试`);
276
+ fail(room_text('会话上下文压缩失败({reason}),下次执行将改用新会话;请缩短输入或拆分任务后重试',
277
+ { reason: state.compaction_error }), { failure_class: 'compaction_failed', retryable: false });
278
278
  return finish();
279
279
  }
280
+ if (state.last_error) { fail(`模型请求失败:${state.last_error}`); return finish(); }
280
281
  const reply = state.last_text.slice(0, REPLY_EXCERPT_CHARS);
281
282
  // The provider stopped the reply at its output cap: say so as it happened, without guessing why (V14-V16).
282
283
  if (state.last_stop === 'length') {
@@ -11,7 +11,7 @@ import { connect } from 'node:net';
11
11
  import { homedir } from 'node:os';
12
12
  import { dirname, join, resolve } from 'node:path';
13
13
  import { runs_commands } from '../expert_prompts.mjs';
14
- import { bind_access, DENIAL_FIELD, EDIT_TOOLS, edge_entries, launch_directory, log_entries, marked, MAX_DENIALS, model_entry, json_line,
14
+ import { bind_access, cli_max_run_ms, cli_timeout_reason, DENIAL_FIELD, EDIT_TOOLS, edge_entries, launch_directory, log_entries, marked, MAX_DENIALS, model_entry, json_line,
15
15
  clock_reset_at, newest_record, not_sent, page_sessions, preview_messages, project_directory, prompt_text, prompt_title, query_catalog,
16
16
  same_path, TASK_SUBCOMMANDS, tree_killable, typed_prompt, watch_events } from './common.mjs';
17
17
 
@@ -27,6 +27,17 @@ const CHAT_TURN_MS = 30 * 60_000;
27
27
  // Error kinds Claude Code records that a retry a minute later meets again: a used-up plan limit, a lost login.
28
28
  const LASTING_ERRORS = ['rate_limit', 'authentication_failed'];
29
29
  const EDIT_TOOL_NAMES = /^(Edit|MultiEdit|Write|NotebookEdit)$/;
30
+ const SHELL_TOOL_NAMES = /^(Bash|PowerShell)$/;
31
+ // A shell command that may write files: a redirect into a file, an in-place edit, a script writing, a copy, move or
32
+ // delete. Only such a command claims the paths it names; reading commands (cat, grep, git diff) claim none.
33
+ const SHELL_WRITES = /(?<![=\-<>])>{1,2}(?!=)\s*(?!&|\/dev\/null|\$null|nul\b)|\bsed\s+-i|\.write\w*\(|write_text|writeFileSync|\b(?:Set|Add)-Content\b|\bOut-File\b|\btee\b|\b(?:mv|cp|rm)\s|\b(?:Move|Copy|Remove|Rename)-Item\b|\bgit\s+(?:checkout|restore|apply|mv|rm)\b/i;
34
+
35
+ /** The paths a file-writing shell command names (with a folder or an extension), so files it wrote count as the agent's own. */
36
+ function shell_written_paths(command) {
37
+ const text = String(command || '');
38
+ if (!SHELL_WRITES.test(text)) return [];
39
+ return text.split(/[\s'"`;|&<>(),=]+/).filter(token => /[\\/]/.test(token) && /\.[\w-]+$/.test(token));
40
+ }
30
41
  // The Messages API refuses an image whose base64 form passes 5 MB, failing the whole turn; larger ones go by path only.
31
42
  const MAX_INLINE_IMAGE_BYTES = 3_750_000;
32
43
  // Claude Code logs side queries (titles, compaction, subagents) too; only these sources are the member's own turns.
@@ -256,8 +267,11 @@ const events = {
256
267
  },
257
268
  edits(event) {
258
269
  if (event.type !== 'assistant') return [];
259
- return (event.message?.content || []).filter(block => block.type === 'tool_use' && EDIT_TOOL_NAMES.test(block.name))
260
- .map(block => String(block.input?.file_path || block.input?.notebook_path || '')).filter(Boolean);
270
+ // Edit tools name their file; a shell command that writes is taken to have written the paths it names (Claude often
271
+ // edits by script), else its own files would read as someone else's on the card (user 2026-11-17).
272
+ return (event.message?.content || []).filter(block => block.type === 'tool_use')
273
+ .flatMap(block => EDIT_TOOL_NAMES.test(block.name) ? [String(block.input?.file_path || block.input?.notebook_path || '')]
274
+ : SHELL_TOOL_NAMES.test(block.name) ? shell_written_paths(block.input?.command) : []).filter(Boolean);
261
275
  },
262
276
  detail: claude_detail,
263
277
  };
@@ -667,8 +681,18 @@ async function deliver(config, binding, task, spawn_process = spawn) {
667
681
  } catch (error) { throw not_sent(error); }
668
682
  tree_killable(child);
669
683
  let spawned = false;
684
+ const max_run_ms = cli_max_run_ms();
685
+ let timed_out = false;
686
+ const limit_timer = setTimeout(() => {
687
+ timed_out = true;
688
+ child.kill();
689
+ task.on_failure(cli_timeout_reason(max_run_ms), { retryable: false });
690
+ }, max_run_ms);
691
+ child.once('error', () => clearTimeout(limit_timer));
670
692
  const log_path = resolve(task.directory, `claude-${task.id}.log`);
671
693
  let output = '';
694
+ task.on_recovery?.({ kind: 'claude_process', session_id, log_path,
695
+ offset: existsSync(log_path) ? statSync(log_path).size : 0 });
672
696
  let partial_line = '';
673
697
  child.stdout.on('data', chunk => {
674
698
  output += chunk;
@@ -682,7 +706,8 @@ async function deliver(config, binding, task, spawn_process = spawn) {
682
706
  child.stderr.on('data', chunk => task.on_output(log_path, chunk));
683
707
  watch_events(claude, child.stdout, task);
684
708
  child.once('close', code => {
685
- if (!spawned) return;
709
+ clearTimeout(limit_timer);
710
+ if (!spawned || timed_out) return;
686
711
  const denials = claude_denials(output);
687
712
  if (denials.length) task.on_denials?.(denials);
688
713
  const error = claude_exit_error(code, output);
@@ -853,8 +878,28 @@ function skills(profile, options = {}) {
853
878
  }), { ...options, cwd: profile.cwd || homedir(), catalog_label: '技能' });
854
879
  }
855
880
 
881
+ /** Read only this background delivery's log slice, requiring its own successful result and matching session. */
882
+ function recover_turn(record) {
883
+ const unknown = { status: 'unknown', exact: false };
884
+ if (record?.kind !== 'claude_process' || !record.session_id || !record.log_path
885
+ || !Number.isSafeInteger(record.offset) || record.offset < 0) return unknown;
886
+ const bytes = readFileSync(record.log_path);
887
+ if (bytes.length <= record.offset) return unknown;
888
+ const output = bytes.subarray(record.offset).toString('utf8');
889
+ const entries = output.trim().split(/\r?\n/).map(json_line).filter(Boolean);
890
+ const results = entries.filter(entry => entry.type === 'result');
891
+ const result = results[0];
892
+ if (results.length !== 1 || entries.at(-1) !== result || result.session_id !== record.session_id
893
+ || entries.some(entry => entry.session_id && entry.session_id !== record.session_id)) return unknown;
894
+ if (result.is_error === true) return { status: 'failed', exact: true };
895
+ if (result.is_error !== false || result.subtype !== 'success') return unknown;
896
+ return { status: 'completed', exact: true, text: entries.map(events.note).filter(Boolean).at(-1) || '',
897
+ denied: claude_denials(JSON.stringify(result)).length > 0 };
898
+ }
899
+
856
900
  /** Claude Code's behaviour; its static facts are in profiles.mjs. */
857
901
  export const claude = {
902
+ recover_turn,
858
903
  id: 'claude', catalog_source: 'claude-cli',
859
904
  into_window: claude_inbox_ready,
860
905
  deliver, chat, events,
@@ -7,12 +7,10 @@
7
7
  */
8
8
  import { resolve } from 'node:path';
9
9
  import { createInterface } from 'node:readline';
10
- import { bind_access, launch_directory, not_sent, report_edits, track_edits, tree_killable } from './common.mjs';
10
+ import { bind_access, cli_max_run_ms, cli_timeout_reason, launch_directory, not_sent, report_edits, track_edits, tree_killable } from './common.mjs';
11
11
  import { adapter_capabilities } from './profiles.mjs';
12
12
 
13
13
  const CLI_DIAGNOSTIC_CHARS = 1000;
14
- // A hung CLI keeps its lease renewed forever when the room sets no execution limit, so cap every process.
15
- const CLI_MAX_RUN_MS = 2 * 60 * 60_000;
16
14
  // Immediate restarts of a CLI that failed before any turn ran, before the runner's slower retry takes over.
17
15
  const CLI_START_RETRIES = 2;
18
16
 
@@ -53,9 +51,9 @@ function monitor_cli(adapter, child, binding, task, restart) {
53
51
  const log_path = resolve(task.directory, `${adapter.id}-${task.id}.log`);
54
52
  state.log_path = log_path;
55
53
  const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
56
- const max_run_ms = Number(process.env.CODISCUSS_CLI_MAX_MS) || CLI_MAX_RUN_MS;
54
+ const max_run_ms = cli_max_run_ms();
57
55
  track_edits(adapter, task);
58
- state.limit_timer = setTimeout(() => { state.error = `CLI 运行超过 ${Math.round(max_run_ms / 1000)} 秒仍未结束,已终止`; child.kill(); }, max_run_ms);
56
+ state.limit_timer = setTimeout(() => { state.error = cli_timeout_reason(max_run_ms); child.kill(); }, max_run_ms);
59
57
  child.stdout.on('data', chunk => task.on_output(log_path, chunk));
60
58
  child.stderr.setEncoding('utf8');
61
59
  child.stderr.on('data', chunk => {
@@ -85,7 +83,7 @@ function monitor_cli(adapter, child, binding, task, restart) {
85
83
  if (state.denials.length) task.on_denials?.(state.denials);
86
84
  const error = cli_exit_error(adapter, state, code, signal);
87
85
  // The adapter's classification of the failure (`quota` with when it resets); a lasting one is never started again.
88
- const failure = error ? adapter.failure_class?.(error) || {} : {};
86
+ const failure = error ? adapter.failure_class?.(error, state) || {} : {};
89
87
  if (error && state.not_started && !state.stopped && !failure.failure_class && restart?.()) return;
90
88
  // `not_started`: the adapter saw the CLI fail before any turn ran, so the runner may deliver the same task again.
91
89
  if (error) task.on_failure(error, { not_started: Boolean(state.not_started) && !failure.failure_class,
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { spawn } from 'node:child_process';
13
13
  import { createInterface } from 'node:readline';
14
+ import { tree_killable } from './common.mjs';
14
15
 
15
16
  /**
16
17
  * The under-development `context_management` feature lets the model call `new_context`, which drops the history without a
@@ -28,6 +29,7 @@ let finished = false;
28
29
  const queued_steers = [];
29
30
 
30
31
  const server = spawn(executable, ['app-server', ...CONTEXT_OVERRIDES, ...server_args], { windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
32
+ tree_killable(server);
31
33
  server.stderr.pipe(process.stderr);
32
34
  server.once('error', error => fail(error.message));
33
35
  server.once('close', code => { if (!finished) fail(`Codex app-server 意外退出(${code})`); });
@@ -70,6 +72,13 @@ function exec_item(item) {
70
72
  return null;
71
73
  }
72
74
 
75
+ /** Forward only bounded software error-code fields, never arbitrary provider error metadata. */
76
+ function error_details(error = {}) {
77
+ if (!error || typeof error !== 'object') return {};
78
+ return Object.fromEntries(['codex_error_info', 'codexErrorInfo'].filter(key => typeof error[key] === 'string'
79
+ && error[key].length <= 128).map(key => [key, error[key]]));
80
+ }
81
+
73
82
  /** Translate one server notification; the turn's end ends this process. */
74
83
  function notification({ method, params = {} }) {
75
84
  if (params.threadId && params.threadId !== thread_id) return;
@@ -77,11 +86,11 @@ function notification({ method, params = {} }) {
77
86
  else if (method === 'item/started' || method === 'item/completed') {
78
87
  const item = exec_item(params.item || {});
79
88
  if (item) emit({ type: method === 'item/started' ? 'item.started' : 'item.completed', item });
80
- } else if (method === 'error') emit({ type: 'error', message: params.error?.message || params.message || 'Codex 返回错误' });
89
+ } else if (method === 'error') emit({ type: 'error', message: params.error?.message || params.message || 'Codex 返回错误', ...error_details(params.error) });
81
90
  else if (method === 'turn/completed') {
82
91
  const turn = params.turn || {};
83
92
  if (turn.status === 'completed') emit({ type: 'turn.completed', usage: params.usage || {} });
84
- else emit({ type: 'turn.failed', error: { message: turn.error?.message || (turn.status === 'interrupted' ? '本轮已中断' : 'Codex 本轮失败') } });
93
+ else emit({ type: 'turn.failed', error: { message: turn.error?.message || (turn.status === 'interrupted' ? '本轮已中断' : 'Codex 本轮失败'), ...error_details(turn.error) } });
85
94
  finished = true;
86
95
  server.kill();
87
96
  process.stdout.write('', () => process.exit(0));
@@ -121,6 +130,7 @@ async function start(task) {
121
130
  const started = await request('turn/start', { threadId: thread_id, input: [{ type: 'text', text: task.prompt }, ...images],
122
131
  ...(task.model ? { model: task.model } : {}), ...(task.effort ? { effort: task.effort } : {}) });
123
132
  turn_id = started.turn.id;
133
+ emit({ type: 'codiscuss.turn', thread_id, turn_id, rollout_path: opened.thread.path || '' });
124
134
  for (const text of queued_steers.splice(0)) await steer(text);
125
135
  }
126
136
 
@@ -128,12 +128,23 @@ function remember_writer_conflict(state, diagnostic) {
128
128
  /** Consume only documented lifecycle events, not text produced by agent tools. */
129
129
  function lifecycle(state, event, task, bind) {
130
130
  if (event.type === 'thread.started') bind(event.thread_id);
131
+ if (event.type === 'codiscuss.turn') task.on_recovery?.({ kind: 'codex_turn',
132
+ thread_id: event.thread_id, turn_id: event.turn_id, rollout_path: event.rollout_path });
131
133
  if (event.type === 'turn.completed') { state.completed = true; state.finish_timer = setTimeout(() => { state.finished = true; task.on_trace?.('kill_after_completed'); state.child.kill(); }, CLI_EXIT_GRACE_MS); }
132
- if (event.type === 'turn.failed') state.error = event.error?.message || 'Codex CLI 执行失败';
133
- if (event.type === 'error') state.diagnostic = event.message || 'Codex CLI 返回错误';
134
+ if (event.type === 'turn.failed') { state.error = event.error?.message || 'Codex CLI 执行失败'; state.failure_info = event.error; }
135
+ if (event.type === 'error') { state.diagnostic = event.message || 'Codex CLI 返回错误'; if (!state.error) state.failure_info = event; }
134
136
  remember_writer_conflict(state, state.error || state.diagnostic);
135
137
  }
136
138
 
139
+ /** Classify only software-provided codes; text, unknown codes and conflicting fields stay unclassified. */
140
+ function failure_class(error, state = {}) {
141
+ const info = state.failure_info || {};
142
+ const classes = { usage_limit_exceeded: 'quota', usageLimitExceeded: 'quota', cyber_policy: 'policy_blocked' };
143
+ const values = [info.codex_error_info, info.codexErrorInfo].filter(value => value !== undefined);
144
+ const kinds = values.map(value => typeof value === 'string' && Object.hasOwn(classes, value) ? classes[value] : undefined);
145
+ return kinds.length && kinds.every(kind => kind && kind === kinds[0]) ? { failure_class: kinds[0] } : {};
146
+ }
147
+
137
148
  /** A thread another process writes to cannot be resumed here; retrying does not release it. */
138
149
  function exit_error(state) {
139
150
  return state.writer_conflict ? `Codex 会话 ${state.session_id} 已被另一进程持有(active writer),CLI 无法接管。若为 App 中的聊天,请使用 Codex App 接入;独立 CLI 须使用未被占用的会话。重复点击重试不会解除占用` : '';
@@ -414,8 +425,35 @@ async function chat(config, binding, task, spawn_process, user_home) {
414
425
  return daemon_chat(link, binding.session_id, task);
415
426
  }
416
427
 
428
+ /** Recover only the recorded root turn in its thread; other turns and incomplete evidence cannot supply an answer. */
429
+ function recover_turn(record) {
430
+ const unknown = { status: 'unknown', exact: false };
431
+ if (record?.kind !== 'codex_turn' || !record.thread_id || !record.turn_id) return unknown;
432
+ const file = record.rollout_path || session_path(record.thread_id);
433
+ if (!file) return unknown;
434
+ const entries = readFileSync(file, 'utf8').trim().split(/\r?\n/).map(line => JSON.parse(line));
435
+ const meta = entries.find(entry => entry.type === 'session_meta')?.payload;
436
+ if (meta?.id !== record.thread_id || typeof meta.source === 'object') return unknown;
437
+ const turns = entries.filter(entry => entry.type === 'event_msg' && entry.payload?.turn_id === record.turn_id).map(entry => entry.payload);
438
+ const starts = turns.filter(event => event.type === 'task_started');
439
+ const ends = turns.filter(event => ['task_complete', 'turn_aborted'].includes(event.type));
440
+ if (starts.length !== 1 || ends.length !== 1) return unknown;
441
+ if ([starts[0], ends[0]].some(event => event.root_turn_id !== record.turn_id || event.parent_turn_id)) return unknown;
442
+ if (turns.indexOf(ends[0]) < turns.indexOf(starts[0])) return unknown;
443
+ if (ends[0].type === 'turn_aborted') return { status: 'interrupted', exact: true };
444
+ if (ends[0].error != null) {
445
+ const error = ends[0].error;
446
+ return typeof error === 'object' && !Array.isArray(error)
447
+ && (typeof error.message === 'string' || typeof error.codex_error_info === 'string' || typeof error.codexErrorInfo === 'string')
448
+ ? { status: 'failed', exact: true } : unknown;
449
+ }
450
+ if (ends[0].last_agent_message != null && typeof ends[0].last_agent_message !== 'string') return unknown;
451
+ return { status: 'completed', exact: true, text: ends[0].last_agent_message || '' };
452
+ }
453
+
417
454
  /** Codex CLI's behaviour; its static facts are in profiles.mjs. */
418
455
  export const codex_cli = {
456
+ recover_turn, failure_class,
419
457
  id: 'codex_cli', catalog_source: 'codex-app-server',
420
458
  deliver: (config, binding, task, spawn_process, user_home) => cli_delivery(codex_cli, config, binding, task, spawn_process, user_home),
421
459
  chat,
@@ -6,10 +6,18 @@ import { tmpdir } from 'node:os';
6
6
  import { createInterface } from 'node:readline';
7
7
  import { TASK_SUBCOMMANDS } from '../expert_prompts.mjs';
8
8
  import { atomic_json } from '../files.mjs';
9
+ import { t } from '../i18n.mjs';
9
10
 
10
11
  // The room defines which website subcommands a task may run; adapters turn them into each software's permission rules.
11
12
  export { TASK_SUBCOMMANDS };
12
13
  export const CALL_TIMEOUT_MS = 30_000;
14
+ export const CLI_MAX_RUN_MS = 2 * 60 * 60_000;
15
+ /** The shared headless process limit, including the operator's override. */
16
+ export function cli_max_run_ms() { return Number(process.env.CODISCUSS_CLI_MAX_MS) || CLI_MAX_RUN_MS; }
17
+ /** Explain the total runtime limit in the CLI's selected language. */
18
+ export function cli_timeout_reason(milliseconds) {
19
+ return t('CLI 运行超过 {seconds} 秒仍未结束,已终止', { seconds: Math.round(milliseconds / 1000) });
20
+ }
13
21
  /** Tool names that edit files, across the softwares' event streams. */
14
22
  export const EDIT_TOOLS = /^(Edit|MultiEdit|Write|NotebookEdit|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/;
15
23
  /** A refused operation's detail and rule are cut to this length; a run reports at most this many. */
@@ -17,6 +17,8 @@
17
17
  * at the end (`on_exit(reason)` when the turn ended unfinished but should not be retried, such as an interrupted or
18
18
  * closed window or a refused operation: the runner then neither captures the last remark nor retries), `on_process(handle)` with `kill()` when it can stop (`handle.stop_on_shutdown = false` when only the owner's stop may
19
19
  * run it, not the runner's shutdown), `on_output(path, line)` for its process log;
20
+ * - optional `recover_turn(record)` reads a delivery recorded by `task.on_recovery(record)` and returns
21
+ * `{status: 'completed'|'interrupted'|'failed'|'unknown', exact, text?, denied?}` without invoking software;
20
22
  * - optional `receipt(config, id)` for deliveries confirmed later (`status: 'sidecar_pending'`),
21
23
  * `into_window(profile, binding)` (this delivery goes into the member's own open window), `cleanup(directory)`
22
24
  * (remove what a deleted room left in the software) and `sweep(service_home, user_home)` (back up and remove retired
@@ -48,6 +50,13 @@ const SESSION_PATTERN = /^[0-9A-Za-z_-]{8,128}$/;
48
50
  /** The descriptor of a configured adapter, or null for a value this version does not support. */
49
51
  export function adapter_of(id) { return ADAPTERS[id] || null; }
50
52
 
53
+ /** Read one recorded delivery's outcome without starting software; missing or unreadable evidence is unknown. */
54
+ export async function recover_turn(adapter_id, record) {
55
+ try {
56
+ return await adapter_of(adapter_id)?.recover_turn?.(record) || { status: 'unknown', exact: false };
57
+ } catch { return { status: 'unknown', exact: false }; }
58
+ }
59
+
51
60
  /**
52
61
  * Which adapter holds an existing conversation of the software a manual member registered with (`client`): the one
53
62
  * whose store owns it, else the CLI that would resume it. '' when no adapter takes over that software.