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

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 (43) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +46 -13
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +13 -4
  5. package/dist/agent/effect-ledger.js +18 -5
  6. package/dist/agent/job-manager.d.ts +9 -0
  7. package/dist/agent/job-manager.js +45 -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/executor.d.ts +2 -0
  12. package/dist/executor.js +1 -0
  13. package/dist/memory/maintenance-gates.d.ts +24 -10
  14. package/dist/memory/maintenance-gates.js +11 -9
  15. package/dist/memory/maintenance-jobs.d.ts +3 -2
  16. package/dist/memory/maintenance-jobs.js +33 -21
  17. package/dist/memory/scheduler.d.ts +7 -2
  18. package/dist/playbooks/task-closeout.md +2 -0
  19. package/dist/playbooks/task-delegation.md +12 -8
  20. package/dist/playbooks/task-driving.md +2 -2
  21. package/dist/playbooks/task-planning.md +1 -1
  22. package/dist/runtime/bootstrap.js +7 -4
  23. package/dist/runtime/delivery.js +31 -6
  24. package/dist/runtime/dingtalk.d.ts +9 -1
  25. package/dist/runtime/dingtalk.js +7 -4
  26. package/dist/runtime/task-commands.js +130 -53
  27. package/dist/runtime/task-driver.js +38 -9
  28. package/dist/shared/task-ledger.js +19 -3
  29. package/dist/subagents/tool.d.ts +1 -0
  30. package/dist/subagents/tool.js +33 -3
  31. package/dist/tasks/control.d.ts +1 -0
  32. package/dist/tasks/control.js +2 -2
  33. package/dist/tasks/verification.d.ts +8 -0
  34. package/dist/tasks/verification.js +4 -1
  35. package/dist/tools/bash.js +12 -12
  36. package/dist/tools/task-manage/lifecycle.js +6 -3
  37. package/dist/tools/task-manage/verification.d.ts +2 -1
  38. package/dist/tools/task-manage/verification.js +2 -1
  39. package/dist/tui/turn-controller.js +3 -3
  40. package/dist/usage/ledger.d.ts +2 -0
  41. package/dist/usage/ledger.js +7 -2
  42. package/dist/usage/render.js +17 -8
  43. 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
@@ -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: {
@@ -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);
@@ -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
  `;
@@ -3,9 +3,18 @@ export declare function channelEffectCount(channelId: string): number;
3
3
  /** Test seam: drop all tallies. */
4
4
  export declare function resetChannelEffects(): void;
5
5
  /**
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`.
6
+ * Whether a completed tool call counts as an effect.
7
+ *
8
+ * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
9
+ * them apart. It used to count only a background launch, which produced the wrong answer for the
10
+ * single most important shape this runtime has — a turn that synchronously drives an external
11
+ * coding agent, then records what came back. That turn changes no file the runtime can see and
12
+ * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task paused
13
+ * by the governor: the hardest-working wake was the one most likely to be judged idle.
14
+ *
15
+ * A synchronous command that exited 0 and returned output therefore counts too. That is
16
+ * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
17
+ * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
18
+ * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
10
19
  */
11
20
  export declare function isEffectfulTool(toolName: string, details: unknown): boolean;
@@ -29,14 +29,27 @@ export function resetChannelEffects() {
29
29
  counts.clear();
30
30
  }
31
31
  /**
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`.
32
+ * Whether a completed tool call counts as an effect.
33
+ *
34
+ * `bash` is the awkward case: the same tool runs `ls` and `rm -rf`, and the runtime cannot tell
35
+ * them apart. It used to count only a background launch, which produced the wrong answer for the
36
+ * single most important shape this runtime has — a turn that synchronously drives an external
37
+ * coding agent, then records what came back. That turn changes no file the runtime can see and
38
+ * usually ends `[SILENT]`, so it scored zero effects and, after three of them, got its task paused
39
+ * by the governor: the hardest-working wake was the one most likely to be judged idle.
40
+ *
41
+ * A synchronous command that exited 0 and returned output therefore counts too. That is
42
+ * bypassable — `echo x` qualifies — but the alternative was a false negative on real work, and the
43
+ * counter never was the stop-loss: `budget.maxAttempts` bounds a task no matter how productive it
44
+ * claims to look. What "futile" now means is the honest thing: a wake that executed nothing at all.
36
45
  */
37
46
  export function isEffectfulTool(toolName, details) {
38
47
  if (toolName === "bash") {
39
- return isRecord(details) && details.async !== undefined;
48
+ if (!isRecord(details))
49
+ return false;
50
+ if (details.async !== undefined)
51
+ return true;
52
+ return details.exitCode === 0 && details.producedOutput === true;
40
53
  }
41
54
  return EFFECT_TOOLS.has(toolName);
42
55
  }
