@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.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 (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  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-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -1,115 +1,18 @@
1
- import { existsSync } from "node:fs";
2
- import { readdir, readFile, unlink } from "node:fs/promises";
3
1
  import { join } from "node:path";
4
- import { parseScheduledEventContent } from "../../events/events.js";
5
- import * as log from "../../log.js";
6
- import { parseLocalTime } from "../../shared/local-time.js";
7
- import { errorMessage } from "../../shared/text-utils.js";
8
- import { createCycle, nextCycleId } from "../../tasks/cycle.js";
9
- import { renderStandardTaskBody, renderTaskDocument } from "../../tasks/ledger.js";
10
- import { parseTaskEventName } from "../../tasks/task-events.js";
11
- import { validateTaskSchedule } from "../../tasks/task-schedule.js";
2
+ import { uncheckedTaskAcceptanceItems } from "../../tasks/ledger.js";
3
+ import { appendTaskLog } from "../../tasks/log.js";
4
+ import { archiveTask, writeStoredTask } from "../../tasks/store.js";
12
5
  import { describeTicket } from "../../tasks/ticket.js";
13
- import { completionVerificationBlockReason } from "../../tasks/verification.js";
14
6
  import { RecoverableToolError } from "../tool-details.js";
15
7
  export function tasksDir(options) {
16
8
  return join(options.channelDir, "tasks");
17
9
  }
18
- export function eventsDir(options) {
19
- return join(options.workspaceDir, "events");
20
- }
21
- export function renderTaskFile(fields, body) {
22
- return renderTaskDocument(fields, body);
23
- }
24
10
  export function requiredField(value, field, action) {
25
11
  const trimmed = value?.trim();
26
12
  if (!trimmed)
27
13
  throw new RecoverableToolError(`${action} requires ${field}.`);
28
14
  return trimmed;
29
15
  }
30
- export function markdownValue(value) {
31
- const lines = value.trim().split(/\r?\n/);
32
- if (lines.length === 1)
33
- return lines[0];
34
- return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
35
- }
36
- /** The `## 上次结果` paragraph a close writes into the contract. */
37
- export function renderCloseEvidence(request) {
38
- const summary = requiredField(request.summary, "summary", "task_close outcome=complete");
39
- const evidence = requiredField(request.evidence, "evidence", "task_close outcome=complete");
40
- const lines = [`- Summary: ${markdownValue(summary)}`, `- Evidence: ${markdownValue(evidence)}`];
41
- const residualRisk = request.residualRisk?.trim();
42
- if (residualRisk)
43
- lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
44
- return lines.join("\n");
45
- }
46
- export function normalizeBudget(budget) {
47
- if (!budget)
48
- return undefined;
49
- const next = {};
50
- for (const key of ["steps", "wallMin", "usd", "rounds"]) {
51
- const value = budget[key];
52
- if (value === undefined)
53
- continue;
54
- if (!Number.isFinite(value) || value <= 0) {
55
- throw new RecoverableToolError(`budget.${key} must be a positive number.`);
56
- }
57
- next[key] = value;
58
- }
59
- if (budget.until !== undefined) {
60
- const trimmed = budget.until.trim();
61
- if (trimmed) {
62
- // `budget.ts` runs `until` through `parseLocalTime` and silently drops the deadline on a
63
- // parse failure, so validate it here with the same parser — a mistyped stop-time should
64
- // be a recoverable error, not a task with no hard stop.
65
- if (parseLocalTime(trimmed) === undefined) {
66
- throw new RecoverableToolError(`budget.until "${budget.until}" is not a parseable local time. Use e.g. 2026-09-06T18:00:00+08:00.`);
67
- }
68
- next.until = trimmed;
69
- }
70
- else {
71
- next.until = undefined;
72
- }
73
- }
74
- return Object.keys(next).length > 0 ? next : undefined;
75
- }
76
- export function normalizeSchedule(schedule) {
77
- if (schedule === undefined)
78
- return undefined;
79
- const trimmed = schedule.trim();
80
- if (!trimmed)
81
- return null; // explicit clear
82
- validateTaskSchedule(trimmed);
83
- return trimmed;
84
- }
85
- /**
86
- * A newly created task starts `open` — even a recurring one. Creation opens its first cycle
87
- * immediately rather than parking until the next cron occurrence, because "create it and it does
88
- * nothing until tomorrow morning" was consistently surprising; the cadence still governs every
89
- * *subsequent* cycle through the `schedule` ticket the loop parks on when it finishes.
90
- */
91
- export function renderTaskSkeleton(request, now = new Date()) {
92
- const schedule = normalizeSchedule(request.schedule);
93
- const fields = {
94
- state: "open",
95
- schedule: schedule ?? undefined,
96
- // The first cycle opens at creation: steps, rework rounds and cost all accumulate onto a
97
- // cycle, so a task without one would have nowhere to record what it did.
98
- cycle: createCycle(nextCycleId(undefined, now), now),
99
- budget: normalizeBudget(request.budget),
100
- verify: request.verificationRequired ? "required" : undefined,
101
- };
102
- const body = renderStandardTaskBody({
103
- title: request.title,
104
- goal: request.goal,
105
- dod: request.dod,
106
- manual: request.manual,
107
- verificationPlan: request.verificationPlan,
108
- verificationRequired: request.verificationRequired ?? false,
109
- plan: request.plan,
110
- });
111
- return { fields, body };
112
- }
113
16
  /** The scheduling half of a lifecycle notice: where the task stands and who will wake it. */
114
17
  export function describeTaskState(fields) {
115
18
  if (fields.paused)
@@ -119,109 +22,67 @@ export function describeTaskState(fields) {
119
22
  }
120
23
  return `state: ${fields.state}`;
121
24
  }
25
+ /** A run with no wall-clock limit of its own is given up on after a day, like v4's default backstop. */
26
+ const DEFAULT_RUN_DEADLINE_MS = 24 * 60 * 60 * 1000;
122
27
  /**
123
- * Build the injected lookup a ticket resolver needs. The run/job/event registries are read here —
124
- * once, at the call site — rather than imported inside `ticket.ts`, which is what keeps the whole
125
- * validation matrix unit-testable against plain fakes.
28
+ * Delegations and background jobs bound to `taskId` that have not settled yet, each with the
29
+ * instant its owner gives up on it. The registries are read here — once, at the call site —
30
+ * rather than imported inside `ticket.ts`, which is what keeps the whole validation matrix
31
+ * unit-testable against plain fakes.
126
32
  */
127
- export async function buildTicketContext(options, taskId, schedule, now = new Date()) {
128
- const runManager = options.runManager;
33
+ export async function listPendingWork(options, taskId) {
34
+ const pending = [];
35
+ for (const run of options.runManager.list()) {
36
+ if (run.taskId !== taskId || run.settledAt !== undefined)
37
+ continue;
38
+ const deadline = run.deadlineAt ??
39
+ (run.maxWallTimeSec ? run.startedAt + run.maxWallTimeSec * 1000 : run.startedAt + DEFAULT_RUN_DEADLINE_MS);
40
+ pending.push({ ref: run.runId, deadlineMs: deadline });
41
+ }
129
42
  const jobs = await options.jobManager.list().catch(() => []);
130
- const events = await readChannelEvents(options);
131
- return {
132
- now,
133
- taskId,
134
- channelId: options.channelId,
135
- schedule,
136
- findRun: (id) => runManager.get(id),
137
- findJob: (id) => jobs.find((job) => job.id === id),
138
- findEvent: (name) => events.get(name),
139
- };
140
- }
141
- /** Every parseable event definition in the workspace, by name. Missing directory → empty. */
142
- async function readChannelEvents(options) {
143
- const dir = eventsDir(options);
144
- const events = new Map();
145
- if (!existsSync(dir))
146
- return events;
147
- for (const filename of await readdir(dir)) {
148
- if (!filename.endsWith(".json"))
43
+ for (const job of jobs) {
44
+ if (job.taskId !== taskId || job.status !== "running")
149
45
  continue;
150
- try {
151
- const event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
152
- events.set(filename.slice(0, -".json".length), {
153
- type: event.type,
154
- channelId: event.channelId,
155
- schedule: event.type === "periodic" ? event.schedule : undefined,
156
- });
157
- }
158
- catch {
159
- // An unparseable event cannot back a ticket; leave it for /events to clean up.
160
- }
46
+ pending.push({ ref: job.id, deadlineMs: job.startedAt + job.timeoutSeconds * 1000 });
161
47
  }
162
- return events;
48
+ return pending;
49
+ }
50
+ export async function buildTicketContext(options, taskId, now = new Date()) {
51
+ const pending = await listPendingWork(options, taskId);
52
+ return { now, pendingWork: () => pending };
163
53
  }
164
54
  /**
165
- * On close-out (complete or cancel), delete every task-owned event.
55
+ * Close a task: the one close-out both `task_step_end outcome=done` and `task_close` share
56
+ * (spec 052, D6/D7).
166
57
  *
167
- * Matching is done by parsing each candidate name and comparing the full task id, not by prefix —
168
- * a prefix match on `task.<channel>.<id>.` would also match a *different* task whose id happens to
169
- * start with this one plus a dot (e.g. closing "v1" must not delete events owned by "v1.2-release").
58
+ * `complete` has two gates, both cheap and both about the *leader's* own state rather than any
59
+ * runtime proof: every DoD item is checked off (the leader's explicit confirmation), and nothing
60
+ * bound to the task is still in flight (otherwise the project would be archived and the late
61
+ * result would fall back into the chat). `cancel` has neither gate — abandoning work must always
62
+ * be possible — but reports what was left running, because closing a task never cancels it.
170
63
  */
171
- export async function cleanupTaskEvents(options, id) {
172
- const dir = eventsDir(options);
173
- if (!existsSync(dir))
174
- return { deleted: [] };
175
- const deleted = [];
176
- for (const filename of (await readdir(dir)).sort()) {
177
- if (!filename.endsWith(".json"))
178
- continue;
179
- const parsed = parseTaskEventName(filename.slice(0, -".json".length), options.channelId);
180
- if (parsed?.id !== id)
181
- continue;
182
- const eventPath = join(dir, filename);
183
- let content;
184
- try {
185
- content = await readFile(eventPath, "utf-8");
186
- }
187
- catch (error) {
188
- log.logWarning(`Could not read task-owned event ${filename} during cleanup`, `${errorMessage(error)}. Fix filesystem access, then use /events show ${filename.slice(0, -".json".length)} and retry cleanup.`);
189
- continue;
190
- }
191
- try {
192
- parseScheduledEventContent(content, filename);
64
+ export async function closeTaskDocument(input) {
65
+ const { options, document, id, outcome, note } = input;
66
+ const pending = (await listPendingWork(options, id)).map((item) => item.ref);
67
+ if (outcome === "complete") {
68
+ const unchecked = uncheckedTaskAcceptanceItems(document.body);
69
+ if (unchecked.length > 0) {
70
+ throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
193
71
  }
194
- catch {
195
- continue; // can't classify → leave it for /events to handle
72
+ if (pending.length > 0) {
73
+ throw new RecoverableToolError(`Task "${id}" still has work in flight (${pending.join(", ")}). Wait for it (park on a work ticket), or cancel it with subagent_run / job before finishing.`);
196
74
  }
197
- await unlink(eventPath);
198
- deleted.push(filename.slice(0, -".json".length));
199
75
  }
200
- return { deleted };
201
- }
202
- /**
203
- * The verification gate both close entry points share (`task_step_end outcome=done` and
204
- * `task_close outcome=complete`).
205
- *
206
- * It exists as one function because the two used to ask the question separately and both asked
207
- * the weaker one — "did a PASS ever land in this cycle" — which a contract edit or a further code
208
- * change made *after* the PASS would still satisfy. The real check is re-run here, against the
209
- * contract and the checkout as they stand at close time.
210
- */
211
- export async function assertVerificationHoldsForClose(options, document, id) {
212
- if (document.fields.verify !== "required")
213
- return;
214
- const runManager = options.runManager;
215
- const reason = await completionVerificationBlockReason({
216
- channelDir: options.channelDir,
217
- taskId: id,
218
- taskBody: document.body,
219
- cycleId: document.fields.cycle?.id,
220
- findRunWorkingDirectory: (runId) => runManager.get(runId)?.workingDirectory,
221
- fallbackWorkingDirectory: options.workingDirectory,
76
+ await input.afterChecks?.();
77
+ const usage = document.fields.usage;
78
+ await appendTaskLog(options.channelDir, id, {
79
+ kind: "close",
80
+ outcome: outcome === "complete" ? "done" : "cancelled",
81
+ note,
82
+ steps: input.steps ?? usage?.steps ?? 0,
83
+ usd: usage?.usd ?? 0,
222
84
  });
223
- if (!reason)
224
- return;
225
- throw new RecoverableToolError(`Task "${id}" requires independent verification and it does not currently hold: ${reason}. ` +
226
- `Dispatch a purpose=verify sub-agent with taskId=${id} against the artifact you are about to deliver, and let its PASS land before finishing.`);
85
+ await writeStoredTask(document);
86
+ await archiveTask(options.channelDir, id, outcome === "complete" ? "completed" : "cancelled");
87
+ return { stillRunning: outcome === "cancel" ? pending : [] };
227
88
  }
@@ -1,11 +1,11 @@
1
1
  import type { TaskManageResult, TaskManageToolOptions, TaskStepEndRequest } from "./types.js";
2
2
  /**
3
- * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4).
3
+ * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4; narrowed by spec 052, D7).
4
4
  *
5
- * One tool with four outcomes replaces v3's `task_update(note)` + `task_close` + the
6
- * status/wake/waitingFor triple the model had to keep mutually consistent. The model states an
7
- * *intent* ("keep going", "wait for this", "we're done", "I'm stuck") and the runtime derives the
8
- * state, so an illegal combination — parked with nothing to wait for, active with a future wake —
9
- * is not expressible rather than merely diagnosed afterwards by `/tasks doctor`.
5
+ * One tool with three outcomes: the model states an *intent* ("keep going", "wait for this",
6
+ * "we're done") and the runtime derives the state, so an illegal combination — parked with
7
+ * nothing to wait for, active with a future wake — is not expressible rather than merely
8
+ * diagnosed afterwards. Asking the user is not a fourth outcome but a park on an `ask` ticket,
9
+ * which the runtime also announces.
10
10
  */
11
11
  export declare function endTaskStep(options: TaskManageToolOptions, request: TaskStepEndRequest): Promise<TaskManageResult>;
@@ -1,19 +1,18 @@
1
- import { renderCloseSummary, writeLastResult } from "../../tasks/cycle.js";
2
- import { applyTaskPlanPatch, normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../tasks/ledger.js";
1
+ import { applyTaskItemsPatch, normalizeTaskId } from "../../tasks/ledger.js";
3
2
  import { appendTaskLog } from "../../tasks/log.js";
4
3
  import { queueTaskNotice } from "../../tasks/steer.js";
5
- import { archiveTask, readStoredTask, writeStoredTask } from "../../tasks/store.js";
4
+ import { readStoredTask, writeStoredTask } from "../../tasks/store.js";
6
5
  import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
7
6
  import { RecoverableToolError } from "../tool-details.js";
8
- import { assertVerificationHoldsForClose, buildTicketContext, cleanupTaskEvents, requiredField } from "./shared.js";
7
+ import { buildTicketContext, closeTaskDocument, requiredField } from "./shared.js";
9
8
  /**
10
- * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4).
9
+ * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4; narrowed by spec 052, D7).
11
10
  *
12
- * One tool with four outcomes replaces v3's `task_update(note)` + `task_close` + the
13
- * status/wake/waitingFor triple the model had to keep mutually consistent. The model states an
14
- * *intent* ("keep going", "wait for this", "we're done", "I'm stuck") and the runtime derives the
15
- * state, so an illegal combination — parked with nothing to wait for, active with a future wake —
16
- * is not expressible rather than merely diagnosed afterwards by `/tasks doctor`.
11
+ * One tool with three outcomes: the model states an *intent* ("keep going", "wait for this",
12
+ * "we're done") and the runtime derives the state, so an illegal combination — parked with
13
+ * nothing to wait for, active with a future wake — is not expressible rather than merely
14
+ * diagnosed afterwards. Asking the user is not a fourth outcome but a park on an `ask` ticket,
15
+ * which the runtime also announces.
17
16
  */
18
17
  export async function endTaskStep(options, request) {
19
18
  if (!options.taskId) {
@@ -23,103 +22,65 @@ export async function endTaskStep(options, request) {
23
22
  const document = await readStoredTask(options.channelDir, id);
24
23
  if (!document)
25
24
  throw new RecoverableToolError(`Task "${id}" no longer exists; nothing to end.`);
26
- const cycleId = document.fields.cycle?.id ?? options.cycleId ?? "-";
27
25
  const note = requiredField(request.note, "note", "task_step_end");
28
- // Also reject stale callers that bypass the schema, which no longer exposes schedule tickets.
29
- if (request.outcome === "park" && request.ticket?.kind === "schedule") {
30
- throw new RecoverableToolError("To finish this cycle, use outcome=done with summary and evidence; the runtime schedules the next occurrence. To skip it, use task_close outcome=skip with a reason. Use a time ticket to wait within this cycle.");
26
+ if (request.items?.length) {
27
+ document.body = applyTaskItemsPatch(document.body, request.items).body;
31
28
  }
32
- if (request.planSteps?.length) {
33
- document.body = applyTaskPlanPatch(document.body, request.planSteps).body;
29
+ const seq = (document.fields.usage?.steps ?? 0) + 1;
30
+ // The step's own model cost joins the task's usage here, before a `done` writes its close
31
+ // record; bound delegations add theirs when they settle. A rough figure by design.
32
+ const cost = options.getStepCost?.();
33
+ const usd = cost && cost.usd > 0 ? cost.usd : 0;
34
+ const usdEstimated = cost?.estimated === true;
35
+ const usage = document.fields.usage;
36
+ if (usage) {
37
+ document.fields.usage = {
38
+ ...usage,
39
+ steps: seq,
40
+ usd: usage.usd + usd,
41
+ usdEstimated: usage.usdEstimated || usdEstimated,
42
+ };
34
43
  }
35
- const seq = (document.fields.cycle?.steps ?? 0) + 1;
36
- if (document.fields.cycle)
37
- document.fields.cycle = { ...document.fields.cycle, steps: seq };
38
44
  const tools = [...new Set(options.getToolsUsed?.() ?? [])];
45
+ const report = request.report?.trim();
39
46
  const logStep = async (outcome) => {
40
- await appendTaskLog(options.channelDir, id, { cycle: cycleId, kind: "step", seq, outcome, note, tools });
47
+ await appendTaskLog(options.channelDir, id, {
48
+ kind: "step",
49
+ seq,
50
+ outcome,
51
+ note,
52
+ tools,
53
+ ...(report ? { report } : {}),
54
+ ...(usd > 0 ? { usd } : {}),
55
+ ...(usdEstimated ? { usdEstimated: true } : {}),
56
+ });
41
57
  };
42
- // Steps are silent by default (D3); `notify` is the explicit opt-in the runtime delivers once
43
- // the step ends. `blocked` always speaks — a task waiting on the user that says nothing is the
44
- // same silent dead end tickets exist to prevent.
45
- //
46
- // The notice is an *outbound side effect*: it must not land before every recoverable check
47
- // (required fields, unmet acceptance items, verification hold, ticket resolution) has passed,
48
- // or a rejected `outcome=done` still tells the channel "task complete" and a corrected retry
49
- // queues a second notice. So compute it here and only flush it past a successful
50
- // `writeStoredTask` + `logStep`, right before each return.
51
- const pendingNotice = request.notify?.trim()
52
- ? request.notify.trim()
53
- : request.outcome === "blocked"
54
- ? `任务 ${id} 需要你的决定:${request.reason ?? note}`
55
- : undefined;
58
+ // Steps are silent by default (D9); `report` is the explicit opt-in the runtime delivers once
59
+ // the step ends. The notice is an *outbound side effect*: it must not land before every
60
+ // recoverable check (required fields, unmet acceptance items, work in flight, ticket
61
+ // resolution) has passed, or a rejected `outcome=done` still tells the channel "task complete"
62
+ // and a corrected retry queues a second notice. So it is computed here and only flushed past a
63
+ // successful write, right before each return.
64
+ let pendingNotice = report || undefined;
56
65
  const flushNotice = async () => {
57
66
  if (pendingNotice)
58
67
  await queueTaskNotice(options.channelDir, id, pendingNotice);
59
68
  };
60
69
  if (request.outcome === "done") {
61
- const summary = requiredField(request.summary, "summary", "task_step_end outcome=done");
62
- const evidence = requiredField(request.evidence, "evidence", "task_step_end outcome=done");
63
- const unchecked = uncheckedTaskAcceptanceItems(document.body);
64
- if (unchecked.length > 0) {
65
- throw new RecoverableToolError(`Task "${id}" still has unmet acceptance items: ${unchecked.slice(0, 3).join("; ")}. Check them off with edit once the evidence holds.`);
66
- }
67
- // Verification is imported by the runtime when a purpose=verify run settles (D7), so what
68
- // gates `done` here is the cycle's verification ledger — not whether the model remembered to
69
- // call an import tool. The settled verdict is re-bound to the contract and the checkout as
70
- // they are *now*: a PASS is evidence about the artifact the verifier saw, and the loop can
71
- // edit both after it lands.
72
- await assertVerificationHoldsForClose(options, document, id);
73
- const cycle = document.fields.cycle;
74
- document.body = writeLastResult(document.body, renderCloseSummary({
75
- cycleId,
76
- outcome: "done",
77
- summary,
78
- evidence,
79
- residualRisk: request.residualRisk,
80
- steps: cycle?.steps ?? seq,
81
- rounds: cycle?.rounds ?? 0,
82
- usd: cycle?.usd ?? 0,
83
- usdEstimated: cycle?.usdEstimated ?? false,
84
- }));
85
- await appendTaskLog(options.channelDir, id, {
86
- cycle: cycleId,
87
- kind: "close",
88
- outcome: "done",
89
- summary,
90
- evidence,
91
- residualRisk: request.residualRisk,
92
- steps: cycle?.steps ?? seq,
93
- rounds: cycle?.rounds ?? 0,
94
- usd: cycle?.usd ?? 0,
70
+ await closeTaskDocument({
71
+ options,
72
+ document,
73
+ id,
74
+ outcome: "complete",
75
+ note,
76
+ steps: seq,
77
+ afterChecks: () => logStep("done"),
95
78
  });
96
- if (document.fields.schedule) {
97
- // Recurring: park on the next occurrence rather than archiving. The contract, the Plan
98
- // and the loop log all survive into the next cycle; only the counters reset.
99
- const context = await buildTicketContext(options, id, document.fields.schedule);
100
- const ticket = resolveTicket({ kind: "schedule" }, context);
101
- document.fields.state = "parked";
102
- document.fields.ticket = ticket;
103
- await writeStoredTask(document);
104
- await logStep("done");
105
- await flushNotice();
106
- return {
107
- action: "step_end",
108
- id,
109
- state: "parked",
110
- notice: `任务 \`${id}\` 本周期完成,${describeTicket(ticket)}。`,
111
- };
112
- }
113
- await writeStoredTask(document);
114
- await logStep("done");
115
79
  await flushNotice();
116
- const { deleted } = await cleanupTaskEvents(options, id);
117
- await archiveTask(options.channelDir, id, "completed");
118
80
  return {
119
81
  action: "step_end",
120
82
  id,
121
83
  archived: true,
122
- deletedEvents: deleted,
123
84
  notice: `任务 \`${id}\` 已完成并归档。`,
124
85
  };
125
86
  }
@@ -130,18 +91,20 @@ export async function endTaskStep(options, request) {
130
91
  notice = `步骤已记录,任务 \`${id}\` 继续。`;
131
92
  }
132
93
  else {
133
- // `blocked` is `park` on an `ask` ticket: a task that needs the user is still a task with a
134
- // verifiable, backstopped wait, not a special state that could go quiet.
135
- const input = request.outcome === "blocked"
136
- ? { kind: "ask", asked: requiredField(request.reason, "reason", "task_step_end outcome=blocked") }
137
- : request.ticket;
138
- if (!input) {
94
+ if (!request.ticket) {
139
95
  throw new RecoverableToolError("task_step_end outcome=park requires a ticket describing what will wake this task.");
140
96
  }
141
- const context = await buildTicketContext(options, id, document.fields.schedule);
142
- const ticket = resolveTicket(input, context);
97
+ const context = await buildTicketContext(options, id);
98
+ const ticket = resolveTicket(request.ticket, context);
143
99
  document.fields.state = "parked";
144
100
  document.fields.ticket = ticket;
101
+ // A task waiting on the user that says nothing is the same silent dead end tickets exist to
102
+ // prevent, so an `ask` park always speaks.
103
+ if (ticket.kind === "ask") {
104
+ pendingNotice = [report, `任务 ${id} 需要你的决定:${ticket.asked}\n用 /tasks reply ${id} <内容> 回答。`]
105
+ .filter(Boolean)
106
+ .join("\n\n");
107
+ }
145
108
  notice = `任务 \`${id}\` 已停泊:${describeTicket(ticket)}(兜底 ${ticket.by})。`;
146
109
  }
147
110
  await writeStoredTask(document);
@@ -8,16 +8,14 @@ export interface TaskManageResult {
8
8
  path?: string;
9
9
  state?: string;
10
10
  archived?: boolean;
11
- deletedEvents?: string[];
12
11
  tasks?: Array<{
13
12
  id: string;
14
13
  title: string;
15
14
  state: string;
16
15
  paused: boolean;
17
16
  ticket?: string;
18
- cycle?: string;
19
17
  steps?: number;
20
- rounds?: number;
18
+ items?: string;
21
19
  }>;
22
20
  /** Rendered log lines, for `task_log`. */
23
21
  entries?: string[];
@@ -35,15 +33,16 @@ export type TaskStepEndRequest = Static<typeof taskStepEndSchema>;
35
33
  export interface TaskManageToolOptions {
36
34
  jobManager: ChannelJobManager;
37
35
  runManager: SubAgentRunManager;
38
- workspaceDir: string;
39
36
  channelDir: string;
40
- channelId: string;
41
- /** Project checkout whose artifact state an independent verifier binds to. */
42
- workingDirectory?: string;
43
37
  /** Present only inside a task session: which task's loop this tool set belongs to. */
44
38
  taskId?: string;
45
- /** Present only inside a task session: the cycle the current step belongs to. */
46
- cycleId?: string;
47
39
  /** Tools this step has completed so far; feeds the loop log's idle-step evidence (D6). */
48
40
  getToolsUsed?: () => string[];
41
+ /** This step's own model cost so far (bound delegations are credited at their settlement). */
42
+ getStepCost?: () => TaskStepCost;
43
+ }
44
+ /** A rough figure: `estimated` when some model in the step has no pricing metadata. */
45
+ export interface TaskStepCost {
46
+ usd: number;
47
+ estimated: boolean;
49
48
  }
@@ -33,7 +33,7 @@ export function createTaskCreateTool(options) {
33
33
  return {
34
34
  name: "task_create",
35
35
  label: "task_create",
36
- description: "Create a persistent task: goal, DoD, and optional plan, manual, verification plan, schedule, budget.",
36
+ description: "Create a persistent project you lead: goal, DoD checklist, optional Work Items and budget. The runtime then drives it in its own session; delegate pieces with subagent (bound to the task automatically in that session).",
37
37
  parameters: taskCreateSchema,
38
38
  execute: async (_toolCallId, args) => {
39
39
  const result = await withLock(options, args.id, () => createTask(options, args));
@@ -45,7 +45,7 @@ export function createTaskUpdateTool(options) {
45
45
  return {
46
46
  name: "task_update",
47
47
  label: "task_update",
48
- description: "Edit a task's plan steps, cadence, budget, or verification requirement. Progress goes to task_step_end.",
48
+ description: "Edit a task's Work Items or budget. Progress goes to task_step_end.",
49
49
  parameters: taskUpdateSchema,
50
50
  execute: async (_toolCallId, args) => {
51
51
  const result = await withLock(options, args.id, () => updateTask(options, args));
@@ -57,7 +57,7 @@ export function createTaskCloseTool(options) {
57
57
  return {
58
58
  name: "task_close",
59
59
  label: "task_close",
60
- description: "Close a task: outcome complete, skip (one recurring occurrence), or cancel.",
60
+ description: "Close a task: complete (DoD all checked, nothing in flight) or cancel.",
61
61
  parameters: taskCloseSchema,
62
62
  execute: async (_toolCallId, args) => {
63
63
  const result = await withLock(options, args.id, () => closeTask(options, args));
@@ -69,7 +69,7 @@ export function createTaskLogTool(options) {
69
69
  return {
70
70
  name: "task_log",
71
71
  label: "task_log",
72
- description: "Read a task's loop log: steps, verification rounds, expiries and cycle closes.",
72
+ description: "Read a task's loop log: steps, dispatches, settlements, expiries and the close.",
73
73
  parameters: taskLogSchema,
74
74
  execute: async (_toolCallId, args) => {
75
75
  const result = await readTaskLogTool(options, args);
@@ -81,7 +81,7 @@ export function createTaskStepEndTool(options) {
81
81
  return {
82
82
  name: "task_step_end",
83
83
  label: "task_step_end",
84
- description: "End this task step: continue (more work now), park (wait on a ticket), done (close the cycle), or blocked (ask the user).",
84
+ description: "End this task step: continue (more work now), park (wait on a time/work/ask ticket), or done (the project is finished).",
85
85
  parameters: taskStepEndSchema,
86
86
  execute: async (_toolCallId, args) => {
87
87
  const result = await withLock(options, options.taskId ?? "", () => endTaskStep(options, args));