@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-beta.4

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 (60) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +54 -15
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +25 -4
  5. package/dist/agent/effect-ledger.js +45 -5
  6. package/dist/agent/job-manager.d.ts +20 -0
  7. package/dist/agent/job-manager.js +66 -10
  8. package/dist/agent/maintenance-context.js +3 -2
  9. package/dist/agent/progress-formatter.d.ts +10 -1
  10. package/dist/agent/progress-formatter.js +14 -2
  11. package/dist/agent/prompt/manifest.d.ts +32 -1
  12. package/dist/agent/prompt/manifest.js +41 -2
  13. package/dist/executor.d.ts +2 -0
  14. package/dist/executor.js +1 -0
  15. package/dist/memory/maintenance-gates.d.ts +24 -10
  16. package/dist/memory/maintenance-gates.js +11 -9
  17. package/dist/memory/maintenance-jobs.d.ts +3 -2
  18. package/dist/memory/maintenance-jobs.js +33 -21
  19. package/dist/memory/scheduler.d.ts +7 -2
  20. package/dist/playbooks/task-closeout.md +2 -0
  21. package/dist/playbooks/task-delegation.md +14 -8
  22. package/dist/playbooks/task-driving.md +8 -5
  23. package/dist/playbooks/task-planning.md +2 -2
  24. package/dist/runtime/bootstrap.js +35 -9
  25. package/dist/runtime/delivery.d.ts +12 -2
  26. package/dist/runtime/delivery.js +55 -13
  27. package/dist/runtime/dingtalk.d.ts +9 -1
  28. package/dist/runtime/dingtalk.js +7 -4
  29. package/dist/runtime/task-commands.js +170 -54
  30. package/dist/runtime/task-driver.d.ts +3 -3
  31. package/dist/runtime/task-driver.js +42 -12
  32. package/dist/settings.d.ts +10 -0
  33. package/dist/settings.js +14 -0
  34. package/dist/shared/file-stamp.d.ts +10 -0
  35. package/dist/shared/file-stamp.js +19 -0
  36. package/dist/shared/task-ledger.d.ts +12 -1
  37. package/dist/shared/task-ledger.js +34 -3
  38. package/dist/subagents/tool.d.ts +1 -0
  39. package/dist/subagents/tool.js +33 -3
  40. package/dist/tasks/control.d.ts +1 -0
  41. package/dist/tasks/control.js +2 -2
  42. package/dist/tasks/transitions.d.ts +2 -1
  43. package/dist/tasks/transitions.js +2 -1
  44. package/dist/tasks/verification.d.ts +8 -0
  45. package/dist/tasks/verification.js +4 -1
  46. package/dist/tools/bash.js +12 -12
  47. package/dist/tools/task-manage/lifecycle.js +9 -6
  48. package/dist/tools/task-manage/schema.d.ts +1 -3
  49. package/dist/tools/task-manage/schema.js +6 -5
  50. package/dist/tools/task-manage/shared.d.ts +8 -0
  51. package/dist/tools/task-manage/shared.js +17 -1
  52. package/dist/tools/task-manage/types.d.ts +20 -21
  53. package/dist/tools/task-manage/verification.d.ts +2 -1
  54. package/dist/tools/task-manage/verification.js +2 -1
  55. package/dist/tools/task-manage.js +4 -20
  56. package/dist/tui/turn-controller.js +3 -3
  57. package/dist/usage/ledger.d.ts +2 -0
  58. package/dist/usage/ledger.js +7 -2
  59. package/dist/usage/render.js +17 -8
  60. package/package.json +1 -1
