@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.1

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 (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -2,18 +2,25 @@ import { existsSync } from "node:fs";
2
2
  import { readdir } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { renderSubcommandUsage } from "../commands/catalog.js";
5
+ import { capReply, flattenMarkdownForChat } from "../commands/reply-limits.js";
6
+ import { docsUrl } from "../paths.js";
7
+ import { formatSpanZh } from "../shared/format.js";
5
8
  import { parseLocalTime } from "../shared/local-time.js";
6
- import { clipText, errorMessage } from "../shared/text-utils.js";
7
- import { buildTaskBoard, renderTaskBoard } from "../tasks/board.js";
9
+ import { errorMessage } from "../shared/text-utils.js";
10
+ import { buildTaskBoard, renderTaskBoardForUser } from "../tasks/board.js";
11
+ import { taskStateLabel } from "../tasks/frontmatter.js";
8
12
  import { normalizeTaskId, readActiveTasks } from "../tasks/ledger.js";
9
- import { readTaskLog, renderTaskLogLine } from "../tasks/log.js";
13
+ import { readTaskLog, renderTaskLogLineForUser, taskArchiveLogPath, taskLogIsArchived, taskLogPath, } from "../tasks/log.js";
10
14
  import { withTaskMutation } from "../tasks/mutation-lock.js";
11
15
  import { hasTaskSteer, queueTaskSteer } from "../tasks/steer.js";
12
- import { pauseTask as pauseTaskDocument, readStoredTask, redeemTicket, resumeTask as resumeTaskDocument, updateStoredTask, } from "../tasks/store.js";
13
- import { describeTicket } from "../tasks/ticket.js";
14
- /** `/tasks show <id>` head-snippet cap; the full file is always readable at its own path. */
15
- const TASK_SHOW_MAX_CHARS = 2_400;
16
- const SHOW_LOG_LINES = 8;
16
+ import { archivedTaskPath, pauseTask as pauseTaskDocument, readStoredTask, redeemTicket, resumeTask as resumeTaskDocument, taskPath, updateStoredTask, } from "../tasks/store.js";
17
+ import { describeTicketForUser } from "../tasks/ticket.js";
18
+ /** `/tasks show <id>` contract excerpt; the full file is always readable at its own path. */
19
+ const TASK_SHOW_CONTRACT_CHARS = 500;
20
+ const SHOW_LOG_LINES = 5;
21
+ /** `/tasks log <id>`: the most recent records; older ones are in the `.jsonl` it names. */
22
+ const LOG_LINES = 15;
23
+ const ARCHIVE_LIST_LIMIT = 20;
17
24
  /** A backstop this far past due means the driver is not running, not that it is merely about to act. */
18
25
  const EXPIRED_GRACE_MS = 60 * 60 * 1000;
19
26
  // Broadcast (subcommand names, args, descriptions, examples) lives once in commands/catalog.ts's
@@ -67,50 +74,39 @@ export function parseTasksCommand(args) {
67
74
  throw new Error(`用法:/tasks ${action} <id> <内容>`);
68
75
  return { action, id: match[1], text: match[2].trim() };
69
76
  }
70
- throw new Error(`未知的 /tasks 动作:${action}`);
77
+ throw new Error(`未知子命令 \`${action}\`。`);
71
78
  }
72
79
  function tasksDir(channelDir) {
73
80
  return join(channelDir, "tasks");
74
81
  }
