@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,47 +1,23 @@
1
1
  import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
2
2
  import { RecoverableToolError } from "../shared/recoverable-error.js";
3
3
  import { isPlainObject } from "../shared/type-guards.js";
4
- import { nextTaskWake } from "./task-schedule.js";
5
- const TICKET_KINDS = ["time", "schedule", "run", "job", "ask", "signal"];
6
- /** A ticket the runtime cannot pin to a real occurrence still gets a backstop this far out. */
7
- const DEFAULT_BACKSTOP_MS = 24 * 60 * 60 * 1000;
8
- /** Slack added to a run's own wall-clock deadline before the task gives up on it. */
9
- const RUN_BACKSTOP_SLACK_MS = 10 * 60 * 1000;
4
+ const TICKET_KINDS = ["time", "work", "ask"];
5
+ /** `ask` has no source that could report back on its own, so it gets a generous fixed backstop. */
6
+ const ASK_BACKSTOP_MS = 24 * 60 * 60 * 1000;
7
+ /** Slack added to the latest pending deadline before the task gives up on the work. */
8
+ const WORK_BACKSTOP_SLACK_MS = 10 * 60 * 1000;
10
9
  function requiredString(value, field) {
11
10
  if (typeof value !== "string" || !value.trim()) {
12
11
  throw new RecoverableToolError(`ticket.${field} is required and must be a non-empty string.`);
13
12
  }
14
13
  return value.trim();
15
14
  }
16
- /**
17
- * The interval between the next two occurrences of `cron` after `from`, or `undefined` when the
18
- * cron does not fire at least twice. Used to express backstops as "one/two missed occurrences"
19
- * rather than a fixed wall-clock guess, so a 30-minute sensor and a monthly job get proportionate
20
- * patience from the same rule.
21
- */
22
- function occurrenceInterval(cron, from) {
23
- const first = nextTaskWake(cron, from);
24
- if (!first)
25
- return undefined;
26
- const second = nextTaskWake(cron, first);
27
- if (!second)
28
- return { first, intervalMs: DEFAULT_BACKSTOP_MS };
29
- return { first, intervalMs: second.getTime() - first.getTime() };
30
- }
31
- function scheduleBackstop(cron, now, missedOccurrences) {
32
- const occurrence = occurrenceInterval(cron, now);
33
- if (!occurrence) {
34
- throw new RecoverableToolError(`schedule "${cron}" never fires again; it cannot back a ticket.`);
35
- }
36
- return formatLocalTime(new Date(occurrence.first.getTime() + occurrence.intervalMs * missedOccurrences));
37
- }
38
15
  /**
39
16
  * Validate one model-supplied ticket and stamp its backstop.
40
17
  *
41
- * This is the **only** way a `Ticket` value comes into existence — the migrator, `task_step_end`
42
- * and the `/tasks` commands all funnel through it. Anything that writes the `ticket` frontmatter
43
- * field directly is a defect: it would produce a park with no verified source or no `by`, which
44
- * is precisely the failure this whole mechanism exists to make impossible.
18
+ * This is the **only** way a `Ticket` value comes into existence — `task_step_end`, `/tasks
19
+ * reply` and the converter all funnel through it. Anything that writes the `ticket` frontmatter
20
+ * field directly is a defect: it would produce a park with no verified source or no `by`.
45
21
  */