@@ -91,6 +91,18 @@ export declare class ChannelRunner implements AgentRunner {
91
91
  private recordMemoryActivity;
92
92
  private requireQueuedMessage;
93
93
  private shouldPreserveRawInput;
94
+ /**
95
+ * Save a message that exceeds the per-turn input budget so its clipped middle stays reachable.
96
+ *
97
+ * Pasting a long build log or diff is a normal way to start driving work here, and the clip
98
+ * keeps head and tail — which is where the failing frames usually are *not*. Landing the
99
+ * original under the channel directory puts it inside the paths `read` already allows, so
100
+ * recovery is the ordinary paging path rather than a special case.
101
+ *
102
+ * Best-effort: if the write fails the turn still runs on the clipped text, just without a
103
+ * pointer.
104
+ */
105
+ private persistOversizedInput;
94
106
  private formatUserMessage;
95
107
  /**
96
108
  * Single source of truth for the busy-message window: steer is accepted while
@@ -33,7 +33,7 @@ import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } fro
33
33
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
34
34
  import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
35
35
  import { createPromptBoundaryExtension } from "./prompt/extension.js";
36
- import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
36
+ import { buildPromptManifest, measureToolSchemas, renderContextReport, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning, } from "./prompt/manifest.js";
37
37
  import { loadWorkspacePromptResources } from "./prompt/resources.js";
38
38
  import { createRunQueue } from "./run-queue.js";
39
39
  import { handleSessionEvent } from "./session-events.js";
@@ -171,10 +171,14 @@ export class ChannelRunner {
171
171
  await this.maybeRestorePrimaryModel();
172
172
  this.memoryLifecycle.noteUserTurnStarted();
173
173
  const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
174
+ let oversizedInputPath;
174
175
  if (normalizedInputLength > MAX_USER_MESSAGE_CHARS) {
175
- await ctx.respondInThread(`⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理。`);
176
+ oversizedInputPath = await this.persistOversizedInput(ctx.message.text);
177
+ await ctx.respondInThread(oversizedInputPath
178
+ ? `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理;完整内容已存到 \`${oversizedInputPath}\`,可以让我 read 该文件查看被省略的部分。`
179
+ : `⚠️ 消息过长(${normalizedInputLength} 字符),已截断至约 ${MAX_USER_MESSAGE_CHARS} 字符后处理。`);
176
180
  }
177
- const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS);
181
+ const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS, oversizedInputPath);
178
182
  const userMessage = this.formatUserMessage(clippedInput, ctx.message.userName);
179
183
  const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
180
184
  // Ensure channel directory exists
@@ -359,12 +363,12 @@ export class ChannelRunner {
359
363
  : undefined;
360
364
  const detailLines = [`\`${baseErrorSummary}\``];
361
365
  if (compactionSummary) {
362
- detailLines.push(`Recovery: \`${compactionSummary}\``);
366
+ detailLines.push(`恢复尝试:\`${compactionSummary}\``);
363
367
  }
364
368
  if (fallbackAttempted && fallbackTargetRef) {
365
369
  detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
366
370
  }
367
- await ctx.replaceMessage(`_Sorry, something went wrong._\n\n${detailLines.join("\n\n")}`);
371
+ await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
368
372
  }
369
373
  catch (err) {
370
374
  const errMsg = errorMessage(err);
@@ -405,8 +409,9 @@ export class ChannelRunner {
405
409
  finally {
406
410
  await ctx.close();
407
411
  }
408
- // Log usage summary
409
- if (this.runState.totalUsage.cost.total > 0) {
412
+ // Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
413
+ // bills nothing, and skipping it here left both the log and the ledger empty.
414
+ if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
410
415
  const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
411
416
  const contextTokens = lastAssistantMessage
412
417
  ? lastAssistantMessage.usage.input +
@@ -466,15 +471,15 @@ export class ChannelRunner {
466
471
  await this.sendCommandReply(ctx, this.renderContextReport(command.args));
467
472
  return;
468
473
  case "stop":
469
- await this.sendCommandReply(ctx, "No task is running. Use `/stop` only while a task is running.");
474
+ await this.sendCommandReply(ctx, "当前没有运行中的回合,`/stop` 只在回合进行中有意义。");
470
475
  return;
471
476
  case "steer":
472
477
  this.requireQueuedMessage(command.args, "steer");
473
- await this.sendCommandReply(ctx, "No task is running. Send the message directly instead of using `/steer`.");
478
+ await this.sendCommandReply(ctx, "当前没有运行中的回合,直接发消息即可,不用 `/steer`。");
474
479
  return;
475
480
  case "followup":
476
481
  this.requireQueuedMessage(command.args, "followup");
477
- await this.sendCommandReply(ctx, "No task is running. Send the message directly now, or use `/followup` while a task is running.");
482
+ await this.sendCommandReply(ctx, "当前没有运行中的回合,直接发消息即可;`/followup` 用于回合进行中排队。");
478
483
  return;
479
484
  default: {
480
485
  // The four session/query commands (events/tasks/status/usage) are
@@ -520,8 +525,10 @@ export class ChannelRunner {
520
525
  return {
521
526
  channelId: this.channelId,
522
527
  channelDir: this.channelDir,
523
- messages: [...this.session.messages],
524
- sessionEntries: [...this.sessionManager.getBranch()],
528
+ // Snapshot only when a maintenance job actually needs the transcript; most ticks
529
+ // stop at a schedule gate and never call these.
530
+ messages: () => [...this.session.messages],
531
+ sessionEntries: () => [...this.sessionManager.getBranch()],
525
532
  model: this.session.model ?? this.activeModel,
526
533
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
527
534
  settings: {
@@ -562,7 +569,7 @@ export class ChannelRunner {
562
569
  finalPrompt: this.lastFinalPrompt,
563
570
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
564
571
  toolNames: this.currentTools.map((tool) => tool.name),
565
- toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
572
+ toolSchemas: measureToolSchemas(this.currentTools),
566
573
  soul: this.lastWorkspaceResources?.soul,
567
574
  agents: this.lastWorkspaceResources?.agents,
568
575
  lastTurn: this.lastTurnContextStats,
@@ -617,6 +624,30 @@ export class ChannelRunner {
617
624
  shouldPreserveRawInput(text) {
618
625
  return text.trim().startsWith("/");
619
626
  }
627
+ /**
628
+ * Save a message that exceeds the per-turn input budget so its clipped middle stays reachable.
629
+ *
630
+ * Pasting a long build log or diff is a normal way to start driving work here, and the clip
631
+ * keeps head and tail — which is where the failing frames usually are *not*. Landing the
632
+ * original under the channel directory puts it inside the paths `read` already allows, so
633
+ * recovery is the ordinary paging path rather than a special case.
634
+ *
635
+ * Best-effort: if the write fails the turn still runs on the clipped text, just without a
636
+ * pointer.
637
+ */
638
+ async persistOversizedInput(text) {
639
+ try {
640
+ const dir = join(this.channelDir, "inbox");
641
+ await mkdir(dir, { recursive: true });
642
+ const path = join(dir, `message-${new Date().toISOString().replace(/[:.]/g, "-")}.txt`);
643
+ await writeFile(path, text.replace(/\r/g, ""), { mode: 0o600 });
644
+ return path;
645
+ }
646
+ catch (error) {
647
+ log.logWarning("Could not persist oversized user message", errorMessage(error));
648
+ return undefined;
649
+ }
650
+ }
620
651
  formatUserMessage(text, userName, now = new Date()) {
621
652
  const pad = (n) => n.toString().padStart(2, "0");
622
653
  const offset = -now.getTimezoneOffset();
@@ -644,8 +675,10 @@ export class ChannelRunner {
644
675
  async queueBusyMessage(text, userName) {
645
676
  this.assertBusyWindowOpen();
646
677
  await this.ensureSessionReady();
647
- const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS);
648
- if (clippedText !== text.trim()) {
678
+ const oversized = text.replace(/\r/g, "").trim().length > MAX_USER_MESSAGE_CHARS;
679
+ const oversizedPath = oversized ? await this.persistOversizedInput(text) : undefined;
680
+ const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS, oversizedPath);
681
+ if (oversized) {
649
682
  log.logWarning(`[${this.channelId}] Queued message exceeded ${MAX_USER_MESSAGE_CHARS} chars and was clipped`);
650
683
  }
651
684
  const queuedMessage = this.formatUserMessage(clippedText, userName);
@@ -1021,6 +1054,12 @@ export class ChannelRunner {
1021
1054
  mediaSender: this.mediaSender,
1022
1055
  });
1023
1056
  this.currentTools = tools;
1057
+ // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
1058
+ // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
1059
+ const schemas = measureToolSchemas(tools);
1060
+ if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
1061
+ log.logWarning(`[${this.channelId}] Tool schema budget`, toolSchemaBudgetWarning(schemas));
1062
+ }
1024
1063
  return tools;
1025
1064
  }