75
- /** Compact relative time, e.g. `12m` / `3h` / `2d`; `due` when already past. */
76
- function relative(atMs, now) {
82
+ /** `(最晚 3 小时后重新检查)` — when the runtime looks at a parked task again no matter what. */
83
+ function backstopHint(by, now) {
84
+ const atMs = parseLocalTime(by);
77
85
  if (atMs === undefined || !Number.isFinite(atMs))
78
- return undefined;
86
+ return "";
79
87
  const diffMs = atMs - now;
80
- if (diffMs <= 0)
81
- return "已到期";
82
- const minutes = Math.round(diffMs / 60000);
83
- if (minutes < 60)
84
- return `${minutes}m`;
85
- const hours = Math.round(minutes / 60);
86
- if (hours < 24)
87
- return `${hours}h`;
88
- return `${Math.round(hours / 24)}d`;
88
+ return diffMs <= 0 ? "(已过最晚检查时间)" : `(最晚 ${formatSpanZh(diffMs)}后重新检查)`;
89
89
  }
90
- const STATE_LABEL = { open: "进行中", parked: "等待中", done: "已关闭" };
91
90
  function usageSummary(entry) {
92
91
  const usage = entry.fields.usage;
93
92
  if (!usage)
94
93
  return undefined;
95
- const cost = usage.usd > 0 ? `,$${usage.usd.toFixed(2)}${usage.usdEstimated ? "(含估算)" : ""}` : "";
96
- return `${usage.steps} 步${cost}`;
94
+ const cost = usage.usd > 0 ? ` · 花费 $${usage.usd.toFixed(2)}${usage.usdEstimated ? "(含估算)" : ""}` : "";
95
+ return `已用 ${usage.steps} 步${cost}`;
97
96
  }
98
97
  function ticketSummary(entry, now) {
99
98
  const ticket = entry.fields.ticket;
100
- if (!ticket)
101
- return undefined;
102
- const by = relative(parseLocalTime(ticket.by), now);
103
- return `${describeTicket(ticket)}${by ? `(兜底 ${by})` : ""}`;
99
+ return ticket ? `${describeTicketForUser(ticket)}${backstopHint(ticket.by, now)}` : undefined;
104
100
  }
105
101
  function renderListLine(entry, channelDir, now) {
106
- const bits = [`${entry.id} — ${entry.title}`, STATE_LABEL[entry.fields.state] ?? entry.fields.state];
102
+ const bits = [`\`${entry.id}\` ${entry.title}`, taskStateLabel(entry.fields.state)];
107
103
  if (entry.fields.paused)
108
104
  bits.push(`已暂停(${entry.fields.paused.reason})`);
109
105
  const ticket = ticketSummary(entry, now);
110
106
  if (ticket)
111
107
  bits.push(ticket);
112
108
  if (entry.items)
113
- bits.push(`items ${entry.items.done}/${entry.items.total}`);
109
+ bits.push(`工作项 ${entry.items.done}/${entry.items.total}`);
114
110
  if (entry.fields.origin)
115
111
  bits.push(`来自 ${entry.fields.origin}`);
116
112
  const usage = usageSummary(entry);
@@ -119,31 +115,51 @@ function renderListLine(entry, channelDir, now) {
119
115
  if (hasTaskSteer(channelDir, entry.id))
120
116
  bits.push("有待处理的指示");
121
117
  if (!entry.readable)
122
- bits.push("⚠ frontmatter 不可读");
118
+ bits.push("⚠️ 文件头(frontmatter)不可读");
123
119
  return `- ${bits.join(" · ")}`;
124
120
  }
125
121
  async function listTasks(channelDir) {
126
122
  const now = Date.now();
127
123
  const entries = (await readActiveTasks(tasksDir(channelDir), now)).filter((entry) => !entry.fields.outcome);
128
124
  if (entries.length === 0) {
129
- return "暂无进行中的任务。\n让 Agent 用 task_create 建立一个长程任务后再回来查看。";
125
+ return "暂无进行中的任务。\n在对话里告诉我目标,并说明作为长程任务推进。";
130
126
  }
131
- return [`**任务(${entries.length})**`, ...entries.map((entry) => renderListLine(entry, channelDir, now))].join("\n");
127
+ const report = [
128
+ `**任务(${entries.length})**`,
129
+ ...entries.map((entry) => renderListLine(entry, channelDir, now)),
130
+ ].join("\n");
131
+ return capReply(report, { nextStepHint: "用 `/tasks show <id>` 查看单个任务" }).text;
132
+ }
133
+ function notFound(id) {
134
+ return `未找到任务 \`${id}\`。用 \`/tasks\` 查看进行中的任务,或 \`/tasks archive\` 查看已归档的。`;
135
+ }
136
+ /** The head of the contract, reshaped for chat and cut on a line boundary; the full file is one path away. */
137
+ function contractExcerpt(body, maxChars) {
138
+ const flat = flattenMarkdownForChat(body.trim());
139
+ if (flat.length <= maxChars)
140
+ return { text: flat, clipped: false };
141
+ const cut = flat.lastIndexOf("\n", maxChars);
142
+ const head = flat.slice(0, cut > 0 ? cut : maxChars).trimEnd();
143
+ // A cut inside a fenced block would leave the rest of the reply rendered as code.
144
+ const openFence = (head.match(/^```/gm)?.length ?? 0) % 2 === 1;
145
+ return { text: openFence ? `${head}\n\`\`\`` : head, clipped: true };
132
146
  }
133
147
  async function showTask(channelDir, idInput) {
134
148
  const id = normalizeTaskId(idInput);
135
149
  const document = (await readStoredTask(channelDir, id, true)) ?? undefined;
136
150
  if (!document)
137
- return `未找到任务 \`${id}\`。\n用 /tasks list 查看进行中的任务,或 /tasks archive 查看已归档的。`;
151
+ return notFound(id);
138
152
  const now = Date.now();
139
153
  const entry = (await readActiveTasks(tasksDir(channelDir), now)).find((candidate) => candidate.id === id);
140
154
  const head = [`**任务 ${id}**`];
141
- head.push(`- 状态:${STATE_LABEL[document.fields.state] ?? document.fields.state}`);
142
- if (document.fields.paused)
143
- head.push(`- 已暂停(${document.fields.paused.by}):${document.fields.paused.reason}`);
155
+ head.push(`- 状态:${taskStateLabel(document.fields.state)}`);
156
+ if (document.fields.paused) {
157
+ const by = document.fields.paused.by === "user" ? "由你暂停" : "由系统暂停";
158
+ head.push(`- 已暂停(${by}):${document.fields.paused.reason}`);
159
+ }
144
160
  if (document.fields.ticket) {
145
- const by = relative(parseLocalTime(document.fields.ticket.by), now);
146
- head.push(`- 等待:${describeTicket(document.fields.ticket)}${by ? `(兜底 ${by})` : ""}`);
161
+ const ticket = document.fields.ticket;
162
+ head.push(`- 等待:${describeTicketForUser(ticket)}${backstopHint(ticket.by, now)}`);
147
163
  }
148
164
  if (document.fields.origin)
149
165
  head.push(`- 来自事件:${document.fields.origin}`);
@@ -151,15 +167,28 @@ async function showTask(channelDir, idInput) {
151
167
  if (usage)
152
168
  head.push(`- 用量:${usage}`);
153
169
  const board = await buildTaskBoard(channelDir, id, document.body);
154
- const boardLines = board ? ["", "**团队看板**", renderTaskBoard(board, now)] : [];
170
+ const boardLines = board ? ["", "**工作项**", renderTaskBoardForUser(board, id, now)] : [];
155
171
  const log = await readTaskLog(channelDir, id, {
156
172
  kinds: ["step", "expired", "close", "note"],
157
173
  limit: SHOW_LOG_LINES,
158
174
  });
159
- const logLines = log.length > 0 ? ["", `**最近 ${log.length} 条日志**`, ...log.map(renderTaskLogLine)] : [];
160
- const body = clipText(document.body.trim(), TASK_SHOW_MAX_CHARS);
161
- return [...head, ...boardLines, ...logLines, "", "**契约**", body, "", `完整日志:/tasks log ${id}`].join("\n");
175
+ const logLines = log.length > 0 ? ["", "**最近记录**", ...log.map(renderTaskLogLineForUser)] : [];
176
+ const path = existsSync(taskPath(channelDir, id)) ? taskPath(channelDir, id) : archivedTaskPath(channelDir, id);
177
+ const contract = contractExcerpt(document.body, TASK_SHOW_CONTRACT_CHARS);
178
+ const report = [
179
+ ...head,
180
+ ...boardLines,
181
+ ...logLines,
182
+ "",
183
+ "**任务说明**",
184
+ contract.text,
185
+ ...(contract.clipped ? ["(仅显示开头)"] : []),
186
+ "",
187
+ `完整记录:\`/tasks log ${id}\`;任务文件:\`${path}\``,
188
+ ].join("\n");
189
+ return capReply(report, { nextStepHint: `用 \`/tasks log ${id}\` 查看记录,完整任务说明在 \`${path}\`` }).text;
162
190
  }
191
+ const ARCHIVE_OUTCOME = { completed: "已完成", cancelled: "已取消" };
163
192
  async function listArchive(channelDir) {
164
193
  const archiveDir = join(tasksDir(channelDir), "archive");
165
194
  if (!existsSync(archiveDir))
@@ -168,21 +197,38 @@ async function listArchive(channelDir) {
168
197
  if (files.length === 0)
169
198
  return "暂无已归档任务。\n任务完成或取消后会出现在这里。";
170
199
  const lines = [];
171
- for (const filename of files.slice(0, 20)) {
200
+ for (const filename of files.slice(0, ARCHIVE_LIST_LIMIT)) {
172
201
  const id = filename.slice(0, -".md".length);
173
202
  const document = await readStoredTask(channelDir, id, true).catch(() => undefined);
174
- lines.push(`- ${id}${document?.fields.outcome ? ` · ${document.fields.outcome}` : ""}${document?.fields.closedAt ? ` · ${document.fields.closedAt}` : ""}`);
203
+ const outcome = document?.fields.outcome;
204
+ const bits = [`\`${id}\``];
205
+ if (outcome)
206
+ bits.push(ARCHIVE_OUTCOME[outcome] ?? outcome);
207
+ if (document?.fields.closedAt)
208
+ bits.push(document.fields.closedAt.slice(0, 16).replace("T", " "));
209
+ lines.push(`- ${bits.join(" · ")}`);
210
+ }
211
+ if (files.length > ARCHIVE_LIST_LIMIT) {
212
+ lines.push(`- 另有 ${files.length - ARCHIVE_LIST_LIMIT} 个,在 \`${archiveDir}\``);
175
213
  }
176
- if (files.length > 20)
177
- lines.push(`- (另有 ${files.length - 20} 个,见 tasks/archive/)`);
178
- return [`**已归档任务(${files.length})**`, ...lines].join("\n");
214
+ return capReply([`**已归档任务(${files.length})**`, ...lines].join("\n"), {
215
+ nextStepHint: `完整列表在 \`${archiveDir}\``,
216
+ }).text;
179
217
  }
180
218
  async function showTaskLog(channelDir, idInput) {
181
219
  const id = normalizeTaskId(idInput);
182
- const records = await readTaskLog(channelDir, id, { limit: 30 });
183
- if (records.length === 0)
184
- return `任务 \`${id}\` 暂无循环日志。`;
185
- return [`**任务 ${id} 日志(${records.length} 条)**`, ...records.map(renderTaskLogLine)].join("\n");
220
+ const all = await readTaskLog(channelDir, id);
221
+ if (all.length === 0)
222
+ return `任务 \`${id}\` 暂无记录。\n任务执行第一步后会出现在这里。`;
223
+ const records = all.slice(-LOG_LINES);
224
+ const path = taskLogIsArchived(channelDir, id) ? taskArchiveLogPath(channelDir, id) : taskLogPath(channelDir, id);
225
+ const lines = [
226
+ `**任务 ${id} 的记录(最近 ${records.length} 条,共 ${all.length} 条)**`,
227
+ ...records.map(renderTaskLogLineForUser),
228
+ ];
229
+ if (all.length > records.length)
230
+ lines.push("", `更早的记录在 \`${path}\``);
231
+ return capReply(lines.join("\n"), { nextStepHint: `完整记录在 \`${path}\`` }).text;
186
232
  }
187
233
  async function pauseTask(options, idInput) {
188
234
  const id = normalizeTaskId(idInput);
@@ -191,14 +237,14 @@ async function pauseTask(options, idInput) {
191
237
  reason: "用户通过 /tasks pause 暂停。",
192
238
  });
193
239
  if (!document)
194
- return `未找到任务 \`${id}\`。`;
195
- return `已暂停任务 \`${id}\`。当前阶段与等待票已保留;需要继续时用 /tasks resume ${id}。`;
240
+ return notFound(id);
241
+ return `已暂停任务 \`${id}\`,等待条件已保留;需要继续时用 \`/tasks resume ${id}\`。`;
196
242
  }
197
243
  export async function resumeTask(options, idInput, grants = {}) {
198
244
  const id = normalizeTaskId(idInput);
199
245
  const document = await resumeTaskDocument(options.channelDir, id);
200
246
  if (!document)
201
- return `未找到任务 \`${id}\`。`;
247
+ return notFound(id);
202
248
  const granted = [];
203
249
  if (Object.keys(grants).length > 0) {
204
250
  await updateStoredTask(options.channelDir, id, (task) => {
@@ -212,20 +258,20 @@ export async function resumeTask(options, idInput, grants = {}) {
212
258
  // on the next step.
213
259
  const spent = key === "steps" ? task.fields.usage?.steps : task.fields.usage?.usd;
214
260
  budget[key] = (spent ?? 0) + extra;
215
- granted.push(`${key}+${extra}`);
261
+ granted.push(key === "steps" ? `${extra} 步` : `$${extra}`);
216
262
  }
217
263
  task.fields.budget = budget;
218
264
  });
219
265
  }
220
- return `已恢复任务 \`${id}\`${granted.length > 0 ? `(${granted.join(",")})` : ""}。`;
266
+ return `已恢复任务 \`${id}\`${granted.length > 0 ? `,追加预算 ${granted.join("、")}` : ""}。`;
221
267
  }
222
268
  async function steerTask(options, idInput, text) {
223
269
  const id = normalizeTaskId(idInput);
224
270
  const document = await readStoredTask(options.channelDir, id);
225
271
  if (!document)
226
- return `未找到任务 \`${id}\`。`;
272
+ return notFound(id);
227
273
  await queueTaskSteer(options.channelDir, id, text);
228
- return `已把这条指示排给任务 \`${id}\` 的下一步(不会打断当前正在跑的一步)。`;
274
+ return `已把这条指示排给任务 \`${id}\` 的下一步,不会打断正在执行的这一步。`;
229
275
  }
230
276
  /**
231
277
  * Answer an `ask` ticket: the reply becomes the next step's first input, and redeeming the ticket
@@ -236,7 +282,7 @@ async function replyToTask(options, idInput, text) {
236
282
  const id = normalizeTaskId(idInput);
237
283
  const document = await readStoredTask(options.channelDir, id);
238
284
  if (!document)
239
- return `未找到任务 \`${id}\`。`;
285
+ return notFound(id);
240
286
  await queueTaskSteer(options.channelDir, id, text, "用户回答");
241
287
  const redeemed = await redeemTicket(options.channelDir, id, (ticket) => ticket.kind === "ask");
242
288
  if (!redeemed) {
@@ -262,19 +308,19 @@ async function doctor(options) {
262
308
  const problems = [];
263
309
  for (const entry of entries) {
264
310
  if (!entry.readable) {
265
- problems.push(issue(`${entry.id} 的 frontmatter 不可读`, `用 edit 修复 tasks/${entry.id}.md 的首部`));
311
+ problems.push(issue(`\`${entry.id}\` 的文件头(frontmatter)不可读`, `让我修复 \`${taskPath(options.channelDir, entry.id)}\` 的文件头,或手动修改`));
266
312
  continue;
267
313
  }
268
314
  if (entry.legacy) {
269
- problems.push(issue(`${entry.id} 仍含旧版本的字段(status / enabled / control / wake / schedule)`, "保留原件,按 docs/events-and-tasks.md 的升级步骤处理;不要仅删旧字段"));
315
+ problems.push(issue(`\`${entry.id}\` 仍含旧版本的字段(status / enabled / control / wake / schedule)`, `保留原件,按 ${docsUrl("events-and-tasks.md")} 的升级步骤处理;不要只删旧字段`));
270
316
  }
271
317
  const by = entry.fields.ticket ? parseLocalTime(entry.fields.ticket.by) : undefined;
272
318
  if (entry.expired && !entry.fields.paused && by !== undefined && by < now - EXPIRED_GRACE_MS) {
273
- problems.push(issue(`${entry.id} 的等待票已过兜底时限超过 1 小时`, "driver 本该重开或通知;检查 daemon 是否在跑"));
319
+ problems.push(issue(`\`${entry.id}\` 的等待条件已超过最晚检查时间 1 小时以上`, "自动调度本该重新开始或通知;请部署者确认服务器上的 pipiclaw 仍在运行"));
274
320
  }
275
321
  }
276
322
  if (problems.length === 0)
277
- return `**任务体检**\n- ${entries.length} 个任务,未发现问题。`;
323
+ return `检查了 ${entries.length} 个任务,未发现问题。`;
278
324
  return [`**任务体检(${problems.length} 项)**`, ...problems].join("\n");
279
325
  }
280
326
  export async function handleTasksCommand(options) {
@@ -1,6 +1,7 @@
1
1
  import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import { type DiscoverOptions } from "../channel/channel-index.js";
3
3
  import { type PipiclawTaskDriverSettings } from "../settings.js";
4
+ import { type BudgetBreach } from "../tasks/budget.js";
4
5
  import { type TaskLedgerEntry } from "../tasks/ledger.js";
5
6
  export interface TaskDriverOptions {
6
7
  workspaceDir: string;
@@ -29,9 +30,10 @@ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedg
29
30
  /**
30
31
  * The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
31
32
  * without opening a model turn: the user needs to know their task stopped, and spending an LLM
32
- * call to phrase that is exactly the kind of cost this design removes.
33
+ * call to phrase that is exactly the kind of cost this design removes. A budget stop also says
34
+ * how to resume with more of the dimension that ran out (spec 053, D6).
33
35
  */
34
- export declare function taskStopReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
36
+ export declare function taskStopReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number, breach?: BudgetBreach): ChannelEvent;
35
37
  /**
36
38
  * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9; spec 052).
37
39
  *
@@ -7,6 +7,7 @@ import { PLAYBOOKS_DIR } from "../paths.js";
7
7
  import { TASK_DRIVER_SETTINGS } from "../settings.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { checkBudget, IDLE_STEP_LIMIT } from "../tasks/budget.js";
10
+ import { taskStateLabel } from "../tasks/frontmatter.js";
10
11
  import { readActiveTasks } from "../tasks/ledger.js";
11
12
  import { readTaskLog } from "../tasks/log.js";
12
13
  import { expireTicket, pauseTask, redeemTicket } from "../tasks/store.js";
@@ -79,17 +80,22 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
79
80
  /**
80
81
  * The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
81
82
  * without opening a model turn: the user needs to know their task stopped, and spending an LLM
82
- * call to phrase that is exactly the kind of cost this design removes.
83
+ * call to phrase that is exactly the kind of cost this design removes. A budget stop also says
84
+ * how to resume with more of the dimension that ran out (spec 053, D6).
83
85
  */
84
- export function taskStopReceipt(channelId, entry, reason, nowMs) {
86
+ export function taskStopReceipt(channelId, entry, reason, nowMs, breach) {
87
+ const usage = entry.fields.usage ? ` · 已用 ${entry.fields.usage.steps} 步` : "";
88
+ const grant = breach === "steps" ? " +steps 10" : breach === "usd" ? " +usd 5" : "";
89
+ const resumeLabel = grant ? "继续并追加预算" : "继续";
85
90
  return {
86
91
  ...channelType(channelId),
87
92
  channelId,
88
93
  user: "TASK_DRIVER",
89
94
  userName: "TASK_DRIVER",
90
- text: `任务 ${entry.id}(${entry.title})已停止自动执行:${reason}\n` +
91
- `当前阶段:${entry.fields.state}${entry.fields.usage ? `;已用 ${entry.fields.usage.steps} 步` : ""}\n` +
92
- `查看:/tasks show ${entry.id}\n继续:/tasks resume ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
95
+ text: `🛑 任务 \`${entry.id}\`(${entry.title})已停止自动执行:${reason}。\n` +
96
+ `状态:${taskStateLabel(entry.fields.state)}${usage}\n` +
97
+ `查看:\`/tasks show ${entry.id}\`;${resumeLabel}:\`/tasks resume ${entry.id}${grant}\`\n` +
98
+ "不再需要:直接告诉我取消该任务。",
93
99
  ts: String(nowMs),
94
100
  // Keyed on the cause, not the moment: re-detecting the same stop before the user has acted
95
101
  // must not queue a second identical receipt, while a different cause still does.
@@ -134,14 +140,18 @@ export class TaskDriver {
134
140
  this.options.onDispatch?.(event, accepted);
135
141
  }
136
142
  catch (error) {
137
- log.logWarning("Task driver dispatch observer failed", errorMessage(error));
143
+ log.logWarn("taskdriver.observer.failed", "Task driver dispatch observer failed", {
144
+ reason: errorMessage(error),
145
+ });
138
146
  }
139
147
  }
140
148
  start() {
141
149
  if (this.loopActive)
142
150
  return;
143
151
  this.loopActive = true;
144
- log.logInfo("Task driver started", `schedule timezone=${Intl.DateTimeFormat().resolvedOptions().timeZone} (host)`);
152
+ log.logInfoEvent("taskdriver.started", "Task driver started", {
153
+ fields: { timezone: Intl.DateTimeFormat().resolvedOptions().timeZone },
154
+ });
145
155
  void this.tick();
146
156
  }
147
157
  stop() {
@@ -178,7 +188,7 @@ export class TaskDriver {
178
188
  await this.runOnce();
179
189
  }
180
190
  catch (error) {
181
- log.logWarning("Task driver tick failed", errorMessage(error));
191
+ log.logWarn("taskdriver.tick.failed", "Task driver tick failed", { reason: errorMessage(error) });
182
192
  }
183
193
  this.scheduleNext();
184
194
  }
@@ -203,12 +213,15 @@ export class TaskDriver {
203
213
  this.nextWakeMs = candidate;
204
214
  }
205
215
  /** Stop one task and notify. Delivery failure is logged, never fatal: the durable stop already happened. */
206
- async notifyStop(channelId, entry, reason, nowMs) {
216
+ async notifyStop(channelId, entry, reason, nowMs, breach) {
207
217
  try {
208
- await this.options.notify?.(taskStopReceipt(channelId, entry, reason, nowMs));
218
+ await this.options.notify?.(taskStopReceipt(channelId, entry, reason, nowMs, breach));
209
219
  }
210
220
  catch (error) {
211
- log.logWarning(`[${channelId}] Task stop receipt failed`, errorMessage(error));
221
+ log.logWarn("taskdriver.receipt.failed", "Task stop receipt failed", {
222
+ channelId: channelId,
223
+ reason: errorMessage(error),
224
+ });
212
225
  }
213
226
  }
214
227
  /**
@@ -237,11 +250,19 @@ export class TaskDriver {
237
250
  continue;
238
251
  changed = true;
239
252
  if (expiry.outcome === "paused") {
240
- log.logWarning(`[${channelId}] Task ${entry.id} paused: ticket expired twice`, expiry.ticket);
241
- await this.notifyStop(channelId, entry, `等待未兑现(${expiry.ticket}),已连续两次超过兜底时限`, nowMs);
253
+ log.logWarn("taskdriver.task.paused", "Task paused: ticket expired twice", {
254
+ channelId: channelId,
255
+ reason: expiry.ticket,
256
+ fields: { taskId: entry.id, cause: "ticket_expired" },
257
+ });
258
+ await this.notifyStop(channelId, entry, `等待条件一直未满足(${expiry.ticket}),已连续两次超过最晚检查时间`, nowMs);
242
259
  }
243
260
  else {
244
- log.logInfo(`[${channelId}] Task ${entry.id} reopened after its ticket expired`, expiry.ticket);
261
+ log.logInfoEvent("taskdriver.task.reopened", "Task reopened after its ticket expired", {
262
+ channelId: channelId,
263
+ reason: expiry.ticket,
264
+ fields: { taskId: entry.id },
265
+ });
245
266
  }
246
267
  continue;
247
268
  }
@@ -268,10 +289,14 @@ export class TaskDriver {
268
289
  const idle = steps.every((record) => record.kind === "step" && record.tools.length === 0);
269
290
  if (!idle)
270
291
  continue;
271
- const reason = `连续 ${IDLE_STEP_LIMIT} 步没有任何工具调用,循环已停下等你确认`;
292
+ const reason = `连续 ${IDLE_STEP_LIMIT} 步没有任何工具调用,已停下等你确认`;
272
293
  if (await pauseTask(channelDir, entry.id, { by: "runtime", reason })) {
273
294
  paused = true;
274
- log.logWarning(`[${channelId}] Task ${entry.id} paused: idle loop`, reason);
295
+ log.logWarn("taskdriver.task.paused", "Task paused: idle loop", {
296
+ channelId: channelId,
297
+ reason: reason,
298
+ fields: { taskId: entry.id, cause: "idle" },
299
+ });
275
300
  await this.notifyStop(channelId, entry, reason, nowMs);
276
301
  }
277
302
  }
@@ -322,8 +347,12 @@ export class TaskDriver {
322
347
  continue;
323
348
  }
324
349
  if (await pauseTask(channelDir, entry.id, { by: "runtime", reason: status.reason })) {
325
- log.logWarning(`[${channelId}] Task ${entry.id} paused: budget ${status.breach}`, status.reason);
326
- await this.notifyStop(channelId, entry, status.reason, nowMs);
350
+ log.logWarn("taskdriver.task.paused", "Task paused: budget exhausted", {
351
+ channelId: channelId,
352
+ reason: status.reason,
353
+ fields: { taskId: entry.id, cause: `budget_${status.breach}` },
354
+ });
355
+ await this.notifyStop(channelId, entry, status.reason, nowMs, status.breach);
327
356
  }
328
357
  }
329
358
  const idled = await this.detectIdleLoop(channelDir, channelId, budgeted, nowMs);
@@ -358,10 +387,16 @@ export class TaskDriver {
358
387
  if (accepted) {
359
388
  dispatched++;
360
389
  lastDispatchOffset = offset;
361
- log.logInfo(`[${channelId}] Task driver enqueued ${entry.id}`);
390
+ log.logDebugEvent("taskdriver.step.enqueued", "Task step enqueued", {
391
+ channelId: channelId,
392
+ fields: { taskId: entry.id },
393
+ });
362
394
  }
363
395
  else {
364
- log.logWarning(`[${channelId}] Task driver could not enqueue ${entry.id}`, "channel queue unavailable");
396
+ log.logWarn("taskdriver.step.enqueue_failed", "Task step not enqueued: channel queue unavailable", {
397
+ channelId: channelId,
398
+ fields: { taskId: entry.id },
399
+ });
365
400
  }
366
401
  }
367
402
  for (const key of this.lastDispatchMs.keys()) {
@@ -291,7 +291,10 @@ async function convertOneTask(workspaceDir, channelId, channelDir, id, now) {
291
291
  stage = "archive";
292
292
  await archiveTask(channelDir, id, "cancelled");
293
293
  }
294
- log.logInfo(`Task ${id} converted to v5`, `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`);
294
+ log.logInfoEvent("tasks.migration.converted", "Task converted to v5", {
295
+ reason: `state=${fields.state}${fields.paused ? " paused" : ""}${origin ? ` origin=${origin}` : ""}${retire ? " (retired)" : ""}`,
296
+ fields: { taskId: id },
297
+ });
295
298
  return true;
296
299
  }
297
300
  catch (error) {
@@ -400,7 +403,9 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
400
403
  }
401
404
  catch (error) {
402
405
  // An undiscoverable workspace is not an empty one: no task was looked at, so no marker.
403
- log.logWarning("Channels of the workspace could not be discovered", errorMessage(error));
406
+ log.logWarn("tasks.migration.discover_failed", "Workspace channels could not be discovered", {
407
+ reason: errorMessage(error),
408
+ });
404
409
  failures.push({ channelId: "*", stage: "discover", error: errorMessage(error), rollback: "ok" });
405
410
  }
406
411
  for (const channelId of channelIds) {
@@ -411,7 +416,10 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
411
416
  }
412
417
  catch (error) {
413
418
  // An unreadable task directory is not an empty one: the originals were not looked at.
414
- log.logWarning(`Tasks of ${channelId} could not be listed`, errorMessage(error));
419
+ log.logWarn("tasks.migration.list_failed", "Channel tasks could not be listed", {
420
+ channelId: channelId,
421
+ reason: errorMessage(error),
422
+ });
415
423
  failures.push({ channelId, stage: "scan", error: errorMessage(error), rollback: "ok" });
416
424
  }
417
425
  for (const filename of filenames) {
@@ -421,7 +429,10 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
421
429
  converted++;
422
430
  }
423
431
  catch (error) {
424
- log.logWarning(`Task ${id} could not be converted to v5`, errorMessage(error));
432
+ log.logWarn("tasks.migration.convert_failed", "Task could not be converted to v5", {
433
+ reason: errorMessage(error),
434
+ fields: { taskId: id },
435
+ });
425
436
  failures.push({
426
437
  channelId,
427
438
  task: id,
@@ -432,7 +443,10 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
432
443
  }
433
444
  }
434
445
  await moveTaskOwnedEvents(workspaceDir, channelId, channelDir).catch((error) => {
435
- log.logWarning(`Task-owned events of ${channelId} could not be moved`, errorMessage(error));
446
+ log.logWarn("tasks.migration.events_failed", "Task-owned events could not be moved", {
447
+ channelId: channelId,
448
+ reason: errorMessage(error),
449
+ });
436
450
  failures.push({ channelId, stage: "events", error: errorMessage(error), rollback: "ok" });
437
451
  });
438
452
  }
@@ -444,5 +458,8 @@ export async function migrateTasksToV5(workspaceDir, stateDir) {
444
458
  await rm(reportPath, { force: true });
445
459
  await writeFile(markerPath, `${formatLocalTime(now)}\n`, "utf-8");
446
460
  if (converted > 0)
447
- log.logInfo("Task conversion to v5 complete", `${converted} task(s)`);
461
+ log.logInfoEvent("tasks.migration.done", "Task conversion to v5 complete", {
462
+ reason: `${converted} task(s)`,
463
+ fields: { converted },
464
+ });
448
465
  }
@@ -1,9 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import * as log from "../log.js";
3
3
  import { createTaskDocument, instanceStamp } from "../tasks/create.js";
4
+ import { taskStateLabel } from "../tasks/frontmatter.js";
4
5
  import { readActiveTasks } from "../tasks/ledger.js";
5
6
  import { archivedTaskPath, taskPath, tasksDir } from "../tasks/store.js";
6
- const STATE_LABEL = { open: "进行中", parked: "等待中" };
7
7
  /**
8
8
  * Create the task instance a template event asks for (spec 052, D2).
9
9
  *
@@ -27,11 +27,15 @@ export function createTaskSpawner(options) {
27
27
  }
28
28
  const active = (await readActiveTasks(tasksDir(channelDir))).find((entry) => entry.fields.origin === request.eventName && !entry.fields.outcome);
29
29
  if (active) {
30
- const state = STATE_LABEL[active.fields.state] ?? active.fields.state;
30
+ const state = `${taskStateLabel(active.fields.state)}${active.fields.paused ? ",已暂停" : ""}`;
31
31
  await options
32
- .notify(request.channelId, `周期任务 ${request.eventName} 本次(${instanceStamp(request.occurrence)})未启动:上一实例 ${active.id} 仍在进行(${state}${active.fields.paused ? ",已暂停" : ""})。\n查看:/tasks show ${active.id}`)
32
+ .notify(request.channelId, `⚠️ 周期任务 \`${request.eventName}\` 本次(${instanceStamp(request.occurrence)})未启动:上一个实例 \`${active.id}\` 仍未结束(${state})。\n查看:\`/tasks show ${active.id}\``)
33
33
  .catch((error) => {
34
- log.logWarning(`Could not deliver skip receipt for ${request.eventName}`, String(error));
34
+ log.logWarn("tasks.spawn.receipt_failed", "Skip receipt delivery failed", {
35
+ channelId: request.channelId,
36
+ reason: String(error),
37
+ fields: { event: request.eventName },
38
+ });
35
39
  });
36
40
  return { outcome: "skipped", id: active.id };
37
41
  }
@@ -42,7 +46,10 @@ export function createTaskSpawner(options) {
42
46
  origin: request.eventName,
43
47
  now: request.occurrence,
44
48
  });
45
- log.logInfo(`[${request.channelId}] Event ${request.eventName} spawned task ${id}`);
49
+ log.logInfoEvent("tasks.spawn.created", "Event spawned a task instance", {
50
+ channelId: request.channelId,
51
+ fields: { event: request.eventName, taskId: id },
52
+ });
46
53
  options.nudge();
47
54
  return { outcome: "spawned", id };
48
55
  };
@@ -0,0 +1,18 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
2
+ /**
3
+ * Consumer-side merging of completion wakes. K parallel delegations (or background jobs) used to
4
+ * settle into K separate main-agent turns, each re-reading the whole session to handle one result
5
+ * — and with the event queue capped at a handful of items, the rest waited out a 30s+ retry. Now
6
+ * the turn that starts one completion wake also takes every other one still waiting for this
7
+ * channel, so results that arrive while the channel is busy are handled together in the next turn.
8
+ * Nothing is delayed to make that happen: the first result still wakes the channel immediately.
9
+ *
10
+ * Only chat-level wakes merge. A task-bound wake carries `internalWake` and goes through its own
11
+ * claim (`task-wake.ts`), which already lets sibling wakes of one fan-out drop out once the task
12
+ * is reopened.
13
+ */
14
+ /** The merged turn's prompt grows with every result's tail; past this many it is better split. */
15
+ export declare const MAX_COALESCED_WAKES = 6;
16
+ export declare function isCoalescableWake(event: ChannelEvent): boolean;
17
+ /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
18
+ export declare function mergeCompletionWakes(primary: ChannelEvent, others: ChannelEvent[]): ChannelEvent;