46
22
  export function resolveTicket(input, ctx) {
47
23
  if (!isPlainObject(input)) {
@@ -65,80 +41,26 @@ export function resolveTicket(input, ctx) {
65
41
  const at = formatLocalTime(new Date(atMs));
66
42
  return { kind: "time", at, by: at };
67
43
  }
68
- case "schedule": {
69
- if (!ctx.schedule) {
70
- throw new RecoverableToolError("A schedule ticket needs the task to have a `schedule` cron. Set one, or park on a time ticket instead.");
71
- }
72
- // The occurrence is stamped, not recomputed on read: a ticket must name a fixed moment,
73
- // or "is it due yet?" would keep answering "not yet" as the cron rolls forward.
74
- const occurrence = occurrenceInterval(ctx.schedule, ctx.now);
75
- if (!occurrence) {
76
- throw new RecoverableToolError(`schedule "${ctx.schedule}" never fires again; it cannot back a ticket.`);
44
+ case "work": {
45
+ const pending = ctx.pendingWork();
46
+ if (pending.length === 0) {
47
+ throw new RecoverableToolError("This task has no delegation or background job in flight, so a work ticket has nothing to wait for. " +
48
+ "Every result so far is already on the <task_board>: read it and continue, or dispatch more work first (with the task bound).");
77
49
  }
50
+ const latest = Math.max(...pending.map((item) => item.deadlineMs));
78
51
  return {
79
- kind: "schedule",
80
- at: formatLocalTime(occurrence.first),
81
- by: scheduleBackstop(ctx.schedule, ctx.now, 1),
52
+ kind: "work",
53
+ refs: pending.map((item) => item.ref),
54
+ by: formatLocalTime(new Date(latest + WORK_BACKSTOP_SLACK_MS)),
82
55
  };
83
56
  }
84
- case "run": {
85
- const id = requiredString(input.id, "id");
86
- const run = ctx.findRun(id);
87
- if (!run) {
88
- throw new RecoverableToolError(`No run "${id}" in this channel. Use subagent_list to find the right id, or park on a different ticket.`);
89
- }
90
- if (run.settledAt !== undefined) {
91
- throw new RecoverableToolError(`Run ${id} already settled; read its result and continue instead of parking on it.`);
92
- }
93
- if (run.taskId !== ctx.taskId) {
94
- throw new RecoverableToolError(`Run ${id} belongs to task ${run.taskId ?? "(none)"}; it will never wake this task. Dispatch with taskId=${ctx.taskId}.`);
95
- }
96
- const deadline = run.deadlineAt ?? (run.maxWallTimeSec ? run.startedAt + run.maxWallTimeSec * 1000 : undefined);
97
- const by = (deadline ?? run.startedAt + DEFAULT_BACKSTOP_MS) + RUN_BACKSTOP_SLACK_MS;
98
- return { kind: "run", id, by: formatLocalTime(new Date(by)) };
99
- }
100
- case "job": {
101
- const id = requiredString(input.id, "id");
102
- const job = ctx.findJob(id);
103
- if (!job) {
104
- throw new RecoverableToolError(`No job "${id}" in this channel. Use job op=list to find the right id, or park on a different ticket.`);
105
- }
106
- if (job.status !== "running") {
107
- throw new RecoverableToolError(`Job ${id} is ${job.status}; read its output and continue instead of parking on it.`);
108
- }
109
- if (job.taskId !== ctx.taskId) {
110
- throw new RecoverableToolError(`Job ${id} belongs to task ${job.taskId ?? "(none)"}; it will never wake this task. Relaunch it with taskId=${ctx.taskId}.`);
111
- }
112
- return { kind: "job", id, by: formatLocalTime(new Date(job.startedAt + DEFAULT_BACKSTOP_MS)) };
113
- }
114
57
  case "ask": {
115
58
  const asked = requiredString(input.asked, "asked");
116
- return { kind: "ask", asked, by: formatLocalTime(new Date(nowMs + DEFAULT_BACKSTOP_MS)) };
117
- }
118
- case "signal": {
119
- const name = requiredString(input.event, "event");
120
- const event = ctx.findEvent(name);
121
- if (!event) {
122
- throw new RecoverableToolError(`No event "${name}" in this workspace. Create it with event_manage first, or park on a time ticket.`);
123
- }
124
- if (event.channelId !== ctx.channelId) {
125
- throw new RecoverableToolError(`Event "${name}" belongs to another channel; it cannot wake this task.`);
126
- }
127
- if (event.type !== "periodic" || !event.schedule) {
128
- throw new RecoverableToolError(`Event "${name}" is one-shot; a sensor must be periodic. Use a time ticket instead.`);
129
- }
130
- // The event must name this task: a signal ticket is redeemed by the events watcher on a
131
- // pure name match, so accepting an unrelated event's name here would create a park that
132
- // nothing can ever redeem (INV-7's write-side half).
133
- const expectedPrefix = `task.${ctx.channelId}.${ctx.taskId}.`;
134
- if (!name.startsWith(expectedPrefix)) {
135
- throw new RecoverableToolError(`Event "${name}" does not belong to this task; a signal ticket needs an event named ${expectedPrefix}<use>.`);
136
- }
137
- return { kind: "signal", event: name, by: scheduleBackstop(event.schedule, ctx.now, 2) };
59
+ return { kind: "ask", asked, by: formatLocalTime(new Date(nowMs + ASK_BACKSTOP_MS)) };
138
60
  }
139
61
  }
140
62
  }
141
- /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a v4 ticket. */
63
+ /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a ticket. */
142
64
  export function parseTicket(raw) {
143
65
  let value;
144
66
  try {
@@ -158,16 +80,14 @@ export function parseTicket(raw) {
158
80
  switch (kind) {
159
81
  case "time":
160
82
  return typeof value.at === "string" && value.at ? { kind: "time", at: value.at, by } : undefined;
161
- case "schedule":
162
- return typeof value.at === "string" && value.at ? { kind: "schedule", at: value.at, by } : undefined;
163
- case "run":
164
- return typeof value.id === "string" && value.id ? { kind: "run", id: value.id, by } : undefined;
165
- case "job":
166
- return typeof value.id === "string" && value.id ? { kind: "job", id: value.id, by } : undefined;
83
+ case "work": {
84
+ const refs = Array.isArray(value.refs)
85
+ ? value.refs.filter((ref) => typeof ref === "string" && ref.length > 0)
86
+ : [];
87
+ return { kind: "work", refs, by };
88
+ }
167
89
  case "ask":
168
90
  return typeof value.asked === "string" && value.asked ? { kind: "ask", asked: value.asked, by } : undefined;
169
- case "signal":
170
- return typeof value.event === "string" && value.event ? { kind: "signal", event: value.event, by } : undefined;
171
91
  }
172
92
  }
173
93
  /** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
@@ -176,34 +96,25 @@ export function ticketBackstopMs(ticket) {
176
96
  }
177
97
  /**
178
98
  * Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
179
- * deadline cannot be read is exactly the silent-forever state D2-INV forbids, so it fails toward
180
- * waking the task rather than toward leaving it buried.
99
+ * deadline cannot be read is exactly the silent-forever state the backstop forbids, so it fails
100
+ * toward waking the task rather than toward leaving it buried.
181
101
  */
182
102
  export function ticketExpired(ticket, now = new Date()) {
183
103
  const by = ticketBackstopMs(ticket);
184
104
  return by === undefined || by <= now.getTime();
185
105
  }
186
- /**
187
- * The moment a `time` ticket is *due* (as opposed to its backstop). Only `time` and `schedule`
188
- * tickets are driver-polled; every other kind is pushed by its owner, so they have no due time.
189
- */
106
+ /** The moment a `time` ticket is *due*. Only `time` tickets are driver-polled; the rest are pushed by their owner. */
190
107
  export function ticketDueMs(ticket) {
191
- return ticket.kind === "time" || ticket.kind === "schedule" ? parseLocalTime(ticket.at) : undefined;
108
+ return ticket.kind === "time" ? parseLocalTime(ticket.at) : undefined;
192
109
  }
193
110
  /** One-line summary for `/tasks`, receipts, and the step brief. */
194
111
  export function describeTicket(ticket) {
195
112
  switch (ticket.kind) {
196
113
  case "time":
197
114
  return `等待时间 ${ticket.at}`;
198
- case "schedule":
199
- return `等待下一次计划唤醒 ${ticket.at}`;
200
- case "run":
201
- return `等待委派 ${ticket.id}`;
202
- case "job":
203
- return `等待作业 ${ticket.id}`;
115
+ case "work":
116
+ return ticket.refs.length > 0 ? `等待委派/作业 ${ticket.refs.join(", ")}` : "等待委派/作业";
204
117
  case "ask":
205
118
  return `等待用户回答:${ticket.asked}`;
206
- case "signal":
207
- return `等待事件 ${ticket.event}`;
208
119
  }
209
120
  }
@@ -0,0 +1,20 @@
1
+ import { type TaskDispatchRecord, type TaskSettleRecord } from "./log.js";
2
+ /**
3
+ * The run and job managers' only way to tell a task about work bound to it (spec 052, D4).
4
+ *
5
+ * Both are best-effort by design: a task whose file has since been archived or hand-deleted must
6
+ * not block a completion wake, and a failed log write must not fail a dispatch. Each caller guards
7
+ * these with its own idempotency marker (`taskAccounted` for runs, `taskLogged` for jobs) so a
8
+ * replayed settlement writes nothing twice.
9
+ */
10
+ /** Record that a delegation or job was bound to the task. A task that no longer exists is skipped. */
11
+ export declare function logTaskDispatch(channelDir: string, taskId: string, record: Omit<TaskDispatchRecord, "ts" | "kind">): Promise<void>;
12
+ export interface TaskSettlementCost {
13
+ usd: number;
14
+ estimated: boolean;
15
+ }
16
+ /**
17
+ * Record that bound work settled and add its cost to the task's usage. The cost lands in the
18
+ * same budget the leader's own steps spend from, so a runaway fan-out stops the task.
19
+ */
20
+ export declare function logTaskSettlement(channelDir: string, taskId: string, record: Omit<TaskSettleRecord, "ts" | "kind" | "usd" | "usdEstimated">, cost?: TaskSettlementCost): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { appendTaskLog } from "./log.js";
2
+ import { readStoredTask, updateStoredTask } from "./store.js";
3
+ /**
4
+ * The run and job managers' only way to tell a task about work bound to it (spec 052, D4).
5
+ *
6
+ * Both are best-effort by design: a task whose file has since been archived or hand-deleted must
7
+ * not block a completion wake, and a failed log write must not fail a dispatch. Each caller guards
8
+ * these with its own idempotency marker (`taskAccounted` for runs, `taskLogged` for jobs) so a
9
+ * replayed settlement writes nothing twice.
10
+ */
11
+ /** Record that a delegation or job was bound to the task. A task that no longer exists is skipped. */
12
+ export async function logTaskDispatch(channelDir, taskId, record) {
13
+ if (!(await readStoredTask(channelDir, taskId)))
14
+ return;
15
+ await appendTaskLog(channelDir, taskId, { kind: "dispatch", ...record });
16
+ }
17
+ /**
18
+ * Record that bound work settled and add its cost to the task's usage. The cost lands in the
19
+ * same budget the leader's own steps spend from, so a runaway fan-out stops the task.
20
+ */
21
+ export async function logTaskSettlement(channelDir, taskId, record, cost = { usd: 0, estimated: false }) {
22
+ if (cost.usd > 0 || cost.estimated) {
23
+ await updateStoredTask(channelDir, taskId, (task) => {
24
+ const usage = task.fields.usage;
25
+ if (!usage)
26
+ return;
27
+ task.fields.usage = {
28
+ ...usage,
29
+ usd: usage.usd + Math.max(0, cost.usd),
30
+ usdEstimated: usage.usdEstimated || cost.estimated,
31
+ };
32
+ });
33
+ }
34
+ if (!(await readStoredTask(channelDir, taskId)))
35
+ return;
36
+ await appendTaskLog(channelDir, taskId, {
37
+ kind: "settle",
38
+ ...record,
39
+ ...(cost.usd > 0 ? { usd: cost.usd } : {}),
40
+ ...(cost.estimated ? { usdEstimated: true } : {}),
41
+ });
42
+ }
@@ -40,7 +40,7 @@ export interface BashToolOptions {
40
40
  */
41
41
  jobManager?: ChannelJobManager;
42
42
  /**
43
- * Set inside a task cycle's session. A background job started here belongs to this task, so the
43
+ * Set inside a task's session. A background job started here belongs to this task, so the
44
44
  * runtime binds the id rather than asking the model to repeat it (and rejects a conflicting one
45
45
  * before the job launches — the old "relaunch with taskId=…" told the model to re-run a command
46
46
  * that may have side effects). Chat sessions leave this unset and keep the optional `taskId`.
@@ -234,7 +234,7 @@ export function createBashTool(executor, options = {}) {
234
234
  text: `Background job ${job.id} started: ${jobLabel}\n` +
235
235
  (willNotify
236
236
  ? "Complete any independent work, then end the turn when only waiting remains. Completion wakes this channel with the exit code and output; do not poll or schedule a check-in. " +
237
- "Inside a task step, park with task_step_end on this job id."
237
+ 'Inside a task step, park with task_step_end on ticket {"kind":"work"}.'
238
238
  : "It runs off-turn and will NOT wake you when it finishes; check it with the job tool (op:poll/list)."),
239
239
  },
240
240
  ],
@@ -2,12 +2,25 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import { type ScheduledEvent } from "../events/events.js";
4
4
  import type { SecurityConfig } from "../security/types.js";
5
+ import type { TaskCreateInput } from "../tasks/contract-input.js";
5
6
  declare const eventManageSchema: Type.TObject<{
6
7
  action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"show">, Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
7
8
  name: Type.TOptional<Type.TString>;
8
9
  definition: Type.TOptional<Type.TObject<{
9
10
  type: Type.TUnion<[Type.TLiteral<"one-shot">, Type.TLiteral<"periodic">, Type.TLiteral<"immediate">]>;
10
- text: Type.TString;
11
+ text: Type.TOptional<Type.TString>;
12
+ task: Type.TOptional<Type.TObject<{
13
+ title: Type.TString;
14
+ goal: Type.TString;
15
+ dod: Type.TString;
16
+ items: Type.TOptional<Type.TArray<Type.TObject<{
17
+ text: Type.TString;
18
+ }>>>;
19
+ budget: Type.TOptional<Type.TObject<{
20
+ steps: Type.TOptional<Type.TInteger>;
21
+ usd: Type.TOptional<Type.TNumber>;
22
+ }>>;
23
+ }>>;
11
24
  at: Type.TOptional<Type.TString>;
12
25
  schedule: Type.TOptional<Type.TString>;
13
26
  preAction: Type.TOptional<Type.TObject<{
@@ -20,7 +33,8 @@ declare const eventManageSchema: Type.TObject<{
20
33
  export type EventManageAction = "list" | "show" | "create" | "update" | "delete";
21
34
  export type EventDefinitionInput = {
22
35
  type: "one-shot" | "periodic" | "immediate";
23
- text: string;
36
+ text?: string;
37
+ task?: TaskCreateInput;
24
38
  at?: string;
25
39
  schedule?: string;
26
40
  preAction?: {
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import { resolveEventPath } from "../events/event-commands.js";
6
6
  import { EventValidationError, MAX_EVENT_FILES, validateScheduledEvent } from "../events/event-validation.js";
7
- import { parseScheduledEventContent } from "../events/events.js";
7
+ import { describeEventPayload, parseScheduledEventContent } from "../events/events.js";
8
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
9
  import { RecoverableToolError } from "../shared/recoverable-error.js";
10
10
  import { clipText, errorMessage } from "../shared/text-utils.js";
@@ -12,7 +12,25 @@ const eventDefinitionSchema = Type.Object({
12
12
  type: Type.Union([Type.Literal("one-shot"), Type.Literal("periodic"), Type.Literal("immediate")], {
13
13
  description: '"one-shot" (needs `at`), "periodic" (needs cron `schedule`). "immediate" is always rejected.',
14
14
  }),
15
- text: Type.String({ description: "Message delivered to the channel when the event fires." }),
15
+ text: Type.Optional(Type.String({
16
+ description: "Chat message delivered to the channel when the event fires. Give either `text` or `task`, never both.",
17
+ })),
18
+ task: Type.Optional(Type.Object({
19
+ title: Type.String({ description: "Task title." }),
20
+ goal: Type.String({
21
+ description: "Goal of each spawned task: result, scope, allowed external actions, key constraints.",
22
+ }),
23
+ dod: Type.String({ description: 'Checklist items, e.g. "- [ ] <criterion>"; plain prose is rejected.' }),
24
+ items: Type.Optional(Type.Array(Type.Object({ text: Type.String({ description: "Work item text." }) }), {
25
+ description: "Initial Work Items, numbered W1…Wn in order.",
26
+ })),
27
+ budget: Type.Optional(Type.Object({
28
+ steps: Type.Optional(Type.Integer({ minimum: 1 })),
29
+ usd: Type.Optional(Type.Number({ description: "Max cost for one spawned task." })),
30
+ })),
31
+ }, {
32
+ description: "Template for a task instance. Each time the event fires, a fresh task is created from it and the runtime drives it in its own session — use it for recurring or scheduled work that needs state, delegation or checking. If the previous instance is still running, the occurrence is skipped and the user is told.",
33
+ })),
16
34
  at: Type.Optional(Type.String({ description: "one-shot local time, e.g. 2026-07-27T07:30:00+08:00 (2 min to ~24.8 days out)." })),
17
35
  schedule: Type.Optional(Type.String({ description: "periodic 5-field cron, in the host timezone." })),
18
36
  preAction: Type.Optional(Type.Object({
@@ -34,7 +52,7 @@ const eventManageSchema = Type.Object({
34
52
  description: '"list" this channel\'s events, "show" one event\'s full definition (for a safe update), or "create" / "update" / "delete" one by name.',
35
53
  }),
36
54
  name: Type.Optional(Type.String({
37
- description: "Event name (filename without .json); required for show/create/update/delete, ignored for list. Task-owned events: `task.<channelId>.<taskId>.<use>`.",
55
+ description: "Event name (filename without .json); required for show/create/update/delete, ignored for list.",
38
56
  })),
39
57
  definition: Type.Optional(eventDefinitionSchema),
40
58
  });
@@ -65,7 +83,7 @@ async function listOwnedEvents(options) {
65
83
  continue;
66
84
  const when = event.type === "one-shot" ? `at ${event.at}` : event.schedule;
67
85
  const pre = event.preAction ? " (preAction)" : "";
68
- const text = clipText(event.text, 80, { collapseWhitespace: true });
86
+ const text = clipText(describeEventPayload(event), 80, { collapseWhitespace: true });
69
87
  entries.push({ name, parsed: true, line: `- ${name} [${event.type}] ${when}${pre} — ${text}` });
70
88
  }
71
89
  return entries;
@@ -97,7 +115,10 @@ function validateDefinition(definition, name, options) {
97
115
  const onDisk = {
98
116
  type: definition.type,
99
117
  channelId: options.channelId,
100
- text: definition.text,
118
+ // Both are passed through when both are given: the parser rejects "text and task" with a
119
+ // message that says why, which a silent preference for one of them would hide.
120
+ ...(definition.text !== undefined ? { text: definition.text } : {}),
121
+ ...(definition.task ? { task: definition.task } : {}),
101
122
  ...(definition.type === "one-shot" ? { at: definition.at } : { schedule: definition.schedule }),
102
123
  ...(definition.preAction
103
124
  ? {
@@ -200,8 +221,10 @@ export async function manageEvent(options, request) {
200
221
  notice: `已删除事件 \`${eventName}\`。`,
201
222
  };
202
223
  }
203
- if (!request.definition || !request.definition.type || !request.definition.text?.trim()) {
204
- throw new RecoverableToolError(`${request.action} requires a definition with at least "type" and "text".`);
224
+ if (!request.definition ||
225
+ !request.definition.type ||
226
+ (!request.definition.text?.trim() && !request.definition.task)) {
227
+ throw new RecoverableToolError(`${request.action} requires a definition with "type" and either "text" or "task".`);
205
228
  }
206
229
  if (request.action === "create") {
207
230
  if (existsSync(eventPath)) {
@@ -220,11 +243,6 @@ export async function manageEvent(options, request) {
220
243
  await readOwnedEvent(eventPath, eventName, options);
221
244
  }
222
245
  const event = validateDefinition(request.definition, eventName, options);
223
- // Persist the canonical form: a tolerated legacy `timezone` is dropped so freshly written
224
- // events never carry the deprecated field (cron is always host-timezone now).
225
- if (event.type === "periodic" && event.legacyTimezone !== undefined) {
226
- delete event.legacyTimezone;
227
- }
228
246
  const content = `${JSON.stringify(event, null, 2)}\n`;
229
247
  await writeFileAtomically(eventPath, content);
230
248
  return {
@@ -10,6 +10,7 @@ import type { PipiclawSessionSearchSettings } from "../settings.js";
10
10
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
11
11
  import type { SubAgentRunManager } from "../subagents/runs.js";
12
12
  import type { PipiclawToolsConfig } from "./config.js";
13
+ import type { TaskStepCost } from "./task-manage/types.js";
13
14
  export interface CreatePipiclawToolsOptions {
14
15
  jobManager: ChannelJobManager;
15
16
  runManager: SubAgentRunManager;
@@ -27,8 +28,8 @@ export interface CreatePipiclawToolsOptions {
27
28
  getSubAgentDiscovery: () => SubAgentDiscoveryResult;
28
29
  getSubAgentModelReference?: () => string | null;
29
30
  getSessionSearchSettings: () => PipiclawSessionSearchSettings;
30
- securityConfig?: SecurityConfig;
31
- toolsConfig?: PipiclawToolsConfig;
31
+ securityConfig: SecurityConfig;
32
+ toolsConfig: PipiclawToolsConfig;
32
33
  /** Transport-provided attachment port; when present, enables the `send_media` tool. */
33
34
  mediaSender?: MediaSender;
34
35
  /**
@@ -39,9 +40,10 @@ export interface CreatePipiclawToolsOptions {
39
40
  */
40
41
  taskLoop?: {
41
42
  taskId: string;
42
- cycleId: string;
43
43
  };
44
44
  /** Tools completed in the current turn; only `task_step_end` reads it. */
45
45
  getToolsUsed?: () => string[];
46
+ /** The current turn's own model cost so far; only `task_step_end` reads it. */
47
+ getStepCost?: () => TaskStepCost;
46
48
  }
47
49
  export declare function createPipiclawTools(options: CreatePipiclawToolsOptions): AgentTool<any>[];
@@ -1,16 +1,13 @@
1
- import { APP_HOME_DIR } from "../paths.js";
2
- import { loadSecurityConfig } from "../security/config.js";
3
1
  import { withSubAgentsDirWriteDeny } from "../subagents/discovery.js";
4
2
  import { createSubAgentInlineTool, createSubAgentTool } from "../subagents/tool.js";
5
- import { loadToolsConfig } from "./config.js";
6
3
  import { buildToolSet } from "./registry.js";
7
4
  import { createSubAgentListTool, createSubAgentRunTool } from "./subagent-manage.js";
8
5
  import { withToolDetails } from "./tool-details.js";
9
6
  export function createPipiclawTools(options) {
10
7
  // Spec 040, D8.1: the main agent's own write/edit tools can write a self-authorizing
11
8
  // `runtime: external` role file just as readily as a sub-agent's can; deny it here too.
12
- const securityConfig = withSubAgentsDirWriteDeny(options.securityConfig ?? loadSecurityConfig(APP_HOME_DIR), options.workspaceDir);
13
- const toolsConfig = options.toolsConfig ?? loadToolsConfig(APP_HOME_DIR);
9
+ const securityConfig = withSubAgentsDirWriteDeny(options.securityConfig, options.workspaceDir);
10
+ const { toolsConfig } = options;
14
11
  const securityContext = {
15
12
  agentWorkspaceDir: options.workspaceDir,
16
13
  projectRoot: options.projectScope.projectRoot,
@@ -45,6 +42,7 @@ export function createPipiclawTools(options) {
45
42
  mediaSender: options.mediaSender,
46
43
  taskLoop: options.taskLoop,
47
44
  getToolsUsed: options.getToolsUsed,
45
+ getStepCost: options.getStepCost,
48
46
  });
49
47
  const subAgentToolOptions = {
50
48
  getRunManager: () => options.runManager,
@@ -68,6 +66,8 @@ export function createPipiclawTools(options) {
68
66
  workspaceDir: options.workspaceDir,
69
67
  channelId: options.channelId,
70
68
  },
69
+ // Inside a task session every delegation binds to that task automatically (spec 052, D4).
70
+ boundTaskId: options.taskLoop?.taskId,
71
71
  };
72
72
  const subAgentManageOptions = {
73
73
  runManager: options.runManager,
@@ -8,6 +8,7 @@ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.j
8
8
  import type { PipiclawSessionSearchSettings } from "../settings.js";
9
9
  import type { SubAgentRunManager } from "../subagents/runs.js";
10
10
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
11
+ import type { TaskStepCost } from "./task-manage/types.js";
11
12
  import { type ToolDetailsKind } from "./tool-details.js";
12
13
  /**
13
14
  * Unified build context passed to every tool's `create` closure. It carries the union
@@ -57,16 +58,17 @@ export interface ToolBuildContext {
57
58
  */
58
59
  mediaSender?: MediaSender;
59
60
  /**
60
- * Present only inside a task loop step (spec 051, D3): which task this tool set belongs to,
61
- * and the cycle it is running in. `task_step_end` is registered only when this is set, so the
62
- * chat surface can never end a step that is not running.
61
+ * Present only inside a task loop step (spec 051, D3): which task this tool set belongs to.
62
+ * `task_step_end` is registered only when this is set, so the chat surface can never end a
63
+ * step that is not running.
63
64
  */
64
65
  taskLoop?: {
65
66
  taskId: string;
66
- cycleId: string;
67
67
  };
68
68
  /** Tools completed in the current turn; only the task loop reads it. */
69
69
  getToolsUsed?: () => string[];
70
+ /** The current turn's own model cost so far; only the task loop reads it. */
71
+ getStepCost?: () => TaskStepCost;
70
72
  }
71
73
  export interface ToolRegistration {
72
74
  /** Also the tool's `details.kind`: the name is the authoritative discriminator. */
@@ -39,10 +39,7 @@ function taskToolOptions(ctx) {
39
39
  return {
40
40
  jobManager: req(ctx.jobManager, "jobManager"),
41
41
  runManager: req(ctx.runManager, "runManager"),
42
- workspaceDir: ctx.workspaceDir,
43
42
  channelDir: ctx.channelDir,
44
- channelId: ctx.channelId,
45
- workingDirectory: ctx.securityContext.projectRoot,
46
43
  };
47
44
  }
48
45
  function webEnabled(ctx) {
@@ -193,8 +190,8 @@ export const TOOL_REGISTRY = [
193
190
  create: (ctx) => createTaskStepEndTool({
194
191
  ...taskToolOptions(ctx),
195
192
  taskId: ctx.taskLoop?.taskId,
196
- cycleId: ctx.taskLoop?.cycleId,
197
193
  getToolsUsed: ctx.getToolsUsed,
194
+ getStepCost: ctx.getStepCost,
198
195
  }),
199
196
  },
200
197
  {
@@ -49,10 +49,10 @@ async function formatRunShow(record) {
49
49
  if (record.failureReason)
50
50
  lines.push(`failureReason: ${record.failureReason}`);
51
51
  if (record.verificationVerdict) {
52
- lines.push(`verification: ${record.verificationVerdict.toUpperCase()}${record.verificationStrength === "advisory" ? " (advisory)" : ""}`);
52
+ lines.push(`verification: ${record.verificationVerdict.toUpperCase()}`);
53
53
  }
54
54
  if (record.taskId)
55
- lines.push(`taskId: ${record.taskId}`);
55
+ lines.push(`taskId: ${record.taskId}${record.item ? ` item: ${record.item}` : ""}`);
56
56
  if (record.leaseKey)
57
57
  lines.push("holds write lease: yes");
58
58
  if (record.model)
@@ -233,6 +233,7 @@ export function createSubAgentRunTool(options) {
233
233
  runId: newRunId,
234
234
  purpose: record.purpose,
235
235
  taskId: record.taskId,
236
+ item: record.item,
236
237
  workingDirectory: record.workingDirectory,
237
238
  artifactDir,
238
239
  };
@@ -269,6 +270,7 @@ export function createSubAgentRunTool(options) {
269
270
  artifactDir,
270
271
  purpose: record.purpose,
271
272
  taskId: record.taskId,
273
+ item: record.item,
272
274
  leaseKey,
273
275
  resumeSessionId: record.sessionId,
274
276
  mutates: role.mutates,
@@ -1,32 +1,16 @@
1
- import { existsSync } from "node:fs";
2
- import { mkdir } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { writeFileAtomically } from "../../shared/atomic-file.js";
5
- import { normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../tasks/ledger.js";
6
- import { RecoverableToolError } from "../tool-details.js";
7
- import { renderTaskFile, renderTaskSkeleton, tasksDir } from "./shared.js";
1
+ import { validateTaskContractInput } from "../../tasks/contract-input.js";
2
+ import { createTaskDocument } from "../../tasks/create.js";
8
3
  export async function createTask(options, request) {
9
- const id = normalizeTaskId(request.id);
10
- const dir = tasksDir(options);
11
- const taskPath = join(dir, `${id}.md`);
12
- const archivePath = join(dir, "archive", `${id}.md`);
13
- if (existsSync(taskPath)) {
14
- throw new RecoverableToolError(`Task "${id}" already exists; use task_update or edit the body instead.`);
15
- }
16
- if (existsSync(archivePath)) {
17
- throw new RecoverableToolError(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
18
- }
19
- const { fields, body } = renderTaskSkeleton(request);
20
- const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
21
- if (badDod)
22
- throw new RecoverableToolError(badDod);
23
- await mkdir(dir, { recursive: true });
24
- await writeFileAtomically(taskPath, renderTaskFile(fields, body));
4
+ const { id, ...contract } = request;
5
+ // Same validator the event-template admission uses, so a task that can be created from a
6
+ // template can be created here and the other way round.
7
+ const input = validateTaskContractInput(contract);
8
+ const document = await createTaskDocument({ channelDir: options.channelDir, id, input });
25
9
  return {
26
10
  action: "create",
27
- id,
28
- path: taskPath,
29
- state: fields.state,
30
- notice: `已创建任务 \`${id}\`(state: ${fields.state}${fields.schedule ? `, schedule: ${fields.schedule}` : ""})。`,
11
+ id: document.id,
12
+ path: document.path,
13
+ state: document.fields.state,
14
+ notice: `已创建任务 \`${document.id}\`(state: ${document.fields.state})。`,
31
15
  };
32
16
  }