@@ -95,6 +95,13 @@ export declare class ChannelJobManager {
95
95
  private ensureSweeper;
96
96
  private stopSweeper;
97
97
  private sweep;
98
+ /**
99
+ * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
100
+ *
101
+ * Each job contributes one branch that reads its exit-code file if present and otherwise checks
102
+ * PID liveness — exactly what the single-job probe did, just batched.
103
+ */
104
+ private probeAll;
98
105
  /**
99
106
  * Refresh the status of a single running job by consulting its `.exit` file and liveness.
100
107
  *
@@ -103,6 +110,8 @@ export declare class ChannelJobManager {
103
110
  * to say nothing.
104
111
  */
105
112
  private refresh;
113
+ /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
114
+ private applyProbe;
106
115
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
107
116
  private finish;
108
117
  /**
@@ -190,12 +190,14 @@ export class ChannelJobManager {
190
190
  }
191
191
  this.sweeping = true;
192
192
  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
- }
193
+ const running = Array.from(this.jobs.values()).filter((record) => record.status === "running");
194
+ // One shell for the whole sweep, not one per job: the sweeper runs every 10s for as
195
+ // long as any job lives, so per-job spawns are the steady-state cost of backgrounding.
196
+ const probes = await this.probeAll(running);
197
+ for (const record of running) {
198
+ await this.applyProbe(record, probes.get(record.id) ?? "").catch((error) => {
199
+ log.logWarning(`Background job sweep failed to refresh job ${record.id}`, errorMessage(error));
200
+ });
199
201
  }
200
202
  await this.collectGarbage();
201
203
  }
@@ -206,6 +208,35 @@ export class ChannelJobManager {
206
208
  }
207
209
  }
208
210
  }
211
+ /**
212
+ * Probe every given job in one shell invocation, returning `id → EXIT:<code>|ALIVE|GONE`.
213
+ *
214
+ * Each job contributes one branch that reads its exit-code file if present and otherwise checks
215
+ * PID liveness — exactly what the single-job probe did, just batched.
216
+ */
217
+ async probeAll(records, signal) {
218
+ const states = new Map();
219
+ if (records.length === 0) {
220
+ return states;
221
+ }
222
+ const script = records
223
+ .map((record) => {
224
+ const id = shellEscape(record.id);
225
+ const exitFile = shellEscape(record.exitFile);
226
+ return (`if [ -f ${exitFile} ]; then printf '%s EXIT:%s\\n' ${id} "$(cat ${exitFile})"; ` +
227
+ `elif kill -0 ${record.pid} 2>/dev/null; then printf '%s ALIVE\\n' ${id}; ` +
228
+ `else printf '%s GONE\\n' ${id}; fi`);
229
+ })
230
+ .join("\n");
231
+ const probe = await this.executor.exec(script, { signal });
232
+ for (const line of probe.stdout.split("\n")) {
233
+ const separator = line.indexOf(" ");
234
+ if (separator <= 0)
235
+ continue;
236
+ states.set(line.slice(0, separator), line.slice(separator + 1).trim());
237
+ }
238
+ return states;
239
+ }
209
240
  /**
210
241
  * Refresh the status of a single running job by consulting its `.exit` file and liveness.
211
242
  *
@@ -217,10 +248,14 @@ export class ChannelJobManager {
217
248
  if (record.status !== "running") {
218
249
  return;
219
250
  }
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();
251
+ const probes = await this.probeAll([record], signal);
252
+ await this.applyProbe(record, probes.get(record.id) ?? "", signal, announce);
253
+ }
254
+ /** Turn one probe result into a status transition; an unrecognized result only ages the job. */
255
+ async applyProbe(record, out, signal, announce = true) {
256
+ if (record.status !== "running") {
257
+ return;
258
+ }
224
259
  if (out.startsWith("EXIT:")) {
225
260
  const code = Number.parseInt(out.slice("EXIT:".length).trim(), 10);
226
261
  record.exitCode = Number.isFinite(code) ? code : undefined;
@@ -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;
@@ -4,14 +4,26 @@ function sanitizeProgressText(text) {
4
4
  .replace(/\r/g, "")
5
5
  .trim();
6
6
  }
7
- export function clipUserInput(text, maxChars) {
7
+ /**
8
+ * Head + tail of an over-length message, with the middle replaced by a marker.
9
+ *
10
+ * `fullTextPath` matters more than it looks: the dropped middle of a pasted build log is exactly
11
+ * where the failing stack trace lives, so a marker that only says "omitted" hands the model a
12
+ * mutilated input and no way to notice. When the caller managed to persist the original, the
13
+ * marker names it and says how to read it (the same next-step rule every other truncated output
14
+ * in this runtime follows).
15
+ */
16
+ export function clipUserInput(text, maxChars, fullTextPath) {
8
17
  const normalized = text.replace(/\r/g, "").trim();
9
18
  if (normalized.length <= maxChars) {
10
19
  return normalized;
11
20
  }
12
21
  const headChars = Math.floor(maxChars * 0.6);
13
22
  const tailChars = maxChars - headChars;
14
- return `${normalized.slice(0, headChars)}\n\n[... omitted ${normalized.length - maxChars} chars ...]\n\n${normalized.slice(-tailChars)}`;
23
+ const recovery = fullTextPath
24
+ ? `; the complete message is saved at ${fullTextPath} — page through it with the read tool before drawing conclusions about the omitted part`
25
+ : "";
26
+ return `${normalized.slice(0, headChars)}\n\n[... omitted ${normalized.length - maxChars} chars${recovery} ...]\n\n${normalized.slice(-tailChars)}`;
15
27
  }
16
28
  export function formatProgressEntry(kind, text) {
17
29
  const cleaned = sanitizeProgressText(text);
@@ -12,6 +12,8 @@ export interface ExecOptions {
12
12
  timeout?: number;
13
13
  signal?: AbortSignal;
14
14
  stdin?: string;
15
+ /** Directory to run the command in. Defaults to the daemon's own working directory. */
16
+ cwd?: string;
15
17
  }
16
18
  export interface ExecResult {
17
19
  stdout: string;
package/dist/executor.js CHANGED
@@ -13,6 +13,7 @@ class HostExecutor {
13
13
  return spawn("sh", ["-c", command], {
14
14
  detached: true,
15
15
  stdio: ["pipe", "pipe", "pipe"],
16
+ ...(options?.cwd ? { cwd: options.cwd } : {}),
16
17
  });
17
18
  }
18
19
  catch (err) {
@@ -6,39 +6,53 @@ export interface MaintenanceGateDecision {
6
6
  skipReason?: string;
7
7
  jobKind: MaintenanceJobKind;
8
8
  }
9
+ /**
10
+ * Material checks are passed as thunks, never as values.
11
+ *
12
+ * Every gate below decides on cheap state (settings, timestamps, idle/backoff windows) before it
13
+ * looks at any material, and the material is expensive to produce: scanning the whole transcript,
14
+ * building the incremental source window, reading MEMORY.md/HISTORY.md. Evaluating it up front is
15
+ * what made an idle daemon pay a real cost on every one-minute tick just to be denied.
16
+ */
9
17
  export interface SessionRefreshGateInput {
10
18
  now: Date;
11
19
  state: MemoryMaintenanceState;
12
20
  sessionMemory: PipiclawSessionMemorySettings;
13
21
  maintenance: PipiclawMemoryMaintenanceSettings;
14
22
  channelActive: boolean;
15
- hasNewSessionEntry: boolean;
16
- hasMeaningfulMaterial: boolean;
23
+ hasNewSessionEntry: () => boolean;
24
+ hasMeaningfulMaterial: () => boolean;
17
25
  }
18
- export interface MemoryCheckpointGateInput {
19
- now: Date;
20
- state: MemoryMaintenanceState;
21
- maintenance: PipiclawMemoryMaintenanceSettings;
22
- channelActive: boolean;
26
+ export interface MemoryCheckpointMaterial {
23
27
  hasNewEntry: boolean;
24
28
  hasMeaningfulExchange: boolean;
25
29
  batchSize: number;
26
- minBatchSize?: number;
27
30
  }
28
- export interface StructuralMaintenanceGateInput {
31
+ export interface MemoryCheckpointGateInput {
29
32
  now: Date;
30
33
  state: MemoryMaintenanceState;
31
34
  maintenance: PipiclawMemoryMaintenanceSettings;
32
35
  channelActive: boolean;
36
+ material: () => MemoryCheckpointMaterial;
37
+ minBatchSize?: number;
38
+ }
39
+ export interface StructuralMaintenanceMaterial {
33
40
  memoryCleanupNeeded: boolean;
34
41
  historyFoldingNeeded: boolean;
35
42
  hasMemoryContent: boolean;
36
43
  hasHistoryContent: boolean;
37
44
  }
45
+ export interface StructuralMaintenanceGateInput {
46
+ now: Date;
47
+ state: MemoryMaintenanceState;
48
+ maintenance: PipiclawMemoryMaintenanceSettings;
49
+ channelActive: boolean;
50
+ material: () => Promise<StructuralMaintenanceMaterial>;
51
+ }
38
52
  export interface StructuralMaintenanceGateDecision extends MaintenanceGateDecision {
39
53
  runMemoryCleanup: boolean;
40
54
  runHistoryFolding: boolean;
41
55
  }
42
56
  export declare function shouldRunSessionRefresh(input: SessionRefreshGateInput): MaintenanceGateDecision;
43
57
  export declare function shouldRunMemoryCheckpoint(input: MemoryCheckpointGateInput): MaintenanceGateDecision;
44
- export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): StructuralMaintenanceGateDecision;
58
+ export declare function shouldRunStructuralMaintenance(input: StructuralMaintenanceGateInput): Promise<StructuralMaintenanceGateDecision>;