@oyasmi/pipiclaw 0.9.1-beta.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/agent/channel-runner.d.ts +7 -1
  2. package/dist/agent/channel-runner.js +42 -15
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/prompt/manifest.js +5 -6
  7. package/dist/agent/prompt/sections.js +1 -0
  8. package/dist/agent/reply-limits.d.ts +16 -0
  9. package/dist/agent/reply-limits.js +17 -0
  10. package/dist/agent/runner-factory.d.ts +0 -2
  11. package/dist/agent/session-events.js +2 -2
  12. package/dist/agent/status-render.js +12 -12
  13. package/dist/executor.d.ts +14 -0
  14. package/dist/executor.js +36 -6
  15. package/dist/main.js +3 -4
  16. package/dist/memory/commands.js +79 -38
  17. package/dist/memory/consolidation.d.ts +5 -1
  18. package/dist/memory/consolidation.js +33 -12
  19. package/dist/memory/extraction.d.ts +8 -1
  20. package/dist/memory/extraction.js +47 -4
  21. package/dist/memory/files.d.ts +0 -1
  22. package/dist/memory/files.js +24 -5
  23. package/dist/memory/lifecycle.js +9 -2
  24. package/dist/memory/maintenance-jobs.js +14 -4
  25. package/dist/memory/metadata.d.ts +3 -0
  26. package/dist/memory/metadata.js +7 -0
  27. package/dist/memory/recall.d.ts +9 -0
  28. package/dist/memory/recall.js +101 -17
  29. package/dist/memory/review-log.d.ts +0 -2
  30. package/dist/memory/review-log.js +0 -0
  31. package/dist/memory/session-corpus.js +5 -0
  32. package/dist/memory/session-search.js +9 -0
  33. package/dist/memory/sidecar-worker.js +4 -0
  34. package/dist/memory/source-window.d.ts +0 -1
  35. package/dist/memory/source-window.js +0 -5
  36. package/dist/memory/task-digest.js +0 -2
  37. package/dist/playbooks/agent-delegation.md +32 -24
  38. package/dist/playbooks/background-jobs.md +8 -16
  39. package/dist/playbooks/event-scheduling.md +13 -15
  40. package/dist/playbooks/memory-and-learning.md +29 -22
  41. package/dist/playbooks/outbound-media.md +15 -8
  42. package/dist/playbooks/runtime-orientation.md +40 -37
  43. package/dist/playbooks/task-driving.md +34 -38
  44. package/dist/playbooks/task-planning.md +18 -20
  45. package/dist/runtime/app-home.d.ts +6 -0
  46. package/dist/runtime/app-home.js +15 -6
  47. package/dist/runtime/bootstrap.d.ts +1 -1
  48. package/dist/runtime/bootstrap.js +57 -62
  49. package/dist/runtime/channel-context.d.ts +2 -1
  50. package/dist/runtime/channel-event.d.ts +0 -6
  51. package/dist/runtime/delivery.js +3 -3
  52. package/dist/runtime/dingtalk.d.ts +9 -1
  53. package/dist/runtime/dingtalk.js +27 -13
  54. package/dist/runtime/event-commands.d.ts +15 -0
  55. package/dist/runtime/event-commands.js +48 -40
  56. package/dist/runtime/project-commands.d.ts +16 -0
  57. package/dist/runtime/project-commands.js +13 -17
  58. package/dist/runtime/subagent-commands.d.ts +20 -0
  59. package/dist/runtime/subagent-commands.js +61 -58
  60. package/dist/runtime/task-commands.d.ts +38 -1
  61. package/dist/runtime/task-commands.js +135 -234
  62. package/dist/runtime/task-driver.d.ts +1 -3
  63. package/dist/runtime/task-driver.js +34 -40
  64. package/dist/runtime/task-migration.d.ts +7 -6
  65. package/dist/runtime/task-migration.js +85 -19
  66. package/dist/runtime/task-wake.d.ts +3 -5
  67. package/dist/runtime/task-wake.js +7 -15
  68. package/dist/security/path-guard.js +33 -2
  69. package/dist/security/types.d.ts +9 -0
  70. package/dist/subagents/discovery.d.ts +7 -2
  71. package/dist/subagents/discovery.js +31 -7
  72. package/dist/subagents/external/claude-code.js +42 -2
  73. package/dist/subagents/external/run.js +72 -2
  74. package/dist/subagents/runs.js +28 -3
  75. package/dist/subagents/tool.d.ts +11 -0
  76. package/dist/subagents/tool.js +89 -55
  77. package/dist/subagents/verification-outcome.js +17 -10
  78. package/dist/tasks/control.d.ts +18 -67
  79. package/dist/tasks/control.js +44 -176
  80. package/dist/tasks/ledger.d.ts +7 -13
  81. package/dist/tasks/ledger.js +13 -49
  82. package/dist/tasks/store.d.ts +15 -48
  83. package/dist/tasks/store.js +22 -154
  84. package/dist/tasks/transitions.d.ts +3 -4
  85. package/dist/tasks/transitions.js +8 -27
  86. package/dist/tasks/verification.d.ts +7 -5
  87. package/dist/tools/bash.d.ts +1 -1
  88. package/dist/tools/bash.js +77 -59
  89. package/dist/tools/edit.js +17 -4
  90. package/dist/tools/grep.js +3 -2
  91. package/dist/tools/index.d.ts +0 -2
  92. package/dist/tools/index.js +6 -1
  93. package/dist/tools/job.js +2 -1
  94. package/dist/tools/memory-manage.d.ts +1 -0
  95. package/dist/tools/memory-manage.js +54 -16
  96. package/dist/tools/read.js +21 -5
  97. package/dist/tools/registry.d.ts +0 -1
  98. package/dist/tools/registry.js +0 -1
  99. package/dist/tools/send-media.js +17 -6
  100. package/dist/tools/skill-manage.js +12 -11
  101. package/dist/tools/skill-security.js +1 -1
  102. package/dist/tools/subagent-manage.d.ts +8 -1
  103. package/dist/tools/subagent-manage.js +77 -7
  104. package/dist/tools/task-manage/lifecycle.js +19 -17
  105. package/dist/tools/task-manage/schema.d.ts +2 -6
  106. package/dist/tools/task-manage/schema.js +4 -17
  107. package/dist/tools/task-manage/shared.js +1 -6
  108. package/dist/tools/task-manage/types.d.ts +0 -3
  109. package/dist/tools/task-manage/verification.d.ts +9 -6
  110. package/dist/tools/task-manage/verification.js +19 -71
  111. package/dist/tools/task-manage.d.ts +1 -1
  112. package/dist/tools/task-manage.js +3 -5
  113. package/dist/tools/truncate.d.ts +8 -0
  114. package/dist/tools/truncate.js +8 -0
  115. package/dist/tools/web-fetch.js +9 -1
  116. package/dist/tools/write-content.js +11 -1
  117. package/dist/tui/app.js +1 -1
  118. package/dist/tui/commands.d.ts +1 -1
  119. package/dist/tui/commands.js +1 -1
  120. package/dist/tui/turn-controller.d.ts +1 -1
  121. package/dist/tui/turn-controller.js +14 -4
  122. package/dist/usage/ledger.d.ts +4 -0
  123. package/dist/usage/ledger.js +3 -0
  124. package/dist/usage/render.js +10 -8
  125. package/examples/sub-agents/README.md +2 -0
  126. package/package.json +3 -2