1026
1065
  rebuildSessionTools() {
@@ -5,34 +5,34 @@
5
5
  export const BUILT_IN_COMMANDS = [
6
6
  {
7
7
  name: "help",
8
- description: "Show command help",
8
+ description: "显示命令帮助",
9
9
  examples: ["/help"],
10
10
  availableWhileBusy: true,
11
11
  },
12
12
  {
13
13
  name: "stop",
14
- description: "Stop the current task",
14
+ description: "停止当前回合;若该回合由任务驱动,同时暂停该任务",
15
15
  examples: ["/stop"],
16
16
  availableWhileBusy: true,
17
17
  },
18
18
  {
19
19
  name: "steer",
20
- argumentHint: "<message>",
21
- description: "Adjust the running task after the current tool step finishes",
20
+ argumentHint: "<消息>",
21
+ description: "在当前工具步骤结束后调整正在运行的回合",
22
22
  examples: ["/steer Use the Shanghai time zone and summarize only the latest updates"],
23
23
  availableWhileBusy: true,
24
24
  },
25
25
  {
26
26
  name: "followup",
27
- argumentHint: "<message>",
28
- description: "Queue a request to run after the current task completes",
27
+ argumentHint: "<消息>",
28
+ description: "排队一条请求,等当前回合结束后再执行",
29
29
  examples: ["/followup After that, draft a short executive summary"],
30
30
  availableWhileBusy: true,
31
31
  },
32
32
  {
33
33
  name: "events",
34
34
  argumentHint: "<list|show|delete|history>",
35
- description: "Manage scheduled event files and inspect event history",
35
+ description: "管理定时事件文件,查看事件历史",
36
36
  examples: [
37
37
  "/events list",
38
38
  "/events show weekly-review",
@@ -43,8 +43,8 @@ export const BUILT_IN_COMMANDS = [
43
43
  },
44
44
  {
45
45
  name: "tasks",
46
- argumentHint: "[show <id>|archive|approve <id>|pause <id>|resume <id>|run <id>|stats [id]|doctor]",
47
- description: "View and diagnose the channel's task ledger; `approve` gates external side effects",
46
+ argumentHint: "[show <id>|archive|approve <id>|pause <id>|resume <id>|run <id>|set <id> <字段> <值>|stats [id]|doctor]",
47
+ description: "查看、诊断并直接编辑本频道的任务台账;`approve` 用于放行外部副作用",
48
48
  examples: [
49
49
  "/tasks",
50
50
  "/tasks show weekly-report",
@@ -53,6 +53,8 @@ export const BUILT_IN_COMMANDS = [
53
53
  "/tasks pause weekly-report",
54
54
  "/tasks resume weekly-report",
55
55
  "/tasks run weekly-report",
56
+ "/tasks set weekly-report wake 2026-07-28T09:00:00+08:00",
57
+ "/tasks set weekly-report next 跑一遍构建并贴出失败堆栈",
56
58
  "/tasks stats weekly-report",
57
59
  "/tasks doctor",
58
60
  ],
@@ -60,21 +62,21 @@ export const BUILT_IN_COMMANDS = [
60
62
  },
61
63
  {
62
64
  name: "status",
63
- description: "Show run state, current model, context usage, uptime, and version",
65
+ description: "显示运行状态、当前模型、上下文占用、运行时长与版本",
64
66
  examples: ["/status"],
65
67
  availableWhileBusy: true,
66
68
  },
67
69
  {
68
70
  name: "usage",
69
71
  argumentHint: "[7d|month]",
70
- description: "Show LLM cost for this channel and globally, broken down by kind and top models",
72
+ description: "显示本频道与全局的模型花费和 token,按类型与模型分解",
71
73
  examples: ["/usage", "/usage 7d", "/usage month"],
72
74
  availableWhileBusy: true,
73
75
  },
74
76
  {
75
77
  name: "context",
76
78
  argumentHint: "[detail]",
77
- description: "Show what the model is being sent: system prompt sections, tool schemas, and last-turn context",
79
+ description: "显示实际发给模型的内容:system prompt 分段、工具 schema、上一回合上下文",
78
80
  examples: ["/context", "/context detail"],
79
81
  // Read-only accounting of state the runner already holds: no LLM call, no session
80
82
  // access, so it answers mid-turn like /status and /usage do.
@@ -90,35 +92,35 @@ export const SESSION_COMMANDS = [
90
92
  {
91
93
  name: "memory",
92
94
  argumentHint: "[status|list|show <id>|pending]",
93
- description: "Inspect active memory, metadata, recall statistics, tombstones, and pending suggestions",
95
+ description: "查看生效记忆、元数据、召回统计、墓碑与待确认建议",
94
96
  examples: ["/memory status", "/memory list", "/memory show m-1234abcd", "/memory pending"],
95
97
  },
96
98
  {
97
99
  name: "session",
98
- description: "Show current session state, message stats, token usage, and model info",
100
+ description: "显示当前会话状态、消息统计、token 用量与模型信息",
99
101
  examples: ["/session"],
100
102
  },
101
103
  {
102
104
  name: "thinking",
103
105
  argumentHint: "[off|minimal|low|medium|high|xhigh|max|cycle]",
104
- description: "Show or change the thinking level for the current model",
106
+ description: "查看或修改当前模型的思考档位",
105
107
  examples: ["/thinking", "/thinking medium", "/thinking cycle"],
106
108
  },
107
109
  {
108
110
  name: "model",
109
111
  argumentHint: "[provider/modelId|modelId]",
110
- description: "Show the current model, or switch models using an exact or uniquely matching substring",
112
+ description: "查看当前模型,或用精确名/唯一匹配的子串切换模型",
111
113
  examples: ["/model", "/model anthropic/claude-opus-4-6"],
112
114
  },
113
115
  {
114
116
  name: "new",
115
- description: "Start a new session",
117
+ description: "开启新会话",
116
118
  examples: ["/new"],
117
119
  },
118
120
  {
119
121
  name: "compact",
120
- argumentHint: "[instructions]",
121
- description: "Manually compact the current session context, with optional custom instructions",
122
+ argumentHint: "[压缩要求]",
123
+ description: "手动压缩当前会话上下文,可附加自定义要求",
122
124
  examples: ["/compact", "/compact Keep the latest TODOs and decisions"],
123
125
  },
124
126
  ];
@@ -150,30 +152,30 @@ function renderCommandEntry(spec) {
150
152
  const header = `- \`/${spec.name}${spec.argumentHint ? ` ${spec.argumentHint}` : ""}\``;
151
153
  const lines = [header, ` ${spec.description}`];
152
154
  for (const example of spec.examples ?? []) {
153
- lines.push(` Example: \`${example}\``);
155
+ lines.push(` 示例:\`${example}\``);
154
156
  }
155
157
  return lines.join("\n");
156
158
  }
157
159
  function renderHelpText() {
158
160
  const transport = BUILT_IN_COMMANDS.map(renderCommandEntry).join("\n");
159
161
  const session = SESSION_COMMANDS.map(renderCommandEntry).join("\n");
160
- return `# Slash Commands
162
+ return `# 斜杠命令
161
163
 
162
- Pipiclaw supports two command groups.
164
+ Pipiclaw 的命令分为两组。
163
165
 
164
- ## Transport Commands
166
+ ## 传输层命令
165
167
 
166
- These are handled directly by the DingTalk transport/runtime layer.
168
+ 由钉钉传输层/运行时直接处理,回合进行中也可以用。
167
169
 
168
170
  ${transport}
169
171
 
170
- While a task is running, plain messages use the configured busy-message default. The default is \`steer\`; set \`busyMessageDefault\` in channel.json to \`followUp\` or \`followup\` to queue plain messages after the current task.
172
+ 回合进行中发送的普通消息按 \`busyMessageDefault\` 处理,默认是 \`steer\`;在 channel.json 里设为 \`followUp\`(或 \`followup\`)则改为排队到当前回合之后执行。
171
173
 
172
- Set \`responseMode\` in channel.json to control output shape: \`full_progress_then_plain_final\` (default) streams full progress then sends a plain final message; \`rolling_progress_then_plain_final\` shows only the most recent progress entries, then a short summary; \`final_card_only\` hides progress and delivers the final answer in the AI Card.
174
+ channel.json 的 \`responseMode\` 控制输出形态:\`full_progress_then_plain_final\`(默认)流式展示完整进度,再发一条纯文本结论;\`rolling_progress_then_plain_final\` 只保留最近几条进度,收尾给一行摘要;\`final_card_only\` 隐藏进度,只在 AI 卡片里给最终结果。
173
175
 
174
- ## Session Commands
176
+ ## 会话层命令
175
177
 
176
- These are handled inside the Pipiclaw session layer:
178
+ 由 Pipiclaw 会话层处理,需要在空闲时使用:
177
179
 
178
180
  ${session}
179
181
  `;
@@ -1,11 +1,32 @@
1
1
  export declare function noteChannelEffect(channelId: string): void;
2
2
  export declare function channelEffectCount(channelId: string): number;
3
+ /**
4
+ * Credit one task-driver turn's effects to that task.
5
+ *
6
+ * The channel tally above answers "how much has happened here", which is the wrong question for
7
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
8
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
9
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
10
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
11
+ */
12
+ export declare function noteTaskEffects(channelId: string, taskId: string, delta: number): void;
13
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
14
+ export declare function taskEffectCount(channelId: string, taskId: string): number;
3
15
  /** Test seam: drop all tallies. */
4
16
  export declare function resetChannelEffects(): void;
5
17
  /**
6
- * Whether a completed tool call counts as an effect. `bash` is the awkward case — the same tool
7
- * runs `ls` and `rm -rf`, and the runtime cannot tell them apart — so only a background launch
8
- * (which leaves a job behind) counts. Erring toward "no effect" means a genuinely idle loop is
9
- * still caught; erring the other way would let any wake claim progress by running `true`.
18
+ * Whether a completed tool call counts as an effect.
19
+ *
20
+ * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
21
+ * them apart. It used to count only a background launch, which produced the wrong answer for the
22
+ * single most important shape this runtime has — a turn that synchronously drives an external
23
+ * coding agent, then records what came back. That turn changes no file the runtime can see and
24
+ * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task paused
25
+ * by the governor: the hardest-working wake was the one most likely to be judged idle.
26
+ *
27
+ * A synchronous command that exited 0 and returned output therefore counts too. That is
28
+ * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
29
+ * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
30
+ * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
10
31
  */
11
32
  export declare function isEffectfulTool(toolName: string, details: unknown): boolean;
@@ -14,8 +14,12 @@ import { isRecord } from "../shared/type-guards.js";
14
14
  *
15
15
  * The tally lives in process memory, exactly like the driver's futile counter it feeds; a restart
16
16
  * resets both, which costs at most one extra round of patience before the governor intervenes.
17
+ *
18
+ * Two tallies are kept: one per channel (raw, the measurement point) and one per task, credited
19
+ * a turn at a time by the runtime. The governor reads the second — see `noteTaskEffects`.
17
20
  */
18
21
  const counts = new Map();
22
+ const taskCounts = new Map();
19
23
  /** Tools whose successful completion is, by itself, a visible change to the world. */
20
24
  const EFFECT_TOOLS = new Set(["write", "edit", "send_media", "subagent"]);
21
25
  export function noteChannelEffect(channelId) {
@@ -24,19 +28,55 @@ export function noteChannelEffect(channelId) {
24
28
  export function channelEffectCount(channelId) {
25
29
  return counts.get(channelId) ?? 0;
26
30
  }
31
+ function taskKey(channelId, taskId) {
32
+ return `${channelId}\0${taskId}`;
33
+ }
34
+ /**
35
+ * Credit one task-driver turn's effects to that task.
36
+ *
37
+ * The channel tally above answers "how much has happened here", which is the wrong question for
38
+ * the governor: it also counts the user's small talk, so every task in a busy channel looked like
39
+ * it had just made progress (continue at once, futile counter reset) while a genuinely spinning
40
+ * task hid behind its neighbours. The caller measures one turn as a delta of the channel tally —
41
+ * turns are serialized per channel — and credits it to the task that turn was dispatched for.
42
+ */
43
+ export function noteTaskEffects(channelId, taskId, delta) {
44
+ if (delta <= 0)
45
+ return;
46
+ const key = taskKey(channelId, taskId);
47
+ taskCounts.set(key, (taskCounts.get(key) ?? 0) + delta);
48
+ }
49
+ /** Effects produced by this task's own driver turns so far (spec 031, D7). */
50
+ export function taskEffectCount(channelId, taskId) {
51
+ return taskCounts.get(taskKey(channelId, taskId)) ?? 0;
52
+ }
27
53
  /** Test seam: drop all tallies. */
28
54
  export function resetChannelEffects() {
29
55
  counts.clear();
56
+ taskCounts.clear();
30
57
  }
31
58
  /**
32
- * Whether a completed tool call counts as an effect. `bash` is the awkward case — the same tool
33
- * runs `ls` and `rm -rf`, and the runtime cannot tell them apart — so only a background launch
34
- * (which leaves a job behind) counts. Erring toward "no effect" means a genuinely idle loop is
35
- * still caught; erring the other way would let any wake claim progress by running `true`.
59
+ * Whether a completed tool call counts as an effect.
60
+ *
61
+ * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
62
+ * them apart. It used to count only a background launch, which produced the wrong answer for the
63
+ * single most important shape this runtime has — a turn that synchronously drives an external
64
+ * coding agent, then records what came back. That turn changes no file the runtime can see and
65
+ * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task paused
66
+ * by the governor: the hardest-working wake was the one most likely to be judged idle.
67
+ *
68
+ * A synchronous command that exited 0 and returned output therefore counts too. That is
69
+ * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
70
+ * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
71
+ * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
36
72
  */
37
73
  export function isEffectfulTool(toolName, details) {
38
74
  if (toolName === "bash") {
39
- return isRecord(details) && details.async !== undefined;
75
+ if (!isRecord(details))
76
+ return false;
77
+ if (details.async !== undefined)
78
+ return true;
79
+ return details.exitCode === 0 && details.producedOutput === true;
40
80
  }
41
81
  return EFFECT_TOOLS.has(toolName);
42
82
  }
@@ -82,6 +82,8 @@ export declare class ChannelJobManager {
82
82
  private collectGarbage;
83
83
  get channel(): string;
84
84
  runningCount(): number;
85
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
86
+ runningTaskIds(): Set<string>;
85
87
  /**
86
88
  * Launch a command in the background and return its job id. The wrapper writes merged
87
89
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -95,6 +97,13 @@ export declare class ChannelJobManager {
95
97
  private ensureSweeper;
96
98
  private stopSweeper;
97
99
  private sweep;
100
+ /**
101
+ * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
102
+ *
103
+ * Each job contributes one branch that reads its exit-code file if present and otherwise checks
104
+ * PID liveness — exactly what the single-job probe did, just batched.
105
+ */
106
+ private probeAll;
98
107
  /**
99
108
  * Refresh the status of a single running job by consulting its `.exit` file and liveness.
100
109
  *
@@ -103,6 +112,8 @@ export declare class ChannelJobManager {
103
112
  * to say nothing.
104
113
  */
105
114
  private refresh;
115
+ /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
116
+ private applyProbe;
106
117
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
107
118
  private finish;
108
119
  /**
@@ -147,6 +158,15 @@ interface JobRuntimeConfig {
147
158
  * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
148
159
  */
149
160
  export declare function configureJobRuntime(config: JobRuntimeConfig): void;
161
+ /**
162
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
163
+ *
164
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
165
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
166
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
167
+ * manager simply has no jobs, and the empty set is the right answer.
168
+ */
169
+ export declare function channelJobTaskIds(channelId: string): Set<string>;
150
170
  export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
151
171
  /**
152
172
  * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
@@ -119,6 +119,16 @@ export class ChannelJobManager {
119
119
  runningCount() {
120
120
  return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
121
121
  }
122
+ /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
123
+ runningTaskIds() {
124
+ const ids = new Set();
125
+ for (const job of this.jobs.values()) {
126
+ if (job.status === "running" && job.contract.notify && job.contract.taskId) {
127
+ ids.add(job.contract.taskId);
128
+ }
129
+ }
130
+ return ids;
131
+ }
122
132
  /**
123
133
  * Launch a command in the background and return its job id. The wrapper writes merged
124
134
  * stdout/stderr to a spill file and the command's exit code to a sibling `.exit` file, then
@@ -190,12 +200,14 @@ export class ChannelJobManager {
190
200
  }
191
201
  this.sweeping = true;
192
202
  try {
193
- for (const record of this.jobs.values()) {
194
- if (record.status === "running") {
195
- await this.refresh(record).catch((error) => {
196
- log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
197
- });
198
- }
203
+ const running = Array.from(this.jobs.values()).filter((record) => record.status === "running");
204
+ // One shell for the whole sweep, not one per job: the sweeper runs every 10s for as
205
+ // long as any job lives, so per-job spawns are the steady-state cost of backgrounding.
206
+ const probes = await this.probeAll(running);
207
+ for (const record of running) {
208
+ await this.applyProbe(record, probes.get(record.id) ?? "").catch((error) => {
209
+ log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
210
+ });
199
211
  }
200
212
  await this.collectGarbage();
201
213
  }
@@ -206,6 +218,35 @@ export class ChannelJobManager {
206
218
  }
207
219
  }
208
220
  }
221
+ /**
222
+ * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
223
+ *
224
+ * Each job contributes one branch that reads its exit-code file if present and otherwise checks
225
+ * PID liveness — exactly what the single-job probe did, just batched.
226
+ */
227
+ async probeAll(records, signal) {
228
+ const states = new Map();
229
+ if (records.length === 0) {
230
+ return states;
231
+ }
232
+ const script = records
233
+ .map((record) => {
234
+ const id = shellEscape(record.id);
235
+ const exitFile = shellEscape(record.exitFile);
236
+ return (`if [ -f ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; ` +
237
+ `elif kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; ` +
238
+ `else printf '%s GONE\\n' ${id}; fi`);
239
+ })
240
+ .join("\n");
241
+ const probe = await this.executor.exec(script, { signal });
242
+ for (const line of probe.stdout.split("\n")) {
243
+ const separator = line.indexOf(" ");
244
+ if (separator <= 0)
245
+ continue;
246
+ states.set(line.slice(0, separator), line.slice(separator + 1).trim());
247
+ }
248
+ return states;
249
+ }
209
250
  /**
210
251
  * Refresh the status of a single running job by consulting its `.exit` file and liveness.
211
252
  *
@@ -217,10 +258,14 @@ export class ChannelJobManager {
217
258
  if (record.status !== "running") {
218
259
  return;
219
260
  }
220
- // Read the exit-code file if present, and separately check whether the PID is still alive.
221
- const probe = await this.executor.exec(`if [ -f ${shellEscape(record.exitFile)} ]; then echo "EXIT:$(cat ${shellEscape(record.exitFile)})"; ` +
222
- `elif kill -0 ${record.pid} 2>/dev/null; then echo ALIVE; else echo GONE; fi`, { signal });
223
- const out = probe.stdout.trim();
261
+ const probes = await this.probeAll([record], signal);
262
+ await this.applyProbe(record, probes.get(record.id) ?? "", signal, announce);
263
+ }
264
+ /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
265
+ async applyProbe(record, out, signal, announce = true) {
266
+ if (record.status !== "running") {
267
+ return;
268
+ }
224
269
  if (out.startsWith("EXIT:")) {
225
270
  const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
226
271
  record.exitCode = Number.isFinite(code) ? code : undefined;
@@ -419,6 +464,17 @@ let runtimeConfig = {};
419
464
  export function configureJobRuntime(config) {
420
465
  runtimeConfig = config;
421
466
  }
467
+ /**
468
+ * Which of this channel's tasks a running background job will wake, without needing an `Executor`.
469
+ *
470
+ * Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
471
+ * something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
472
+ * startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
473
+ * manager simply has no jobs, and the empty set is the right answer.
474
+ */
475
+ export function channelJobTaskIds(channelId) {
476
+ return managers.get(channelId)?.runningTaskIds() ?? new Set();
477
+ }
422
478
  export function getChannelJobManager(channelId, executor) {
423
479
  let manager = managers.get(channelId);
424
480
  if (!manager) {
@@ -46,6 +46,7 @@ export async function loadDetachedMaintenanceContext(options) {
46
46
  }
47
47
  transcriptCache.set(options.channelDir, cached);
48
48
  }
49
+ const cachedTranscript = cached;
49
50
  const modelRuntime = await createModelRuntime({
50
51
  authConfigPath: options.authConfigPath,
51
52
  modelsConfigPath: options.modelsConfigPath,
@@ -56,8 +57,8 @@ export async function loadDetachedMaintenanceContext(options) {
56
57
  return {
57
58
  channelId: options.channelId,
58
59
  channelDir: options.channelDir,
59
- messages: [...cached.messages],
60
- sessionEntries: [...cached.sessionEntries],
60
+ messages: () => [...cachedTranscript.messages],
61
+ sessionEntries: () => [...cachedTranscript.sessionEntries],
61
62
  model,
62
63
  resolveApiKey: async (candidate) => getApiKeyForModel(modelRegistry, candidate),
63
64
  settings: {
@@ -1,4 +1,13 @@
1
1
  import type { ProgressEntryKind } from "./types.js";
2
- export declare function clipUserInput(text: string, maxChars: number): string;
2
+ /**
3
+ * Head + tail of an over-length message, with the middle replaced by a marker.
4
+ *
5
+ * `fullTextPath` matters more than it looks: the dropped middle of a pasted build log is exactly
6
+ * where the failing stack trace lives, so a marker that only says "omitted" hands the model a
7
+ * mutilated input and no way to notice. When the caller managed to persist the original, the
8
+ * marker names it and says how to read it (the same next-step rule every other truncated output
9
+ * in this runtime follows).
10
+ */
11
+ export declare function clipUserInput(text: string, maxChars: number, fullTextPath?: string): string;
3
12
  export declare function formatProgressEntry(kind: ProgressEntryKind, text: string): string;
4
13
  export declare function extractToolResultText(result: unknown): string;