@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

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 (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -0,0 +1,71 @@
1
+ import { renderStatus } from "../agent/status-render.js";
2
+ import { getChannelDir } from "../channel/channel-paths.js";
3
+ import { handleEventsCommand } from "../events/event-commands.js";
4
+ import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
5
+ import { getUsageLedger } from "../usage/ledger.js";
6
+ import { parseUsageMode, renderUsageReport } from "../usage/render.js";
7
+ import { handleProjectCommand } from "./project-commands.js";
8
+ import { handleSkillsCommand } from "./skill-commands.js";
9
+ import { handleSubagentsCommand } from "./subagent-commands.js";
10
+ import { handleTasksCommand } from "./task-commands.js";
11
+ export async function runReportCommand(context, name, args) {
12
+ const { channelId, paths } = context;
13
+ const channelDir = getChannelDir(paths.workspaceDir, channelId);
14
+ switch (name) {
15
+ case "events":
16
+ return handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath });
17
+ case "tasks":
18
+ return handleTasksCommand({ args, channelDir, dispatchTask: context.dispatchTask });
19
+ case "status":
20
+ return renderStatus({
21
+ runner: context.peekRunner(),
22
+ version: context.version,
23
+ uptimeMs: Date.now() - context.startedAt,
24
+ });
25
+ case "usage":
26
+ return renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date());
27
+ // Read-only prompt accounting; safe mid-turn.
28
+ case "context":
29
+ return context.getRunner().renderContextReport(args);
30
+ // A human control path independent of the model (spec 040, D6): `/stop` does not kill a
31
+ // dispatched delegation, so cancel must work whether or not a runner is currently active.
32
+ case "subagents":
33
+ return handleSubagentsCommand({
34
+ args,
35
+ runManager: context.runManager,
36
+ channelId,
37
+ discovery: context.peekRunner()?.getSubAgentDiscoverySnapshot(),
38
+ // `roles` needs a role directory even for a channel that has never spoken this boot —
39
+ // resolved from disk, without spinning up a full runner (spec 041).
40
+ getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
41
+ workspaceDir: paths.workspaceDir,
42
+ authConfigPath: paths.authConfigPath,
43
+ modelsConfigPath: paths.modelsConfigPath,
44
+ }),
45
+ });
46
+ case "project":
47
+ return handleProjectCommand({
48
+ args,
49
+ channelId,
50
+ channelDir,
51
+ appHomeDir: paths.appHomeDir,
52
+ actor: context.actor,
53
+ isBusy: () => context.peekRunner()?.isBusy() ?? false,
54
+ listActiveBlockers: () => [
55
+ ...context.runManager
56
+ .list()
57
+ .filter((record) => record.status === "running")
58
+ .map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
59
+ ...context.runningJobLines(),
60
+ ],
61
+ onScopeChanged: context.onScopeChanged,
62
+ });
63
+ case "skills":
64
+ return handleSkillsCommand({
65
+ args,
66
+ workspaceDir: paths.workspaceDir,
67
+ appHomeDir: paths.appHomeDir,
68
+ channelId,
69
+ });
70
+ }
71
+ }
@@ -184,7 +184,7 @@ async function showRun(manager, ref) {
184
184
  if (record.failureReason)
185
185
  lines.push(`- 失败原因:${record.failureReason}`);
186
186
  if (record.verificationVerdict) {
187
- lines.push(`- 验收结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? "(advisory)" : ""}`);
187
+ lines.push(`- 检查结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}`);
188
188
  }
189
189
  lines.push(`- 开始:${new Date(record.startedAt).toLocaleString()}`);
190
190
  if (record.finishedAt)
@@ -3,9 +3,6 @@ export interface HandleTasksCommandOptions {
3
3
  args: string;
4
4
  /** The channel directory; tasks live in `<channelDir>/tasks/`. */
5
5
  channelDir: string;
6
- /** Workspace directory; kept for callers that still pass it (doctor reads task-owned events). */
7
- workspaceDir?: string;
8
- channelId?: string;
9
6
  /** Optional immediate task wake, available in the long-lived DingTalk runtime. */
10
7
  dispatchTask?: (id: string) => Promise<boolean>;
11
8
  }
@@ -17,7 +14,6 @@ type TasksCommand = {
17
14
  } | {
18
15
  action: "log";
19
16
  id: string;
20
- cycle?: string;
21
17
  } | {
22
18
  action: "archive";
23
19
  } | {
@@ -29,9 +25,6 @@ type TasksCommand = {
29
25
  action: "resume";
30
26
  id: string;
31
27
  grants: Partial<TaskBudget>;
32
- } | {
33
- action: "run";
34
- id: string;
35
28
  } | {
36
29
  action: "steer";
37
30
  id: string;
@@ -43,7 +36,6 @@ type TasksCommand = {
43
36
  };
44
37
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
45
38
  export declare function parseTasksCommand(args: string): TasksCommand;
46
- export declare function pauseTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
47
39
  export declare function resumeTask(options: HandleTasksCommandOptions, idInput: string, grants?: Partial<TaskBudget>): Promise<string>;
48
40
  export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;
49
41
  export {};
@@ -4,24 +4,27 @@ import { join } from "node:path";
4
4
  import { renderSubcommandUsage } from "../commands/catalog.js";
5
5
  import { parseLocalTime } from "../shared/local-time.js";
6
6
  import { clipText, errorMessage } from "../shared/text-utils.js";
7
+ import { buildTaskBoard, renderTaskBoard } from "../tasks/board.js";
7
8
  import { normalizeTaskId, readActiveTasks } from "../tasks/ledger.js";
8
9
  import { readTaskLog, renderTaskLogLine } from "../tasks/log.js";
9
10
  import { withTaskMutation } from "../tasks/mutation-lock.js";
10
11
  import { hasTaskSteer, queueTaskSteer } from "../tasks/steer.js";
11
- import { openCycle, pauseTask as pauseTaskDocument, readStoredTask, redeemTicket, resumeTask as resumeTaskDocument, updateStoredTask, } from "../tasks/store.js";
12
+ import { pauseTask as pauseTaskDocument, readStoredTask, redeemTicket, resumeTask as resumeTaskDocument, updateStoredTask, } from "../tasks/store.js";
12
13
  import { describeTicket } from "../tasks/ticket.js";
13
14
  /** `/tasks show <id>` head-snippet cap; the full file is always readable at its own path. */
14
15
  const TASK_SHOW_MAX_CHARS = 2_400;
15
16
  const SHOW_LOG_LINES = 8;
17
+ /** A backstop this far past due means the driver is not running, not that it is merely about to act. */
18
+ const EXPIRED_GRACE_MS = 60 * 60 * 1000;
16
19
  // Broadcast (subcommand names, args, descriptions, examples) lives once in commands/catalog.ts's
17
20
  // `BUILT_IN_COMMANDS` entry for "tasks"; this just renders it (review 2026-08-24 §3.1).
18
21
  function usage() {
19
22
  return renderSubcommandUsage("tasks");
20
23
  }
21
- /** `+steps 20`, `+rounds 2`, `+usd 5` — the three grants `/tasks resume` accepts. */
24
+ /** `+steps 20`, `+usd 5` — the two grants `/tasks resume` accepts. */
22
25
  function parseGrants(rest) {
23
26
  const grants = {};
24
- const pattern = /\+(steps|rounds|usd)\s+([0-9]+(?:\.[0-9]+)?)/g;
27
+ const pattern = /\+(steps|usd)\s+([0-9]+(?:\.[0-9]+)?)/g;
25
28
  for (const match of rest.matchAll(pattern)) {
26
29
  const value = Number(match[2]);
27
30
  if (!Number.isFinite(value) || value <= 0)
@@ -45,22 +48,16 @@ export function parseTasksCommand(args) {
45
48
  throw new Error(`用法:/tasks ${action}`);
46
49
  return { action };
47
50
  }
48
- if (action === "show" || action === "pause" || action === "run") {
51
+ if (action === "show" || action === "pause" || action === "log") {
49
52
  const id = parts[1];
50
53
  if (!id || parts.length > 2)
51
54
  throw new Error(`用法:/tasks ${action} <id>`);
52
55
  return { action, id };
53
56
  }
54
- if (action === "log") {
55
- const id = parts[1];
56
- if (!id || parts.length > 3)
57
- throw new Error("用法:/tasks log <id> [cycle]");
58
- return { action: "log", id, cycle: parts[2] };
59
- }
60
57
  if (action === "resume") {
61
58
  const id = parts[1];
62
59
  if (!id)
63
- throw new Error("用法:/tasks resume <id> [+steps N|+rounds N|+usd X]");
60
+ throw new Error("用法:/tasks resume <id> [+steps N|+usd X]");
64
61
  return { action: "resume", id, grants: parseGrants(parts.slice(2).join(" ")) };
65
62
  }
66
63
  if (action === "steer" || action === "reply") {
@@ -91,12 +88,12 @@ function relative(atMs, now) {
91
88
  return `${Math.round(hours / 24)}d`;
92
89
  }
93
90
  const STATE_LABEL = { open: "进行中", parked: "等待中", done: "已关闭" };
94
- function cycleSummary(entry) {
95
- const cycle = entry.fields.cycle;
96
- if (!cycle)
91
+ function usageSummary(entry) {
92
+ const usage = entry.fields.usage;
93
+ if (!usage)
97
94
  return undefined;
98
- const cost = cycle.usd > 0 ? `,$${cycle.usd.toFixed(2)}${cycle.usdEstimated ? "(含估算)" : ""}` : "";
99
- return `${cycle.id}:${cycle.steps} 步 / ${cycle.rounds} 轮${cost}`;
95
+ const cost = usage.usd > 0 ? `,$${usage.usd.toFixed(2)}${usage.usdEstimated ? "(含估算)" : ""}` : "";
96
+ return `${usage.steps} 步${cost}`;
100
97
  }
101
98
  function ticketSummary(entry, now) {
102
99
  const ticket = entry.fields.ticket;
@@ -112,11 +109,13 @@ function renderListLine(entry, channelDir, now) {
112
109
  const ticket = ticketSummary(entry, now);
113
110
  if (ticket)
114
111
  bits.push(ticket);
115
- if (entry.plan)
116
- bits.push(`plan ${entry.plan.done}/${entry.plan.total}`);
117
- const cycle = cycleSummary(entry);
118
- if (cycle)
119
- bits.push(cycle);
112
+ if (entry.items)
113
+ bits.push(`items ${entry.items.done}/${entry.items.total}`);
114
+ if (entry.fields.origin)
115
+ bits.push(`来自 ${entry.fields.origin}`);
116
+ const usage = usageSummary(entry);
117
+ if (usage)
118
+ bits.push(usage);
120
119
  if (hasTaskSteer(channelDir, entry.id))
121
120
  bits.push("有待处理的指示");
122
121
  if (!entry.readable)
@@ -146,22 +145,20 @@ async function showTask(channelDir, idInput) {
146
145
  const by = relative(parseLocalTime(document.fields.ticket.by), now);
147
146
  head.push(`- 等待:${describeTicket(document.fields.ticket)}${by ? `(兜底 ${by})` : ""}`);
148
147
  }
149
- if (document.fields.schedule)
150
- head.push(`- 周期:${document.fields.schedule}`);
151
- const cycle = entry ? cycleSummary(entry) : undefined;
152
- if (cycle)
153
- head.push(`- 本周期:${cycle}`);
154
- if (document.fields.verify === "required")
155
- head.push("- 需要独立验收");
156
- const rounds = await readTaskLog(channelDir, id, { cycle: document.fields.cycle?.id, kinds: ["round"] });
157
- if (rounds.length > 0) {
158
- const verdicts = rounds.map((record) => (record.kind === "round" ? record.verdict : "")).join(" → ");
159
- head.push(`- 返工:${rounds.length} 轮(${verdicts})`);
160
- }
161
- const log = await readTaskLog(channelDir, id, { limit: SHOW_LOG_LINES });
148
+ if (document.fields.origin)
149
+ head.push(`- 来自事件:${document.fields.origin}`);
150
+ const usage = entry ? usageSummary(entry) : undefined;
151
+ if (usage)
152
+ head.push(`- 用量:${usage}`);
153
+ const board = await buildTaskBoard(channelDir, id, document.body);
154
+ const boardLines = board ? ["", "**团队看板**", renderTaskBoard(board, now)] : [];
155
+ const log = await readTaskLog(channelDir, id, {
156
+ kinds: ["step", "expired", "close", "note"],
157
+ limit: SHOW_LOG_LINES,
158
+ });
162
159
  const logLines = log.length > 0 ? ["", `**最近 ${log.length} 条日志**`, ...log.map(renderTaskLogLine)] : [];
163
160
  const body = clipText(document.body.trim(), TASK_SHOW_MAX_CHARS);
164
- return [...head, ...logLines, "", "**契约**", body, "", `完整日志:/tasks log ${id}`].join("\n");
161
+ return [...head, ...boardLines, ...logLines, "", "**契约**", body, "", `完整日志:/tasks log ${id}`].join("\n");
165
162
  }
166
163
  async function listArchive(channelDir) {
167
164
  const archiveDir = join(tasksDir(channelDir), "archive");
@@ -180,14 +177,14 @@ async function listArchive(channelDir) {
180
177
  lines.push(`- (另有 ${files.length - 20} 个,见 tasks/archive/)`);
181
178
  return [`**已归档任务(${files.length})**`, ...lines].join("\n");
182
179
  }
183
- async function showTaskLog(channelDir, idInput, cycle) {
180
+ async function showTaskLog(channelDir, idInput) {
184
181
  const id = normalizeTaskId(idInput);
185
- const records = await readTaskLog(channelDir, id, { cycle, limit: 30 });
182
+ const records = await readTaskLog(channelDir, id, { limit: 30 });
186
183
  if (records.length === 0)
187
- return `任务 \`${id}\` 暂无循环日志${cycle ? `(周期 ${cycle})` : ""}。`;
184
+ return `任务 \`${id}\` 暂无循环日志。`;
188
185
  return [`**任务 ${id} 日志(${records.length} 条)**`, ...records.map(renderTaskLogLine)].join("\n");
189
186
  }
190
- export async function pauseTask(options, idInput) {
187
+ async function pauseTask(options, idInput) {
191
188
  const id = normalizeTaskId(idInput);
192
189
  const document = await pauseTaskDocument(options.channelDir, id, {
193
190
  by: "user",
@@ -206,18 +203,14 @@ export async function resumeTask(options, idInput, grants = {}) {
206
203
  if (Object.keys(grants).length > 0) {
207
204
  await updateStoredTask(options.channelDir, id, (task) => {
208
205
  const budget = { ...task.fields.budget };
209
- for (const key of ["steps", "rounds", "usd"]) {
206
+ for (const key of ["steps", "usd"]) {
210
207
  const extra = grants[key];
211
208
  if (extra === undefined)
212
209
  continue;
213
- // A grant is *additional* headroom on top of whatever this cycle already spent, so
210
+ // A grant is *additional* headroom on top of whatever the task already spent, so
214
211
  // resuming a task that hit its ceiling actually lets it run rather than re-stopping
215
212
  // on the next step.
216
- const spent = key === "steps"
217
- ? task.fields.cycle?.steps
218
- : key === "rounds"
219
- ? task.fields.cycle?.rounds
220
- : task.fields.cycle?.usd;
213
+ const spent = key === "steps" ? task.fields.usage?.steps : task.fields.usage?.usd;
221
214
  budget[key] = (spent ?? 0) + extra;
222
215
  granted.push(`${key}+${extra}`);
223
216
  }
@@ -226,24 +219,6 @@ export async function resumeTask(options, idInput, grants = {}) {
226
219
  }
227
220
  return `已恢复任务 \`${id}\`${granted.length > 0 ? `(${granted.join(",")})` : ""}。`;
228
221
  }
229
- async function runTask(options, idInput) {
230
- const id = normalizeTaskId(idInput);
231
- const document = await readStoredTask(options.channelDir, id);
232
- if (!document)
233
- return `未找到任务 \`${id}\`。`;
234
- if (document.fields.paused) {
235
- return `任务 \`${id}\` 处于暂停状态;先用 /tasks resume ${id} 恢复,再 /tasks run。`;
236
- }
237
- if (!document.fields.cycle || document.fields.state === "parked") {
238
- const opened = await openCycle(options.channelDir, id);
239
- if (!opened)
240
- return `任务 \`${id}\` 无法开启新周期(可能已归档)。`;
241
- }
242
- const dispatched = await options.dispatchTask?.(id);
243
- return dispatched === false
244
- ? `任务 \`${id}\` 已就绪,但频道队列暂时无法接受;driver 会在下一轮重试。`
245
- : `已立即唤醒任务 \`${id}\`。`;
246
- }
247
222
  async function steerTask(options, idInput, text) {
248
223
  const id = normalizeTaskId(idInput);
249
224
  const document = await readStoredTask(options.channelDir, id);
@@ -275,12 +250,11 @@ function issue(problem, nextStep) {
275
250
  return `- ${problem}(下一步:${nextStep})`;
276
251
  }
277
252
  /**
278
- * `/tasks doctor`, deliberately shrunk (spec 051, D11).
253
+ * `/tasks doctor`, deliberately small (spec 051, D11; spec 052, D11).
279
254
  *
280
- * Most of what v3's doctor looked for — `enabled` disagreeing with `control.stop`, `active` with
281
- * a future wake, an unparsable control block, a park with no recoverable source — cannot be
282
- * produced any more: the frontmatter normalizer and `resolveTicket` reject those states at write
283
- * time. What is left is what a *hand edit* can still create.
255
+ * Most of what older doctors looked for cannot be produced any more: the frontmatter normalizer
256
+ * and `resolveTicket` reject those states at write time. What is left is what a *hand edit*, or a
257
+ * conversion that did not run, can still create.
284
258
  */
285
259
  async function doctor(options) {
286
260
  const now = Date.now();
@@ -292,20 +266,11 @@ async function doctor(options) {
292
266
  continue;
293
267
  }
294
268
  if (entry.legacy) {
295
- problems.push(issue(`${entry.id} 仍是 v3 契约`, "重启一次让迁移器升级它,或用 edit 手动改写 frontmatter"));
296
- }
297
- if (entry.fields.state === "parked" && !entry.fields.ticket) {
298
- problems.push(issue(`${entry.id} 停泊但没有等待票`, `用 /tasks run ${entry.id} 重新开始,或让 Agent 重新停泊`));
299
- }
300
- if (entry.expired && !entry.fields.paused) {
301
- problems.push(issue(`${entry.id} 的等待票已过兜底时限`, "driver 会在下一轮重开或通知;若一直没有,检查 daemon 是否在跑"));
302
- }
303
- if (entry.fields.schedule && !entry.fields.cycle) {
304
- problems.push(issue(`${entry.id} 有 schedule 但没有周期记录`, `用 /tasks run ${entry.id} 开启第一个周期`));
269
+ problems.push(issue(`${entry.id} 仍含旧版本的字段(cycle / schedule / verify 等)`, "重启一次让转换器升级它,或用 edit 手动改写 frontmatter"));
305
270
  }
306
- const until = entry.fields.budget?.until ? parseLocalTime(entry.fields.budget.until) : undefined;
307
- if (until !== undefined && until < now && !entry.fields.paused) {
308
- problems.push(issue(`${entry.id} 已超过 budget.until`, `用 task_update 调整期限,或 /tasks pause ${entry.id}`));
271
+ const by = entry.fields.ticket ? parseLocalTime(entry.fields.ticket.by) : undefined;
272
+ if (entry.expired && !entry.fields.paused && by !== undefined && by < now - EXPIRED_GRACE_MS) {
273
+ problems.push(issue(`${entry.id} 的等待票已过兜底时限超过 1 小时`, "driver 本该重开或通知;检查 daemon 是否在跑"));
309
274
  }
310
275
  }
311
276
  if (problems.length === 0)
@@ -337,15 +302,13 @@ async function dispatchTasksCommand(options, command) {
337
302
  case "show":
338
303
  return await showTask(options.channelDir, command.id);
339
304
  case "log":
340
- return await showTaskLog(options.channelDir, command.id, command.cycle);
305
+ return await showTaskLog(options.channelDir, command.id);
341
306
  case "archive":
342
307
  return await listArchive(options.channelDir);
343
308
  case "pause":
344
309
  return await pauseTask(options, command.id);
345
310
  case "resume":
346
311
  return await resumeTask(options, command.id, command.grants);
347
- case "run":
348
- return await runTask(options, command.id);
349
312
  case "steer":
350
313
  return await steerTask(options, command.id, command.text);
351
314
  case "reply":
@@ -1,5 +1,5 @@
1
1
  import type { ChannelEvent } from "../channel/channel-event.js";
2
- import type { PipiclawTaskDriverSettings } from "../settings.js";
2
+ import { type PipiclawTaskDriverSettings } from "../settings.js";
3
3
  import { type TaskLedgerEntry } from "../tasks/ledger.js";
4
4
  export interface TaskDriverOptions {
5
5
  workspaceDir: string;
@@ -8,7 +8,8 @@ export interface TaskDriverOptions {
8
8
  dispatch: (event: ChannelEvent) => boolean | Promise<boolean>;
9
9
  /** Optional observability hook. It runs after every production dispatch attempt. */
10
10
  onDispatch?: (event: ChannelEvent, accepted: boolean) => void;
11
- getSettings: () => PipiclawTaskDriverSettings;
11
+ /** Test-only override; production uses `TASK_DRIVER_SETTINGS`. */
12
+ settings?: PipiclawTaskDriverSettings;
12
13
  /** Master autonomy switch (`tools.tasks.enabled`); re-read every tick. Defaults to on. */
13
14
  isEnabled?: () => boolean;
14
15
  /** Test-only override for the idle-sleep cap; production uses `settings.maxSleepMinutes`. */
@@ -21,6 +22,8 @@ export interface TaskDriverOptions {
21
22
  * its escaped directory name never displaces the real id the runner map already knows.
22
23
  */
23
24
  export declare function discoverTaskChannels(workspaceDir: string, knownChannelIds?: Iterable<string>): Promise<string[]>;
25
+ /** The task a `[TASK_DRIVER:<id>]` dispatch text names, if it is one. */
26
+ export declare function parseDriverTaskId(text: string | undefined): string | undefined;
24
27
  export declare function createTaskDriverEvent(channelId: string, entry: TaskLedgerEntry, nowMs: number): ChannelEvent;
25
28
  /**
26
29
  * The deterministic receipt a runtime stop produces (spec 051, D11). It is delivered directly,
@@ -29,12 +32,13 @@ export declare function createTaskDriverEvent(channelId: string, entry: TaskLedg
29
32
  */
30
33
  export declare function taskStopReceipt(channelId: string, entry: TaskLedgerEntry, reason: string, nowMs: number): ChannelEvent;
31
34
  /**
32
- * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9).
35
+ * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9; spec 052).
33
36
  *
34
- * Four jobs, in this order per channel: redeem due `time`/`schedule` tickets, apply the backstop
35
- * to expired ones, open cycles for recurring tasks, and queue one step for a runnable task.
36
- * `run`/`job`/`ask`/`signal` tickets are never polled — their owners push them — so the scan
37
- * stays a cheap read of a handful of frontmatters.
37
+ * Three jobs, in this order per channel: redeem due `time` tickets, apply the backstop to expired
38
+ * ones, and queue one step for a runnable task. `work` and `ask` tickets are never polled — their
39
+ * owners push them (a settling delegation or job, `/tasks reply`) — so the scan stays a cheap read
40
+ * of a handful of frontmatters. Recurring work is not the driver's business: an event spawns a
41
+ * fresh task instance each time (spec 052, D2).
38
42
  *
39
43
  * What is deliberately *not* here any more: the ten-field ledger fingerprint, the process-local
40
44
  * effect ledger, the futile-wake and wake-per-cycle counters, and the three-tier backoff table.
@@ -77,8 +81,8 @@ export declare class TaskDriver {
77
81
  /** Stop one task and notify. Delivery failure is logged, never fatal: the durable stop already happened. */
78
82
  private notifyStop;
79
83
  /**
80
- * Deterministic, zero-token maintenance for one channel: redeem due tickets, apply expiry
81
- * backstops, open recurring cycles. Runs whether or not the channel is busy — only model
84
+ * Deterministic, zero-token maintenance for one channel: redeem due tickets and apply expiry
85
+ * backstops. Runs whether or not the channel is busy — only model
82
86
  * dispatch is gated on an idle channel.
83
87
  */
84
88
  private maintain;
@@ -4,11 +4,12 @@ import { discoverWorkspaceChannelIds } from "../channel/channel-index.js";
4
4
  import { dedupeChannelIdsByDirectory, getChannelDir, isChannelId } from "../channel/channel-paths.js";
5
5
  import * as log from "../log.js";
6
6
  import { PLAYBOOKS_DIR } from "../paths.js";
7
+ import { TASK_DRIVER_SETTINGS } from "../settings.js";
7
8
  import { errorMessage } from "../shared/text-utils.js";
8
9
  import { checkBudget, IDLE_STEP_LIMIT } from "../tasks/budget.js";
9
10
  import { readActiveTasks } from "../tasks/ledger.js";
10
11
  import { readTaskLog } from "../tasks/log.js";
11
- import { expireTicket, openCycle, pauseTask, redeemTicket } from "../tasks/store.js";
12
+ import { expireTicket, pauseTask, redeemTicket } from "../tasks/store.js";
12
13
  /** Short debounce so a burst of nudges collapses into a single rescan. */
13
14
  const NUDGE_DEBOUNCE_MS = 50;
14
15
  /** Never schedule a scan closer than this, so near-now horizons cannot spin the loop. */
@@ -35,23 +36,27 @@ function channelType(channelId) {
35
36
  }
36
37
  /**
37
38
  * Stable, provenance-derived dispatch id for a task step (spec 031, D1; spec 051 keeps the shape).
38
- * A step inside a cycle is genuinely new work each time, so the dispatch moment disambiguates it;
39
- * collapsing two steps onto one durable record would silently drop the later one.
39
+ * Each step is genuinely new work, so the dispatch moment disambiguates it; collapsing two steps
40
+ * onto one durable record would silently drop the later one.
40
41
  */
41
42
  function stepDispatchId(channelId, entry, nowMs) {
42
- return `task:${channelId}:${entry.id}:${entry.fields.cycle?.id ?? "-"}:${nowMs}`;
43
+ return `task:${channelId}:${entry.id}:${nowMs}`;
44
+ }
45
+ /** The task a `[TASK_DRIVER:<id>]` dispatch text names, if it is one. */
46
+ export function parseDriverTaskId(text) {
47
+ return /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(text ?? "")?.[1];
43
48
  }
44
49
  export function createTaskDriverEvent(channelId, entry, nowMs) {
45
- const repairOnly = !entry.readable || entry.legacy;
50
+ const repairOnly = !entry.readable;
46
51
  const repair = repairOnly
47
52
  ? ` Task metadata is not readable; repair only the frontmatter in tasks/${entry.id}.md, then stop. ` +
48
- `Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-loop.md")} for the repair path.`
53
+ `Do not execute the task goal or any external action. Read ${join(PLAYBOOKS_DIR, "task-lead.md")} for the repair path.`
49
54
  : "";
50
55
  const capsule = [
51
56
  `Task capsule: title=${entry.title}; state=${entry.fields.state};`,
52
- entry.fields.cycle ? `cycle=${entry.fields.cycle.id} (${entry.fields.cycle.steps} steps);` : "",
53
- entry.plan
54
- ? `plan=${entry.plan.done}/${entry.plan.total} done, current=${entry.plan.current?.id ?? "none"};`
57
+ entry.fields.usage ? `${entry.fields.usage.steps} steps so far;` : "",
58
+ entry.items
59
+ ? `items=${entry.items.done}/${entry.items.total} done, current=${entry.items.current?.id ?? "none"};`
55
60
  : "",
56
61
  ]
57
62
  .filter(Boolean)
@@ -62,11 +67,11 @@ export function createTaskDriverEvent(channelId, entry, nowMs) {
62
67
  user: "TASK_DRIVER",
63
68
  userName: "TASK_DRIVER",
64
69
  text: `[TASK_DRIVER:${entry.id}] Resume task ${entry.id}. ${capsule}${repair} ` +
65
- `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-loop.md")} before acting. ` +
70
+ `Open tasks/${entry.id}.md and read ${join(PLAYBOOKS_DIR, "task-lead.md")} before acting. ` +
66
71
  (repairOnly
67
72
  ? "After the metadata is repaired, leave task work for a later step. "
68
- : "Advance the next concrete step under the task's current goal, plan and acceptance state. ") +
69
- "End the step with task_step_end (continue / park / done / blocked).",
73
+ : "Advance the next concrete step under the task's current goal, work items and acceptance state. ") +
74
+ "End the step with task_step_end (continue / park / done).",
70
75
  ts: String(nowMs),
71
76
  dispatchId: stepDispatchId(channelId, entry, nowMs),
72
77
  };
@@ -83,7 +88,7 @@ export function taskStopReceipt(channelId, entry, reason, nowMs) {
83
88
  user: "TASK_DRIVER",
84
89
  userName: "TASK_DRIVER",
85
90
  text: `任务 ${entry.id}(${entry.title})已停止自动执行:${reason}\n` +
86
- `当前阶段:${entry.fields.state}${entry.fields.cycle ? `;周期:${entry.fields.cycle.id}` : ""}\n` +
91
+ `当前阶段:${entry.fields.state}${entry.fields.usage ? `;已用 ${entry.fields.usage.steps} 步` : ""}\n` +
87
92
  `查看:/tasks show ${entry.id}\n继续:/tasks resume ${entry.id}\n不再需要:让 Agent cancel 该任务。`,
88
93
  ts: String(nowMs),
89
94
  // Keyed on the cause, not the moment: re-detecting the same stop before the user has acted
@@ -92,12 +97,13 @@ export function taskStopReceipt(channelId, entry, reason, nowMs) {
92
97
  };
93
98
  }
94
99
  /**
95
- * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9).
100
+ * Native, ticket-driven scheduler for the persistent task ledger (spec 051, D9; spec 052).
96
101
  *
97
- * Four jobs, in this order per channel: redeem due `time`/`schedule` tickets, apply the backstop
98
- * to expired ones, open cycles for recurring tasks, and queue one step for a runnable task.
99
- * `run`/`job`/`ask`/`signal` tickets are never polled — their owners push them — so the scan
100
- * stays a cheap read of a handful of frontmatters.
102
+ * Three jobs, in this order per channel: redeem due `time` tickets, apply the backstop to expired
103
+ * ones, and queue one step for a runnable task. `work` and `ask` tickets are never polled — their
104
+ * owners push them (a settling delegation or job, `/tasks reply`) — so the scan stays a cheap read
105
+ * of a handful of frontmatters. Recurring work is not the driver's business: an event spawns a
106
+ * fresh task instance each time (spec 052, D2).
101
107
  *
102
108
  * What is deliberately *not* here any more: the ten-field ledger fingerprint, the process-local
103
109
  * effect ledger, the futile-wake and wake-per-cycle counters, and the three-tier backoff table.
@@ -179,7 +185,7 @@ export class TaskDriver {
179
185
  scheduleNext() {
180
186
  if (!this.loopActive || this.timer || this.nudgeTimer)
181
187
  return;
182
- const settings = this.options.getSettings();
188
+ const settings = this.options.settings ?? TASK_DRIVER_SETTINGS;
183
189
  const capMs = this.options.intervalMs ?? settings.maxSleepMinutes * 60_000;
184
190
  const untilNext = this.nextWakeMs !== undefined ? this.nextWakeMs - Date.now() : Number.POSITIVE_INFINITY;
185
191
  const sleepMs = Math.max(MIN_SLEEP_MS, Math.min(capMs, untilNext));
@@ -206,8 +212,8 @@ export class TaskDriver {
206
212
  }
207
213
  }
208
214
  /**
209
- * Deterministic, zero-token maintenance for one channel: redeem due tickets, apply expiry
210
- * backstops, open recurring cycles. Runs whether or not the channel is busy — only model
215
+ * Deterministic, zero-token maintenance for one channel: redeem due tickets and apply expiry
216
+ * backstops. Runs whether or not the channel is busy — only model
211
217
  * dispatch is gated on an idle channel.
212
218
  */
213
219
  async maintain(channelDir, channelId, entries, now) {
@@ -219,21 +225,10 @@ export class TaskDriver {
219
225
  const ticket = entry.fields.ticket;
220
226
  if (!ticket)
221
227
  continue;
222
- // A due timer redeems into an open task; a due schedule opens the next cycle outright.
228
+ // A due timer redeems into an open task.
223
229
  if (entry.dueMs !== undefined && entry.dueMs <= nowMs) {
224
- if (ticket.kind === "schedule") {
225
- const opened = await openCycle(channelDir, entry.id, now).catch((error) => {
226
- log.logWarning(`[${channelId}] Could not open next cycle for ${entry.id}`, errorMessage(error));
227
- return undefined;
228
- });
229
- if (opened) {
230
- changed = true;
231
- log.logInfo(`[${channelId}] Task driver opened cycle ${opened.cycleId} for ${entry.id}`);
232
- }
233
- }
234
- else if (await redeemTicket(channelDir, entry.id, (current) => current.kind === ticket.kind)) {
230
+ if (await redeemTicket(channelDir, entry.id, (current) => current.kind === ticket.kind))
235
231
  changed = true;
236
- }
237
232
  continue;
238
233
  }
239
234
  if (entry.expired) {
@@ -264,10 +259,10 @@ export class TaskDriver {
264
259
  async detectIdleLoop(channelDir, channelId, entries, nowMs) {
265
260
  let paused = false;
266
261
  for (const entry of entries) {
267
- const cycle = entry.fields.cycle;
268
- if (!cycle || cycle.steps < IDLE_STEP_LIMIT)
262
+ const usage = entry.fields.usage;
263
+ if (!usage || usage.steps < IDLE_STEP_LIMIT)
269
264
  continue;
270
- const steps = (await readTaskLog(channelDir, entry.id, { cycle: cycle.id, kinds: ["step"] })).slice(-IDLE_STEP_LIMIT);
265
+ const steps = (await readTaskLog(channelDir, entry.id, { kinds: ["step"] })).slice(-IDLE_STEP_LIMIT);
271
266
  if (steps.length < IDLE_STEP_LIMIT)
272
267
  continue;
273
268
  const idle = steps.every((record) => record.kind === "step" && record.tools.length === 0);
@@ -285,7 +280,7 @@ export class TaskDriver {
285
280
  async runOnce(now = new Date()) {
286
281
  if (this.options.isEnabled?.() === false || this.running)
287
282
  return;
288
- const settings = this.options.getSettings();
283
+ const settings = this.options.settings ?? TASK_DRIVER_SETTINGS;
289
284
  const nowMs = now.getTime();
290
285
  this.running = true;
291
286
  this.nextWakeMs = undefined;
@@ -321,7 +316,7 @@ export class TaskDriver {
321
316
  for (const entry of entries) {
322
317
  if (!entry.runnable)
323
318
  continue;
324
- const status = checkBudget(entry.fields, now);
319
+ const status = checkBudget(entry.fields);
325
320
  if (!status.breach || !status.reason) {
326
321
  budgeted.push(entry);
327
322
  continue;