@@ -1,4 +1,4 @@
1
- import { type TaskControl, type TaskOutcome, type TaskWaitingFor } from "./control.js";
1
+ import { type TaskWaitingFor } from "./control.js";
2
2
  import { type TaskDocumentFields } from "./ledger.js";
3
3
  export interface StoredTaskDocument {
4
4
  id: string;
@@ -17,61 +17,28 @@ export declare function taskBodyHash(body: string): string;
17
17
  export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
18
18
  export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
19
19
  export declare function updateStoredTask(channelDir: string, id: string, update: (document: StoredTaskDocument) => void, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
20
- export interface TaskAttemptClaim {
21
- control: TaskControl;
22
- previousLastOutcome: TaskOutcome;
23
- previousBlockedReason?: string;
24
- previousLastStartedAt?: string;
25
- generation: number;
26
- }
27
- export declare function claimTaskAttempt(channelDir: string, id: string, now: Date): Promise<TaskAttemptClaim | undefined>;
28
- export declare function releaseTaskAttemptClaim(channelDir: string, id: string, claim: TaskAttemptClaim): Promise<void>;
29
- export declare function finishTaskAttempt(channelDir: string, id: string, result: {
30
- tokens: number;
31
- costUsd: number;
32
- costKnown: boolean;
33
- wallTimeMinutes: number;
34
- failed: boolean;
35
- silent?: boolean;
36
- finishedAt: Date;
37
- /**
38
- * The `attemptGeneration` this turn's claim recorded (spec 029's monotonic claim
39
- * identity, see `TaskControl.attemptGeneration`). When present and stale — a newer
40
- * claim has since superseded it — usage is still tallied (the spend genuinely
41
- * happened), but the outcome/finish fields are left alone so a slow, superseded turn
42
- * cannot overwrite the newer attempt's in-flight or already-finished state. Absent
43
- * (e.g. legacy callers) means "apply unconditionally", matching prior behavior.
44
- */
45
- generation?: number;
46
- }): Promise<void>;
47
20
  /**
48
21
  * A governor stop: disable the task without changing its lifecycle stage or wake. The structured
49
22
  * stop record is the durable recovery receipt; notification is handled by the runtime driver.
50
23
  */
51
24
  export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
52
- /** Atomically convert a due timed wait to active before any wake is dispatched. */
53
- export declare function activateWaitingTask(channelDir: string, id: string, expectedWaitingFor?: TaskWaitingFor): Promise<StoredTaskDocument | undefined>;
54
25
  export interface WakeTaskTransitionHooks {
55
- /** Test-only fault seam: both hooks run before the single atomic task-file write. */
26
+ /** Test-only fault seam, called immediately before the atomic activation write. */
56
27
  beforeActivation?: () => void;
57
- beforeAttemptClaim?: () => void;
58
- }
59
- export interface WakeTaskHandoffInput {
60
- kind: "subagent";
61
- resourceId: string;
62
- dispatchId: string;
63
28
  }
64
- /** Activate a completion-woken task and claim its next attempt in one task-file mutation. Keeping
65
- * these state changes in one atomic write means a transient failure cannot leave the task active
66
- * but unclaimed, which would make a retry of the same durable wake look ineligible. */
67
- export declare function activateWaitingTaskAndClaimAttempt(channelDir: string, id: string, expectedWaitingFor: TaskWaitingFor, now: Date, hooks?: WakeTaskTransitionHooks, handoff?: WakeTaskHandoffInput): Promise<{
68
- document: StoredTaskDocument;
69
- generation: number;
70
- } | undefined>;
71
- /** Return a transport-rejected structured wake to its exact pre-activation task state. */
72
- export declare function rollbackWakeTaskActivation(channelDir: string, id: string, expected: WakeTaskHandoffInput): Promise<void>;
73
- /** Clear the durable handoff after the transport has accepted the activated turn. */
74
- export declare function finishWakeTaskActivation(channelDir: string, id: string, expected: WakeTaskHandoffInput): Promise<void>;
29
+ /**
30
+ * Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
31
+ * task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
32
+ * safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
33
+ *
34
+ * Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
35
+ * de-authorization): a completion wake reaches here only after the caller has verified an
36
+ * actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
37
+ * `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
38
+ */
39
+ export declare function activateWaitingTask(channelDir: string, id: string, hooks?: WakeTaskTransitionHooks): Promise<StoredTaskDocument | undefined>;
40
+ /** Return a task to waiting after a transport failed to accept its just-activated turn. */
41
+ export declare function rollbackWaitingTask(channelDir: string, id: string, waitingFor: TaskWaitingFor): Promise<void>;
75
42
  /**
76
43
  * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
77
44
  * with a `-N` suffix when the same task is reopened more than once on the same local day.
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
6
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
7
- import { createDefaultTaskControl, resetTaskControlForCycle, } from "./control.js";
7
+ import { createDefaultTaskControl, resetTaskControlForCycle } from "./control.js";
8
8
  import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, startTaskCycle, taskBody, taskContractSegment, } from "./ledger.js";
9
9
  import { withTaskMutation } from "./mutation-lock.js";
10
10
  import { normalizeStoredStatus, resolveTaskTransition } from "./transitions.js";
@@ -45,7 +45,6 @@ export async function readStoredTask(channelDir, idInput, includeArchive = false
45
45
  enabled: frontmatter.enabled,
46
46
  wake: frontmatter.wake,
47
47
  schedule: frontmatter.schedule,
48
- recurrence: frontmatter.recurrence,
49
48
  control: frontmatter.control,
50
49
  outcome: frontmatter.archiveOutcome,
51
50
  closedAt: frontmatter.closedAt,
@@ -66,186 +65,55 @@ export async function updateStoredTask(channelDir, id, update, includeArchive =
66
65
  return document;
67
66
  });
68
67
  }
69
- export async function claimTaskAttempt(channelDir, id, now) {
70
- let claim;
71
- const document = await updateStoredTask(channelDir, id, (task) => {
72
- const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
73
- if (status !== "active" || task.fields.enabled === false)
74
- return;
75
- task.fields.control ??= createDefaultTaskControl();
76
- claim = {
77
- control: task.fields.control,
78
- previousLastOutcome: task.fields.control.lastOutcome,
79
- previousBlockedReason: task.fields.control.blockedReason,
80
- previousLastStartedAt: task.fields.control.lastStartedAt,
81
- generation: task.fields.control.attemptGeneration + 1,
82
- };
83
- task.fields.control.usage.attempts++;
84
- task.fields.control.attemptGeneration = claim.generation;
85
- task.fields.control.lastStartedAt = formatLocalTime(now);
86
- task.fields.control.lastOutcome = "running";
87
- });
88
- if (claim && document?.fields.control)
89
- claim.control = document.fields.control;
90
- return claim;
91
- }
92
- export async function releaseTaskAttemptClaim(channelDir, id, claim) {
93
- await updateStoredTask(channelDir, id, (task) => {
94
- const control = task.fields.control;
95
- if (!control || control.attemptGeneration !== claim.generation)
96
- return;
97
- control.usage.attempts = Math.max(0, control.usage.attempts - 1);
98
- control.lastStartedAt = claim.previousLastStartedAt;
99
- control.lastOutcome = claim.previousLastOutcome;
100
- control.blockedReason = claim.previousBlockedReason;
101
- });
102
- }
103
- export async function finishTaskAttempt(channelDir, id, result) {
104
- await updateStoredTask(channelDir, id, (task) => {
105
- const control = task.fields.control;
106
- if (!control)
107
- return;
108
- control.usage.tokens += Math.max(0, Math.floor(result.tokens));
109
- control.usage.costUsd += Math.max(0, result.costUsd);
110
- control.usage.costKnown &&= result.costKnown;
111
- control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
112
- if (result.generation !== undefined && control.attemptGeneration !== result.generation)
113
- return;
114
- control.lastFinishedAt = formatLocalTime(result.finishedAt);
115
- if (result.silent) {
116
- // The driver claimed before dispatch to prevent concurrent work. A silent
117
- // turn performed no task advancement, so retain its cost audit but not its
118
- // attempt charge.
119
- control.usage.attempts = Math.max(0, control.usage.attempts - 1);
120
- if (control.lastOutcome === "running") {
121
- control.lastOutcome = "pending";
122
- control.blockedReason = undefined;
123
- }
124
- }
125
- else if (result.failed) {
126
- control.lastOutcome = "failed";
127
- control.blockedReason = "The previous agent run failed; inspect the runtime error before retrying.";
128
- }
129
- else if (control.lastOutcome === "running") {
130
- control.lastOutcome = "progress";
131
- control.blockedReason = undefined;
132
- }
133
- }, true);
134
- }
135
68
  /**
136
69
  * A governor stop: disable the task without changing its lifecycle stage or wake. The structured
137
70
  * stop record is the durable recovery receipt; notification is handled by the runtime driver.
138
71
  */
139
72
  export async function escalateTask(channelDir, id, reason) {
140
73
  const document = await updateStoredTask(channelDir, id, (task) => {
141
- const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
74
+ const status = normalizeStoredStatus(task.fields.status);
142
75
  resolveTaskTransition("governor-stop", id, status);
143
76
  task.fields.enabled = false;
144
77
  task.fields.control ??= createDefaultTaskControl();
145
78
  task.fields.control.stop = { by: "governor", reason, at: formatLocalTime() };
146
- task.fields.control.lastOutcome = "blocked";
147
- task.fields.control.blockedReason = reason;
148
79
  });
149
80
  return document !== undefined;
150
81
  }
151
- /** Atomically convert a due timed wait to active before any wake is dispatched. */
152
- export async function activateWaitingTask(channelDir, id, expectedWaitingFor) {
82
+ /**
83
+ * Atomically convert a due/completion-woken task to active. Idempotent by construction: once a
84
+ * task is no longer `waiting`, a redelivered wake or retry finds `status !== "waiting"` and is a
85
+ * safe no-op, so no separate claim/handoff bookkeeping is needed to detect a duplicate activation.
86
+ *
87
+ * Wake legitimacy is entirely the caller's responsibility (spec 043's `waitingFor`
88
+ * de-authorization): a completion wake reaches here only after the caller has verified an
89
+ * actually-settled run/job whose own recorded `taskId` names this task (`task-wake.ts`'s
90
+ * `isVerified*Wake`). `waitingFor` itself is display-only and never gates activation.
91
+ */
92
+ export async function activateWaitingTask(channelDir, id, hooks) {
153
93
  let activated = false;
154
94
  const document = await updateStoredTask(channelDir, id, (task) => {
155
- const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
95
+ const status = normalizeStoredStatus(task.fields.status);
156
96
  if (status !== "waiting" || task.fields.enabled === false)
157
97
  return;
158
- if (expectedWaitingFor && task.fields.control?.waitingFor !== expectedWaitingFor)
159
- return;
98
+ hooks?.beforeActivation?.();
160
99
  activated = true;
161
100
  task.fields.control ??= createDefaultTaskControl();
162
101
  task.fields.status = "active";
163
102
  task.fields.wake = undefined;
164
- if (task.fields.control) {
103
+ if (task.fields.control)
165
104
  task.fields.control.waitingFor = undefined;
166
- task.fields.control.blockedReason = undefined;
167
- }
168
105
  });
169
106
  return activated ? document : undefined;
170
107
  }
171
- /** Activate a completion-woken task and claim its next attempt in one task-file mutation. Keeping
172
- * these state changes in one atomic write means a transient failure cannot leave the task active
173
- * but unclaimed, which would make a retry of the same durable wake look ineligible. */
174
- export async function activateWaitingTaskAndClaimAttempt(channelDir, id, expectedWaitingFor, now, hooks, handoff) {
175
- let generation;
176
- const document = await updateStoredTask(channelDir, id, (task) => {
177
- const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
178
- const existingHandoff = task.fields.control?.wakeHandoff;
179
- if (handoff &&
180
- status === "active" &&
181
- existingHandoff?.kind === handoff.kind &&
182
- existingHandoff.resourceId === handoff.resourceId &&
183
- existingHandoff.dispatchId === handoff.dispatchId &&
184
- task.fields.control?.attemptGeneration === existingHandoff.generation) {
185
- generation = existingHandoff.generation;
186
- return;
187
- }
188
- if (status !== "waiting" || task.fields.enabled === false)
189
- return;
190
- if (task.fields.control?.waitingFor !== expectedWaitingFor)
191
- return;
192
- hooks?.beforeActivation?.();
193
- task.fields.control ??= createDefaultTaskControl();
194
- task.fields.status = "active";
195
- task.fields.wake = undefined;
196
- task.fields.control.waitingFor = undefined;
197
- task.fields.control.blockedReason = undefined;
198
- hooks?.beforeAttemptClaim?.();
199
- generation = task.fields.control.attemptGeneration + 1;
200
- const previousLastOutcome = task.fields.control.lastOutcome;
201
- const previousBlockedReason = task.fields.control.blockedReason;
202
- const previousLastStartedAt = task.fields.control.lastStartedAt;
203
- task.fields.control.usage.attempts++;
204
- task.fields.control.attemptGeneration = generation;
205
- task.fields.control.lastStartedAt = formatLocalTime(now);
206
- task.fields.control.lastOutcome = "running";
207
- if (handoff) {
208
- task.fields.control.wakeHandoff = {
209
- ...handoff,
210
- generation,
211
- previousLastOutcome,
212
- previousBlockedReason,
213
- previousLastStartedAt,
214
- };
215
- }
216
- });
217
- return document && generation !== undefined ? { document, generation } : undefined;
218
- }
219
- function isMatchingWakeHandoff(handoff, expected) {
220
- return (handoff?.kind === expected.kind &&
221
- handoff.resourceId === expected.resourceId &&
222
- handoff.dispatchId === expected.dispatchId);
223
- }
224
- /** Return a transport-rejected structured wake to its exact pre-activation task state. */
225
- export async function rollbackWakeTaskActivation(channelDir, id, expected) {
108
+ /** Return a task to waiting after a transport failed to accept its just-activated turn. */
109
+ export async function rollbackWaitingTask(channelDir, id, waitingFor) {
226
110
  await updateStoredTask(channelDir, id, (task) => {
227
- const control = task.fields.control;
228
- const handoff = control?.wakeHandoff;
229
- if (!control || !isMatchingWakeHandoff(handoff, expected) || control.attemptGeneration !== handoff.generation) {
111
+ if (task.fields.status !== "active")
230
112
  return;
231
- }
232
113
  task.fields.status = "waiting";
233
114
  task.fields.wake = undefined;
234
- control.waitingFor = "external-signal";
235
- control.usage.attempts = Math.max(0, control.usage.attempts - 1);
236
- control.attemptGeneration = Math.max(0, handoff.generation - 1);
237
- control.lastOutcome = handoff.previousLastOutcome;
238
- control.blockedReason = handoff.previousBlockedReason;
239
- control.lastStartedAt = handoff.previousLastStartedAt;
240
- control.wakeHandoff = undefined;
241
- });
242
- }
243
- /** Clear the durable handoff after the transport has accepted the activated turn. */
244
- export async function finishWakeTaskActivation(channelDir, id, expected) {
245
- await updateStoredTask(channelDir, id, (task) => {
246
- if (isMatchingWakeHandoff(task.fields.control?.wakeHandoff, expected) && task.fields.control) {
247
- task.fields.control.wakeHandoff = undefined;
248
- }
115
+ if (task.fields.control)
116
+ task.fields.control.waitingFor = waitingFor;
249
117
  });
250
118
  }
251
119
  /**
@@ -270,7 +138,7 @@ export function nextCycleId(previousCycleId, occurrence) {
270
138
  export async function openRecurringTaskCycle(channelDir, id, now, force = false) {
271
139
  let cycleId;
272
140
  const document = await updateStoredTask(channelDir, id, (task) => {
273
- const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
141
+ const status = normalizeStoredStatus(task.fields.status);
274
142
  if (status !== "sleeping" || !task.fields.schedule)
275
143
  return;
276
144
  const wakeMs = task.fields.wake ? parseLocalTime(task.fields.wake) : undefined;
@@ -4,10 +4,9 @@ export type TaskStatus = (typeof TASK_STATUSES)[number];
4
4
  /** Statuses a model/user may set directly; recurring sleeping is runtime-owned but repairable. */
5
5
  export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "sleeping"];
6
6
  export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
7
- export type TaskLifecycleAction = "create" | "progress" | "request-verification" | "verify" | "complete" | "skip" | "cancel" | "set" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
8
- /** Map legacy on-disk values to the v2 reader vocabulary. */
9
- export declare function normalizeStoredStatus(raw: string | undefined, recurring?: boolean): TaskStatus;
10
- export declare function wasLegacyEscalated(raw: string | undefined): boolean;
7
+ export type TaskLifecycleAction = "create" | "progress" | "verify" | "complete" | "skip" | "cancel" | "set" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
8
+ /** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
9
+ export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
11
10
  export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
12
11
  /** Assert an action is legal and resolve caller-supplied target status. */
13
12
  export declare function resolveTaskTransition(action: TaskLifecycleAction, id: string, from: TaskStatus, requestedStatus?: string): TaskStatus;
@@ -8,8 +8,11 @@ const WORKABLE = ["active", "waiting"];
8
8
  const TRANSITIONS = {
9
9
  create: { from: [], to: "active" },
10
10
  progress: { from: WORKABLE, to: "caller" },
11
- "request-verification": { from: ["active"], to: "waiting" },
12
- verify: { from: ["waiting"], to: "active" },
11
+ // Not gated on a specific waitingFor value: the wake that reactivates a task parked for a
12
+ // purpose=verify sub-agent already flips it to active before this runs (the same as any other
13
+ // delegation wake), but `verify` also accepts waiting so it is not sensitive to exactly when
14
+ // that reactivation lands relative to the model's own turn.
15
+ verify: { from: WORKABLE, to: "active" },
13
16
  complete: { from: ["active"], to: "caller" },
14
17
  skip: { from: WORKABLE, to: "sleeping" },
15
18
  cancel: { from: LIVE, to: "caller" },
@@ -21,31 +24,9 @@ const TRANSITIONS = {
21
24
  "wait-due": { from: ["waiting"], to: "active" },
22
25
  "cycle-due": { from: ["sleeping"], to: "active" },
23
26
  };
24
- /** Map legacy on-disk values to the v2 reader vocabulary. */
25
- export function normalizeStoredStatus(raw, recurring = false) {
26
- switch (raw) {
27
- case undefined:
28
- case "":
29
- case "open":
30
- case "in-progress":
31
- case "verifying":
32
- return "active";
33
- case "awaiting-user":
34
- case "blocked":
35
- return "waiting";
36
- case "paused":
37
- case "escalated":
38
- return "active";
39
- case "done":
40
- return recurring ? "sleeping" : "active";
41
- case "cancelled":
42
- return "active";
43
- default:
44
- return TASK_STATUSES.includes(raw) ? raw : "active";
45
- }
46
- }
47
- export function wasLegacyEscalated(raw) {
48
- return raw === "escalated";
27
+ /** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
28
+ export function normalizeStoredStatus(raw) {
29
+ return raw !== undefined && TASK_STATUSES.includes(raw) ? raw : "active";
49
30
  }
50
31
  export function isSettableTaskStatus(value) {
51
32
  return SETTABLE_TASK_STATUSES.includes(value);
@@ -28,11 +28,13 @@ export interface VerificationAttestation {
28
28
  */
29
29
  subjectDir?: string;
30
30
  /**
31
- * `enforced` — a built-in verifier, whose write/edit tools are structurally removed before it
32
- * runs (a real gate). `advisory` — an external verifier (spec 040, D9): the tools cannot be
33
- * removed, so the verdict rests on the target CLI's own sandbox flag plus the workspace hash,
34
- * neither of which pipiclaw can prove. Defaults to `enforced` for attestations written before
35
- * this field existed — every verifier was built-in then.
31
+ * `enforced` — a built-in verifier that could not write at all: write/edit are structurally
32
+ * removed before it runs, and its role declared no `bash` either (a real gate). `advisory` —
33
+ * every other shape: an external verifier (spec 040, D9), whose tools cannot be removed so the
34
+ * verdict rests on the target CLI's own sandbox flag plus the workspace hash, and a built-in
35
+ * verifier that kept `bash`, which can write files just as well as `write` can. Defaults to
36
+ * `enforced` for attestations written before this field existed — every verifier was built-in
37
+ * and this distinction did not exist then.
36
38
  */
37
39
  verificationStrength: "enforced" | "advisory";
38
40
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
- import type { Executor } from "../executor.js";
4
+ import { type Executor } from "../executor.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  /**
7
7
  * Default wall-clock timeout for bash commands when the caller supplies neither a
@@ -1,9 +1,11 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { writeFile } from "node:fs/promises";
3
3
  import { Type } from "typebox";
4
+ import { CommandTerminatedError } from "../executor.js";
4
5
  import { guardCommand } from "../security/command-guard.js";
5
6
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
6
7
  import { logSecurityEvent } from "../security/logger.js";
8
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
7
9
  import { maybeOptimizeCommand } from "./command-optimizer.js";
8
10
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
9
11
  /**
@@ -120,7 +122,7 @@ export function createBashTool(executor, options = {}) {
120
122
  if (options.interceptorEnabled) {
121
123
  const intercepted = checkBashInterception(command);
122
124
  if (intercepted) {
123
- throw new Error(intercepted);
125
+ throw new RecoverableToolError(intercepted);
124
126
  }
125
127
  }
126
128
  // Optimize *after* the security guard: the guard must inspect the operator's real
@@ -133,7 +135,7 @@ export function createBashTool(executor, options = {}) {
133
135
  // (the main path supplies a jobManager; the sub-agent path never does).
134
136
  if (runAsync) {
135
137
  if (!options.jobManager) {
136
- throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
138
+ throw new RecoverableToolError("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
137
139
  }
138
140
  const willNotify = notify ?? true;
139
141
  const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, {
@@ -155,69 +157,85 @@ export function createBashTool(executor, options = {}) {
155
157
  details: { async: { state: "running", jobId: job.id } },
156
158
  };
157
159
  }
158
- const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
159
- let output = "";
160
- if (result.stdout)
161
- output += result.stdout;
162
- if (result.stderr) {
163
- if (output)
164
- output += "\n";
165
- output += result.stderr;
166
- }
167
- const totalBytes = Buffer.byteLength(output, "utf-8");
168
- // Spill the full output to a temp file when it exceeds the inline limit, so the model
169
- // can page through the rest with `read`. Written straight to disk rather than piped
170
- // through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
171
- // (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
172
- // already runs on. Best-effort: on failure we simply omit the path hint.
173
- let tempFilePath;
174
- if (totalBytes > DEFAULT_MAX_BYTES) {
175
- const candidatePath = getSpillFilePath();
176
- try {
177
- await writeFile(candidatePath, output, { mode: 0o600 });
178
- tempFilePath = candidatePath;
160
+ // Spill + tail-truncate a combined stdout/stderr blob, sharing the same path for a normal
161
+ // result and one cut short by timeout/abort (fix plan §2.2): a timed-out `npm test` used
162
+ // to reject with up to 10MB of raw output stuffed straight into the tool-call error
163
+ // message, which the pi SDK puts into the model's context verbatim and unbounded.
164
+ const buildOutputText = async (stdout, stderr) => {
165
+ let output = "";
166
+ if (stdout)
167
+ output += stdout;
168
+ if (stderr) {
169
+ if (output)
170
+ output += "\n";
171
+ output += stderr;
179
172
  }
180
- catch {
181
- // Ignore spill failures; the truncated output is still returned.
173
+ const totalBytes = Buffer.byteLength(output, "utf-8");
174
+ // Spill the full output to a temp file when it exceeds the inline limit, so the model
175
+ // can page through the rest with `read`. Written straight to disk rather than piped
176
+ // through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
177
+ // (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
178
+ // already runs on. Best-effort: on failure we simply omit the path hint.
179
+ let tempFilePath;
180
+ if (totalBytes > DEFAULT_MAX_BYTES) {
181
+ const candidatePath = getSpillFilePath();
182
+ try {
183
+ await writeFile(candidatePath, output, { mode: 0o600 });
184
+ tempFilePath = candidatePath;
185
+ }
186
+ catch {
187
+ // Ignore spill failures; the truncated output is still returned.
188
+ }
182
189
  }
183
- }
184
- // Apply tail truncation
185
- const truncation = truncateTail(output);
186
- let outputText = truncation.content || "(no output)";
187
- // Build details with truncation info
188
- let details;
189
- if (truncation.truncated) {
190
- details = {
191
- truncation,
192
- fullOutputPath: tempFilePath,
193
- };
194
- // Build actionable notice
195
- const startLine = truncation.totalLines - truncation.outputLines + 1;
196
- const endLine = truncation.totalLines;
197
- const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
198
- if (truncation.lastLinePartial) {
199
- // Edge case: last line alone > 50KB
200
- const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
201
- outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
190
+ const truncation = truncateTail(output);
191
+ let text = truncation.content || "(no output)";
192
+ let details;
193
+ if (truncation.truncated) {
194
+ details = { truncation, fullOutputPath: tempFilePath };
195
+ const startLine = truncation.totalLines - truncation.outputLines + 1;
196
+ const endLine = truncation.totalLines;
197
+ const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
198
+ if (truncation.lastLinePartial) {
199
+ const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
200
+ text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
201
+ }
202
+ else if (truncation.truncatedBy === "lines") {
203
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
204
+ }
205
+ else {
206
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
207
+ }
202
208
  }
203
- else if (truncation.truncatedBy === "lines") {
204
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
205
- }
206
- else {
207
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
209
+ return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
210
+ };
211
+ try {
212
+ const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
213
+ const built = await buildOutputText(result.stdout, result.stderr);
214
+ let outputText = built.text;
215
+ // A non-zero exit code is a normal result, not a tool failure: commands like
216
+ // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
217
+ // Report the code inline so the model can react without treating it as an error.
218
+ if (result.code !== 0) {
219
+ outputText += `\n\nExit code: ${result.code}`;
208
220
  }
221
+ // Recorded unconditionally (not only on failure) because the task governor judges a
222
+ // wake's productivity from it: a command that ran clean and returned something is the
223
+ // evidence that a turn spent driving an external tool was not idle.
224
+ const details = { ...built.details, exitCode: result.code };
225
+ return { content: [{ type: "text", text: outputText }], details };
209
226
  }
210
- // A non-zero exit code is a normal result, not a tool failure: commands like
211
- // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
212
- // Report the code inline so the model can react without treating it as an error.
213
- if (result.code !== 0) {
214
- outputText += `\n\nExit code: ${result.code}`;
227
+ catch (error) {
228
+ if (!(error instanceof CommandTerminatedError)) {
229
+ throw error;
230
+ }
231
+ const built = await buildOutputText(error.stdout, error.stderr);
232
+ const nextStep = error.reason === "timeout"
233
+ ? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
234
+ : "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
235
+ const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
236
+ const details = { ...built.details, timedOut: true };
237
+ return { content: [{ type: "text", text: outputText }], details };
215
238
  }
216
- // Recorded unconditionally (not only on failure) because the task governor judges a
217
- // wake's productivity from it: a command that ran clean and returned something is the
218
- // evidence that a turn spent driving an external tool was not idle.
219
- details = { ...details, exitCode: result.code, producedOutput: output.trim().length > 0 };
220
- return { content: [{ type: "text", text: outputText }], details };
221
239
  },
222
240
  };
223
241
  }