@oyasmi/pipiclaw 0.7.7 → 0.8.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 (114) hide show
  1. package/README.md +23 -2
  2. package/dist/agent/channel-runner.d.ts +4 -4
  3. package/dist/agent/channel-runner.js +25 -23
  4. package/dist/agent/commands.js +7 -2
  5. package/dist/agent/job-manager.d.ts +5 -5
  6. package/dist/agent/prompt-builder.d.ts +3 -13
  7. package/dist/agent/prompt-builder.js +49 -159
  8. package/dist/agent/run-queue.js +2 -1
  9. package/dist/agent/runner-factory.d.ts +1 -2
  10. package/dist/agent/runner-factory.js +2 -2
  11. package/dist/agent/status-render.d.ts +0 -7
  12. package/dist/agent/status-render.js +8 -3
  13. package/dist/agent/types.d.ts +2 -0
  14. package/dist/agent/workspace-resources.d.ts +1 -1
  15. package/dist/agent/workspace-resources.js +3 -15
  16. package/dist/executor.d.ts +20 -0
  17. package/dist/{sandbox.js → executor.js} +3 -95
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/log.d.ts +1 -1
  21. package/dist/log.js +1 -2
  22. package/dist/memory/files.js +0 -0
  23. package/dist/memory/lifecycle.js +6 -5
  24. package/dist/memory/maintenance-jobs.d.ts +0 -1
  25. package/dist/memory/maintenance-jobs.js +2 -2
  26. package/dist/memory/maintenance-state.js +2 -1
  27. package/dist/memory/post-turn-review.d.ts +0 -1
  28. package/dist/memory/post-turn-review.js +4 -4
  29. package/dist/memory/scheduler.d.ts +0 -1
  30. package/dist/memory/scheduler.js +2 -2
  31. package/dist/memory/session.js +2 -2
  32. package/dist/memory/task-digest.js +17 -0
  33. package/dist/paths.d.ts +2 -0
  34. package/dist/paths.js +11 -0
  35. package/dist/playbooks/catalog.d.ts +9 -0
  36. package/dist/playbooks/catalog.js +44 -0
  37. package/dist/playbooks/event-scheduling.md +43 -0
  38. package/dist/playbooks/memory-and-learning.md +45 -0
  39. package/dist/playbooks/runtime-orientation.md +48 -0
  40. package/dist/playbooks/task-closeout.md +45 -0
  41. package/dist/playbooks/task-delegation.md +44 -0
  42. package/dist/playbooks/task-driving.md +43 -0
  43. package/dist/playbooks/task-planning.md +47 -0
  44. package/dist/playbooks/task-recurring.md +42 -0
  45. package/dist/playbooks/task-repair.md +43 -0
  46. package/dist/runtime/bootstrap.d.ts +12 -11
  47. package/dist/runtime/bootstrap.js +81 -57
  48. package/dist/runtime/delivery.js +4 -3
  49. package/dist/runtime/dingtalk.d.ts +2 -0
  50. package/dist/runtime/dingtalk.js +15 -14
  51. package/dist/runtime/durable-dispatch.d.ts +30 -0
  52. package/dist/runtime/durable-dispatch.js +172 -0
  53. package/dist/runtime/event-commands.js +4 -4
  54. package/dist/runtime/events.d.ts +5 -3
  55. package/dist/runtime/events.js +17 -13
  56. package/dist/runtime/task-commands.d.ts +6 -0
  57. package/dist/runtime/task-commands.js +292 -6
  58. package/dist/runtime/task-driver.d.ts +32 -0
  59. package/dist/runtime/task-driver.js +268 -0
  60. package/dist/security/config.js +2 -1
  61. package/dist/security/network.js +9 -2
  62. package/dist/security/path-guard.js +12 -24
  63. package/dist/security/types.d.ts +0 -1
  64. package/dist/settings.d.ts +12 -0
  65. package/dist/settings.js +30 -0
  66. package/dist/shared/jsonl-appender.js +2 -1
  67. package/dist/shared/task-ledger.d.ts +35 -0
  68. package/dist/shared/task-ledger.js +229 -15
  69. package/dist/shared/text-utils.d.ts +1 -0
  70. package/dist/shared/text-utils.js +3 -0
  71. package/dist/subagents/discovery.js +3 -2
  72. package/dist/subagents/tool.d.ts +15 -3
  73. package/dist/subagents/tool.js +194 -17
  74. package/dist/tasks/artifact-subject.d.ts +6 -0
  75. package/dist/tasks/artifact-subject.js +29 -0
  76. package/dist/tasks/control.d.ts +83 -0
  77. package/dist/tasks/control.js +293 -0
  78. package/dist/tasks/store.d.ts +32 -0
  79. package/dist/tasks/store.js +142 -0
  80. package/dist/tasks/verification.d.ts +23 -0
  81. package/dist/tasks/verification.js +69 -0
  82. package/dist/tools/bash.d.ts +1 -1
  83. package/dist/tools/bash.js +3 -5
  84. package/dist/tools/command-optimizer.d.ts +1 -1
  85. package/dist/tools/command-optimizer.js +4 -6
  86. package/dist/tools/config.js +4 -3
  87. package/dist/tools/edit.d.ts +1 -1
  88. package/dist/tools/edit.js +0 -0
  89. package/dist/tools/event-manage.d.ts +0 -1
  90. package/dist/tools/event-manage.js +9 -14
  91. package/dist/tools/grep.d.ts +1 -1
  92. package/dist/tools/grep.js +4 -6
  93. package/dist/tools/index.d.ts +1 -3
  94. package/dist/tools/index.js +1 -4
  95. package/dist/tools/read.d.ts +1 -1
  96. package/dist/tools/read.js +1 -2
  97. package/dist/tools/registry.d.ts +2 -3
  98. package/dist/tools/registry.js +5 -11
  99. package/dist/tools/skill-manage.d.ts +0 -1
  100. package/dist/tools/skill-manage.js +7 -14
  101. package/dist/tools/task-manage.d.ts +37 -4
  102. package/dist/tools/task-manage.js +398 -39
  103. package/dist/tools/write-content.d.ts +1 -1
  104. package/dist/tools/write-content.js +0 -1
  105. package/dist/tools/write.d.ts +1 -1
  106. package/dist/tui/app.d.ts +0 -2
  107. package/dist/tui/app.js +12 -7
  108. package/dist/tui/cli.d.ts +0 -2
  109. package/dist/tui/cli.js +3 -25
  110. package/dist/tui/turn-controller.d.ts +7 -3
  111. package/dist/tui/turn-controller.js +9 -6
  112. package/dist/web/client.js +2 -1
  113. package/package.json +2 -2
  114. package/dist/sandbox.d.ts +0 -42
@@ -0,0 +1,293 @@
1
+ import { errorMessage } from "../shared/text-utils.js";
2
+ const PRIORITIES = ["low", "normal", "high", "critical"];
3
+ const ISOLATIONS = ["shared", "worktree"];
4
+ const SIDE_EFFECTS = ["read-only", "workspace", "external"];
5
+ const VERIFICATION_MODES = ["evidence", "independent"];
6
+ const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
7
+ const OUTCOMES = ["pending", "running", "progress", "blocked", "failed", "verified"];
8
+ const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
9
+ function isRecord(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+ function optionalString(value) {
13
+ if (typeof value !== "string")
14
+ return undefined;
15
+ const trimmed = value.trim();
16
+ return trimmed || undefined;
17
+ }
18
+ function finiteNonNegative(value, fallback = 0) {
19
+ if (value === undefined)
20
+ return fallback;
21
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
22
+ throw new Error("control usage values must be finite non-negative numbers");
23
+ }
24
+ return value;
25
+ }
26
+ function optionalPositive(value) {
27
+ if (value === undefined)
28
+ return undefined;
29
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
30
+ throw new Error("control budget values must be finite positive numbers");
31
+ }
32
+ return value;
33
+ }
34
+ function enumValue(value, values, fallback) {
35
+ if (value === undefined)
36
+ return fallback;
37
+ if (typeof value !== "string" || !values.includes(value)) {
38
+ throw new Error(`control enum value must be one of: ${values.join(", ")}`);
39
+ }
40
+ return value;
41
+ }
42
+ function taskIds(value) {
43
+ if (value === undefined)
44
+ return [];
45
+ if (!Array.isArray(value))
46
+ throw new Error("control.dependsOn must be an array of task ids");
47
+ if (value.some((item) => typeof item !== "string" || !TASK_ID_PATTERN.test(item.trim()))) {
48
+ throw new Error("control.dependsOn contains an invalid task id");
49
+ }
50
+ return Array.from(new Set(value
51
+ .filter((item) => typeof item === "string")
52
+ .map((item) => item.trim())
53
+ .filter((item) => TASK_ID_PATTERN.test(item))));
54
+ }
55
+ function validateTaskId(value, field) {
56
+ if (value && !TASK_ID_PATTERN.test(value))
57
+ throw new Error(`${field} contains an invalid task id: ${value}`);
58
+ }
59
+ export function createDefaultTaskControl(mode = "independent") {
60
+ return {
61
+ version: 1,
62
+ priority: "normal",
63
+ lastOutcome: "pending",
64
+ dependsOn: [],
65
+ isolation: "shared",
66
+ sideEffects: "workspace",
67
+ externalApproval: "not-required",
68
+ budget: { maxAttempts: 12 },
69
+ usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
70
+ verification: { mode, status: "pending" },
71
+ };
72
+ }
73
+ export function parseTaskControl(raw) {
74
+ let value;
75
+ try {
76
+ value = JSON.parse(raw);
77
+ }
78
+ catch (error) {
79
+ throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
80
+ }
81
+ if (!isRecord(value) || value.version !== 1) {
82
+ throw new Error("control must be a version 1 JSON object");
83
+ }
84
+ const budget = isRecord(value.budget) ? value.budget : {};
85
+ const usage = isRecord(value.usage) ? value.usage : {};
86
+ const verification = isRecord(value.verification) ? value.verification : {};
87
+ const worktree = isRecord(value.worktree) ? value.worktree : undefined;
88
+ const maxAttempts = optionalPositive(budget.maxAttempts);
89
+ if (!maxAttempts || !Number.isInteger(maxAttempts)) {
90
+ throw new Error("control.budget.maxAttempts must be a positive integer");
91
+ }
92
+ const deadline = optionalString(value.deadline);
93
+ if (deadline && !Number.isFinite(new Date(deadline).getTime())) {
94
+ throw new Error("control.deadline must be a valid ISO8601 date");
95
+ }
96
+ const parent = optionalString(value.parent);
97
+ validateTaskId(parent, "control.parent");
98
+ const sideEffects = enumValue(value.sideEffects, SIDE_EFFECTS, "workspace");
99
+ const externalApproval = enumValue(value.externalApproval, ["not-required", "required", "granted"], "not-required");
100
+ const approvalBy = optionalString(value.approvalBy);
101
+ const approvedAt = optionalString(value.approvedAt);
102
+ const approvalBodyHash = optionalString(value.approvalBodyHash);
103
+ if (externalApproval === "granted" &&
104
+ (sideEffects !== "external" ||
105
+ !approvalBy ||
106
+ !approvedAt ||
107
+ !Number.isFinite(new Date(approvedAt).getTime()) ||
108
+ !approvalBodyHash ||
109
+ !/^[a-f0-9]{64}$/i.test(approvalBodyHash))) {
110
+ throw new Error("granted external approval requires external side effects, approvalBy, approvedAt, and approvalBodyHash");
111
+ }
112
+ if (value.worktree !== undefined && (!worktree || !optionalString(worktree.path))) {
113
+ throw new Error("control.worktree must contain a non-empty path");
114
+ }
115
+ return {
116
+ version: 1,
117
+ priority: enumValue(value.priority, PRIORITIES, "normal"),
118
+ deadline,
119
+ nextAction: optionalString(value.nextAction),
120
+ lastOutcome: enumValue(value.lastOutcome, OUTCOMES, "pending"),
121
+ blockedReason: optionalString(value.blockedReason),
122
+ parent,
123
+ dependsOn: taskIds(value.dependsOn),
124
+ isolation: enumValue(value.isolation, ISOLATIONS, "shared"),
125
+ sideEffects,
126
+ externalApproval,
127
+ approvalBy,
128
+ approvedAt,
129
+ approvalBodyHash,
130
+ budget: {
131
+ maxAttempts: Math.max(1, Math.floor(maxAttempts)),
132
+ maxTokens: optionalPositive(budget.maxTokens),
133
+ maxCostUsd: optionalPositive(budget.maxCostUsd),
134
+ maxWallTimeMinutes: optionalPositive(budget.maxWallTimeMinutes),
135
+ },
136
+ usage: {
137
+ attempts: Math.floor(finiteNonNegative(usage.attempts)),
138
+ tokens: Math.floor(finiteNonNegative(usage.tokens)),
139
+ costUsd: finiteNonNegative(usage.costUsd),
140
+ wallTimeMinutes: finiteNonNegative(usage.wallTimeMinutes),
141
+ },
142
+ verification: {
143
+ mode: enumValue(verification.mode, VERIFICATION_MODES, "independent"),
144
+ status: enumValue(verification.status, VERIFICATION_STATUSES, "pending"),
145
+ runId: optionalString(verification.runId),
146
+ evidence: optionalString(verification.evidence),
147
+ bodyHash: optionalString(verification.bodyHash),
148
+ checkedAt: optionalString(verification.checkedAt),
149
+ subjectHash: optionalString(verification.subjectHash),
150
+ },
151
+ worktree: optionalString(worktree?.path)
152
+ ? { path: optionalString(worktree?.path), branch: optionalString(worktree?.branch) }
153
+ : undefined,
154
+ lastStartedAt: optionalString(value.lastStartedAt),
155
+ lastFinishedAt: optionalString(value.lastFinishedAt),
156
+ cycleId: optionalString(value.cycleId),
157
+ };
158
+ }
159
+ /** Reset state which is meaningful only within one recurring task cycle. */
160
+ export function resetTaskControlForCycle(control, cycleId) {
161
+ const normalizedCycleId = cycleId.trim();
162
+ if (!normalizedCycleId)
163
+ throw new Error("cycleId must not be empty.");
164
+ return {
165
+ ...structuredClone(control),
166
+ nextAction: undefined,
167
+ lastOutcome: "pending",
168
+ blockedReason: undefined,
169
+ externalApproval: control.sideEffects === "external" ? "required" : "not-required",
170
+ approvalBy: undefined,
171
+ approvedAt: undefined,
172
+ approvalBodyHash: undefined,
173
+ usage: { attempts: 0, tokens: 0, costUsd: 0, wallTimeMinutes: 0 },
174
+ verification: { mode: control.verification.mode, status: "pending" },
175
+ worktree: undefined,
176
+ lastStartedAt: undefined,
177
+ lastFinishedAt: undefined,
178
+ cycleId: normalizedCycleId,
179
+ };
180
+ }
181
+ function patchOptionalString(current, value) {
182
+ if (value === undefined)
183
+ return current;
184
+ return value.trim() || undefined;
185
+ }
186
+ function patchPositive(current, value, field) {
187
+ if (value === undefined)
188
+ return current;
189
+ if (!Number.isFinite(value) || value < 0)
190
+ throw new Error(`${field} must be a non-negative number.`);
191
+ return value === 0 ? undefined : value;
192
+ }
193
+ export function applyTaskControlPatch(control, patch) {
194
+ const next = structuredClone(control);
195
+ const invalidatesApproval = control.externalApproval === "granted" && Object.keys(patch).length > 0;
196
+ if (patch.priority !== undefined)
197
+ next.priority = patch.priority;
198
+ if (patch.deadline?.trim() && !Number.isFinite(new Date(patch.deadline).getTime())) {
199
+ throw new Error(`deadline "${patch.deadline}" is not a valid ISO8601 date.`);
200
+ }
201
+ next.deadline = patchOptionalString(next.deadline, patch.deadline);
202
+ next.nextAction = patchOptionalString(next.nextAction, patch.nextAction);
203
+ if (patch.lastOutcome !== undefined)
204
+ next.lastOutcome = patch.lastOutcome;
205
+ next.blockedReason = patchOptionalString(next.blockedReason, patch.blockedReason);
206
+ next.parent = patchOptionalString(next.parent, patch.parent);
207
+ validateTaskId(next.parent, "parent");
208
+ if (patch.dependsOn !== undefined) {
209
+ for (const dependency of patch.dependsOn)
210
+ validateTaskId(dependency.trim(), "dependsOn");
211
+ next.dependsOn = taskIds(patch.dependsOn);
212
+ }
213
+ if (patch.isolation !== undefined)
214
+ next.isolation = patch.isolation;
215
+ if (patch.sideEffects !== undefined)
216
+ next.sideEffects = patch.sideEffects;
217
+ if (patch.externalApproval !== undefined)
218
+ next.externalApproval = patch.externalApproval;
219
+ if (patch.maxAttempts !== undefined) {
220
+ if (!Number.isInteger(patch.maxAttempts) || patch.maxAttempts < 1) {
221
+ throw new Error("maxAttempts must be a positive integer.");
222
+ }
223
+ next.budget.maxAttempts = patch.maxAttempts;
224
+ }
225
+ next.budget.maxTokens = patchPositive(next.budget.maxTokens, patch.maxTokens, "maxTokens");
226
+ next.budget.maxCostUsd = patchPositive(next.budget.maxCostUsd, patch.maxCostUsd, "maxCostUsd");
227
+ next.budget.maxWallTimeMinutes = patchPositive(next.budget.maxWallTimeMinutes, patch.maxWallTimeMinutes, "maxWallTimeMinutes");
228
+ if (patch.verificationMode !== undefined && patch.verificationMode !== next.verification.mode) {
229
+ next.verification = { mode: patch.verificationMode, status: "pending" };
230
+ }
231
+ if (patch.worktreePath !== undefined || patch.worktreeBranch !== undefined) {
232
+ const path = patchOptionalString(next.worktree?.path, patch.worktreePath);
233
+ const branch = patchOptionalString(next.worktree?.branch, patch.worktreeBranch);
234
+ next.worktree = path ? { path, branch } : undefined;
235
+ }
236
+ if (next.sideEffects !== "external") {
237
+ next.externalApproval = "not-required";
238
+ next.approvalBy = undefined;
239
+ next.approvedAt = undefined;
240
+ next.approvalBodyHash = undefined;
241
+ }
242
+ if (next.sideEffects === "external" && next.externalApproval === "not-required") {
243
+ next.externalApproval = "required";
244
+ }
245
+ if (invalidatesApproval && next.sideEffects === "external")
246
+ next.externalApproval = "required";
247
+ if (next.externalApproval !== "granted") {
248
+ next.approvalBy = undefined;
249
+ next.approvedAt = undefined;
250
+ next.approvalBodyHash = undefined;
251
+ }
252
+ return next;
253
+ }
254
+ export function taskPriorityRank(priority) {
255
+ return { critical: 0, high: 1, normal: 2, low: 3 }[priority];
256
+ }
257
+ export function taskBudgetViolation(control, nowMs) {
258
+ if (control.deadline) {
259
+ const deadlineMs = new Date(control.deadline).getTime();
260
+ if (Number.isFinite(deadlineMs) && deadlineMs < nowMs)
261
+ return `deadline exceeded (${control.deadline})`;
262
+ }
263
+ if (control.usage.attempts >= control.budget.maxAttempts) {
264
+ return `attempt budget exhausted (${control.usage.attempts}/${control.budget.maxAttempts})`;
265
+ }
266
+ if (control.budget.maxTokens !== undefined && control.usage.tokens >= control.budget.maxTokens) {
267
+ return `token budget exhausted (${control.usage.tokens}/${control.budget.maxTokens})`;
268
+ }
269
+ if (control.budget.maxCostUsd !== undefined && control.usage.costUsd >= control.budget.maxCostUsd) {
270
+ return `cost budget exhausted ($${control.usage.costUsd.toFixed(4)}/$${control.budget.maxCostUsd.toFixed(4)})`;
271
+ }
272
+ if (control.budget.maxWallTimeMinutes !== undefined &&
273
+ control.usage.wallTimeMinutes >= control.budget.maxWallTimeMinutes) {
274
+ return `wall-time budget exhausted (${control.usage.wallTimeMinutes.toFixed(1)}/${control.budget.maxWallTimeMinutes}m)`;
275
+ }
276
+ return undefined;
277
+ }
278
+ export function invalidateTaskVerification(control) {
279
+ if (control.verification.status === "pending")
280
+ return control;
281
+ return { ...control, verification: { mode: control.verification.mode, status: "pending" } };
282
+ }
283
+ export function invalidateTaskApproval(control) {
284
+ if (control.sideEffects !== "external" || control.externalApproval !== "granted")
285
+ return control;
286
+ return {
287
+ ...control,
288
+ externalApproval: "required",
289
+ approvalBy: undefined,
290
+ approvedAt: undefined,
291
+ approvalBodyHash: undefined,
292
+ };
293
+ }
@@ -0,0 +1,32 @@
1
+ import { type TaskDocumentFields } from "../shared/task-ledger.js";
2
+ import type { TaskControl, TaskOutcome } from "./control.js";
3
+ export interface StoredTaskDocument {
4
+ id: string;
5
+ path: string;
6
+ fields: TaskDocumentFields;
7
+ body: string;
8
+ }
9
+ export declare function taskBodyHash(body: string): string;
10
+ export declare function readStoredTask(channelDir: string, idInput: string, includeArchive?: boolean, allowInvalidControl?: boolean): Promise<StoredTaskDocument | undefined>;
11
+ export declare function writeStoredTask(document: StoredTaskDocument): Promise<void>;
12
+ export declare function updateStoredTask(channelDir: string, id: string, update: (document: StoredTaskDocument) => void, includeArchive?: boolean): Promise<StoredTaskDocument | undefined>;
13
+ export interface TaskAttemptClaim {
14
+ control: TaskControl;
15
+ previousLastOutcome: TaskOutcome;
16
+ previousBlockedReason?: string;
17
+ previousLastStartedAt?: string;
18
+ }
19
+ export declare function claimTaskAttempt(channelDir: string, id: string, now: Date): Promise<TaskAttemptClaim | undefined>;
20
+ export declare function releaseTaskAttemptClaim(channelDir: string, id: string, claim: TaskAttemptClaim, startedAt: Date): Promise<void>;
21
+ export declare function finishTaskAttempt(channelDir: string, id: string, result: {
22
+ tokens: number;
23
+ costUsd: number;
24
+ wallTimeMinutes: number;
25
+ failed: boolean;
26
+ finishedAt: Date;
27
+ }): Promise<void>;
28
+ export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
29
+ export declare function dependencyState(channelDir: string, dependencyIds: readonly string[], ownerId?: string): Promise<{
30
+ ready: boolean;
31
+ reason?: string;
32
+ }>;
@@ -0,0 +1,142 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { writeFileAtomically } from "../shared/atomic-file.js";
6
+ import { normalizeTaskId, parseTaskFrontmatter, renderTaskDocument, taskBody, } from "../shared/task-ledger.js";
7
+ export function taskBodyHash(body) {
8
+ return createHash("sha256").update(body).digest("hex");
9
+ }
10
+ export async function readStoredTask(channelDir, idInput, includeArchive = false, allowInvalidControl = false) {
11
+ const id = normalizeTaskId(idInput);
12
+ const activePath = join(channelDir, "tasks", `${id}.md`);
13
+ const archivePath = join(channelDir, "tasks", "archive", `${id}.md`);
14
+ const path = existsSync(activePath)
15
+ ? activePath
16
+ : includeArchive && existsSync(archivePath)
17
+ ? archivePath
18
+ : undefined;
19
+ if (!path)
20
+ return undefined;
21
+ const content = await readFile(path, "utf-8");
22
+ const frontmatter = parseTaskFrontmatter(content);
23
+ if (!frontmatter.readable)
24
+ throw new Error(`Task "${id}" has unreadable frontmatter.`);
25
+ if (frontmatter.controlReadable === false && !allowInvalidControl) {
26
+ throw new Error(`Task "${id}" has unreadable control metadata.`);
27
+ }
28
+ return {
29
+ id,
30
+ path,
31
+ fields: {
32
+ status: frontmatter.status ?? "open",
33
+ wake: frontmatter.wake,
34
+ recurrence: frontmatter.recurrence,
35
+ control: frontmatter.control,
36
+ },
37
+ body: taskBody(content),
38
+ };
39
+ }
40
+ export async function writeStoredTask(document) {
41
+ await writeFileAtomically(document.path, renderTaskDocument(document.fields, document.body));
42
+ }
43
+ export async function updateStoredTask(channelDir, id, update, includeArchive = false) {
44
+ const document = await readStoredTask(channelDir, id, includeArchive);
45
+ if (!document)
46
+ return undefined;
47
+ update(document);
48
+ await writeStoredTask(document);
49
+ return document;
50
+ }
51
+ export async function claimTaskAttempt(channelDir, id, now) {
52
+ let claim;
53
+ const document = await updateStoredTask(channelDir, id, (task) => {
54
+ if (!task.fields.control)
55
+ return;
56
+ claim = {
57
+ control: task.fields.control,
58
+ previousLastOutcome: task.fields.control.lastOutcome,
59
+ previousBlockedReason: task.fields.control.blockedReason,
60
+ previousLastStartedAt: task.fields.control.lastStartedAt,
61
+ };
62
+ task.fields.control.usage.attempts++;
63
+ task.fields.control.lastStartedAt = now.toISOString();
64
+ task.fields.control.lastOutcome = "running";
65
+ });
66
+ if (claim && document?.fields.control)
67
+ claim.control = document.fields.control;
68
+ return claim;
69
+ }
70
+ export async function releaseTaskAttemptClaim(channelDir, id, claim, startedAt) {
71
+ await updateStoredTask(channelDir, id, (task) => {
72
+ const control = task.fields.control;
73
+ if (!control || control.lastStartedAt !== startedAt.toISOString())
74
+ return;
75
+ control.usage.attempts = Math.max(0, control.usage.attempts - 1);
76
+ control.lastStartedAt = claim.previousLastStartedAt;
77
+ control.lastOutcome = claim.previousLastOutcome;
78
+ control.blockedReason = claim.previousBlockedReason;
79
+ });
80
+ }
81
+ export async function finishTaskAttempt(channelDir, id, result) {
82
+ await updateStoredTask(channelDir, id, (task) => {
83
+ const control = task.fields.control;
84
+ if (!control)
85
+ return;
86
+ control.usage.tokens += Math.max(0, Math.floor(result.tokens));
87
+ control.usage.costUsd += Math.max(0, result.costUsd);
88
+ control.usage.wallTimeMinutes += Math.max(0, result.wallTimeMinutes);
89
+ control.lastFinishedAt = result.finishedAt.toISOString();
90
+ if (result.failed) {
91
+ control.lastOutcome = "failed";
92
+ control.blockedReason = "The previous agent run failed; inspect the runtime error before retrying.";
93
+ }
94
+ else if (control.lastOutcome === "running") {
95
+ control.lastOutcome = "progress";
96
+ control.blockedReason = undefined;
97
+ }
98
+ }, true);
99
+ }
100
+ export async function escalateTask(channelDir, id, reason) {
101
+ const document = await updateStoredTask(channelDir, id, (task) => {
102
+ task.fields.status = "escalated";
103
+ task.fields.wake = undefined;
104
+ if (task.fields.control) {
105
+ task.fields.control.lastOutcome = "blocked";
106
+ task.fields.control.blockedReason = reason;
107
+ }
108
+ });
109
+ return document !== undefined;
110
+ }
111
+ export async function dependencyState(channelDir, dependencyIds, ownerId) {
112
+ const detectCycle = async (id, path, active) => {
113
+ if (id === ownerId || active.has(id))
114
+ return `dependency cycle detected (${[...path, id].join(" -> ")})`;
115
+ const dependency = await readStoredTask(channelDir, id, true, true);
116
+ if (!dependency || dependency.fields.status === "done")
117
+ return undefined;
118
+ const nextActive = new Set(active).add(id);
119
+ for (const nestedId of dependency.fields.control?.dependsOn ?? []) {
120
+ const cycle = await detectCycle(nestedId, [...path, id], nextActive);
121
+ if (cycle)
122
+ return cycle;
123
+ }
124
+ return undefined;
125
+ };
126
+ for (const dependencyId of dependencyIds) {
127
+ const cycle = await detectCycle(dependencyId, ownerId ? [ownerId] : [], new Set());
128
+ if (cycle)
129
+ return { ready: false, reason: cycle };
130
+ }
131
+ for (const dependencyId of dependencyIds) {
132
+ const dependency = await readStoredTask(channelDir, dependencyId, true, true);
133
+ if (!dependency)
134
+ return { ready: false, reason: `dependency ${dependencyId} is missing` };
135
+ if (dependency.fields.status === "cancelled" || dependency.fields.status === "escalated") {
136
+ return { ready: false, reason: `dependency ${dependencyId} is ${dependency.fields.status}` };
137
+ }
138
+ if (dependency.fields.status !== "done")
139
+ return { ready: false, reason: `waiting for dependency ${dependencyId}` };
140
+ }
141
+ return { ready: true };
142
+ }
@@ -0,0 +1,23 @@
1
+ export type VerificationVerdict = "pass" | "fail";
2
+ export interface VerificationAttestation {
3
+ version: 1;
4
+ runId: string;
5
+ taskId: string;
6
+ verdict: VerificationVerdict;
7
+ agent: string;
8
+ model: string;
9
+ checkedAt: string;
10
+ bodyHash: string;
11
+ evidence: string;
12
+ outputHash: string;
13
+ workspaceChanged: boolean;
14
+ /** Git HEAD + working-tree subject that the verifier actually inspected. */
15
+ subjectHash?: string;
16
+ }
17
+ export declare function verificationDir(channelDir: string): string;
18
+ export declare function verificationAttestationPath(channelDir: string, runId: string): string;
19
+ export declare function parseVerificationVerdict(output: string): VerificationVerdict | undefined;
20
+ export declare function writeVerificationAttestation(channelDir: string, input: Omit<VerificationAttestation, "version" | "bodyHash" | "outputHash"> & {
21
+ output: string;
22
+ }): Promise<VerificationAttestation>;
23
+ export declare function readVerificationAttestation(channelDir: string, runId: string): Promise<VerificationAttestation>;
@@ -0,0 +1,69 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../shared/atomic-file.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { readStoredTask, taskBodyHash } from "./store.js";
7
+ function attestationFilename(runId) {
8
+ return `${createHash("sha256").update(runId).digest("hex")}.json`;
9
+ }
10
+ export function verificationDir(channelDir) {
11
+ return join(channelDir, "tasks", ".verifications");
12
+ }
13
+ export function verificationAttestationPath(channelDir, runId) {
14
+ return join(verificationDir(channelDir), attestationFilename(runId));
15
+ }
16
+ export function parseVerificationVerdict(output) {
17
+ const value = /(?:^|\n)VERDICT:\s*(PASS|FAIL)\s*$/i.exec(output.trim())?.[1]?.toLowerCase();
18
+ return value === "pass" || value === "fail" ? value : undefined;
19
+ }
20
+ export async function writeVerificationAttestation(channelDir, input) {
21
+ const task = await readStoredTask(channelDir, input.taskId);
22
+ if (!task)
23
+ throw new Error(`Cannot attest verification: task "${input.taskId}" does not exist.`);
24
+ const attestation = {
25
+ version: 1,
26
+ runId: input.runId,
27
+ taskId: input.taskId,
28
+ verdict: input.verdict,
29
+ agent: input.agent,
30
+ model: input.model,
31
+ checkedAt: input.checkedAt,
32
+ bodyHash: taskBodyHash(task.body),
33
+ evidence: input.evidence,
34
+ outputHash: createHash("sha256").update(input.output).digest("hex"),
35
+ workspaceChanged: input.workspaceChanged,
36
+ subjectHash: input.subjectHash,
37
+ };
38
+ await mkdir(verificationDir(channelDir), { recursive: true });
39
+ await writeFileAtomically(verificationAttestationPath(channelDir, input.runId), `${JSON.stringify(attestation, null, 2)}\n`);
40
+ return attestation;
41
+ }
42
+ export async function readVerificationAttestation(channelDir, runId) {
43
+ let value;
44
+ try {
45
+ value = JSON.parse(await readFile(verificationAttestationPath(channelDir, runId), "utf-8"));
46
+ }
47
+ catch (error) {
48
+ throw new Error(`Verification run "${runId}" was not found or is unreadable. Run a subagent with purpose=verify and taskId first. ${errorMessage(error)}`);
49
+ }
50
+ if (typeof value !== "object" ||
51
+ value === null ||
52
+ value.version !== 1 ||
53
+ value.runId !== runId ||
54
+ typeof value.taskId !== "string" ||
55
+ (value.verdict !== "pass" && value.verdict !== "fail") ||
56
+ typeof value.agent !== "string" ||
57
+ typeof value.model !== "string" ||
58
+ typeof value.checkedAt !== "string" ||
59
+ !Number.isFinite(new Date(value.checkedAt).getTime()) ||
60
+ !/^[a-f0-9]{64}$/i.test(String(value.bodyHash)) ||
61
+ !/^[a-f0-9]{64}$/i.test(String(value.outputHash)) ||
62
+ typeof value.evidence !== "string" ||
63
+ typeof value.workspaceChanged !== "boolean" ||
64
+ (value.subjectHash !== undefined &&
65
+ !/^[a-f0-9]{64}$/i.test(String(value.subjectHash)))) {
66
+ throw new Error(`Verification run "${runId}" has an invalid attestation. Run the verifier again.`);
67
+ }
68
+ return value;
69
+ }
@@ -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 "../sandbox.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
@@ -14,10 +14,9 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "
14
14
  */
15
15
  export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
16
16
  /**
17
- * Generate a unique spill file path for full bash output. This lives inside the
18
- * executor's filesystem (the sandbox), not the host, so the path we report back is
19
- * reachable by the same `read`/`bash` tools the model uses to open it. `/tmp` exists
20
- * and is writable in both the host and Docker (Alpine) sandboxes.
17
+ * Generate a unique spill file path for full bash output. It lives under `/tmp` so the
18
+ * path we report back is reachable by the same `read`/`bash` tools the model uses to
19
+ * open it.
21
20
  */
22
21
  function getSpillFilePath() {
23
22
  const id = randomBytes(8).toString("hex");
@@ -86,7 +85,6 @@ export function createBashTool(executor, options = {}) {
86
85
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
87
86
  const securityContext = options.securityContext ?? {
88
87
  workspaceDir: process.cwd(),
89
- workspacePath: process.cwd(),
90
88
  cwd: process.cwd(),
91
89
  };
92
90
  return {
@@ -1,4 +1,4 @@
1
- import type { Executor } from "../sandbox.js";
1
+ import type { Executor } from "../executor.js";
2
2
  /**
3
3
  * Return the rtk-optimized form of `command`, or `command` unchanged when rtk is
4
4
  * unavailable or declines to rewrite it. Never throws.
@@ -21,12 +21,10 @@ import { shellEscape } from "../shared/shell-escape.js";
21
21
  */
22
22
  const RTK_TIMEOUT_SECONDS = 2;
23
23
  /**
24
- * rtk must exist in the *execution environment* — the host PATH for a host executor, or
25
- * inside the container for a docker executor — not merely on the pipiclaw host. We probe
26
- * through the executor so the check reflects where the command will actually run, and
27
- * memoize the probe promise per executor instance so concurrent turns share one probe and
28
- * we do not re-shell on every command. The instance is stable for a channel's lifetime,
29
- * so this is effectively "probe once".
24
+ * rtk must exist on the host PATH. We probe through the executor so the check reflects
25
+ * where the command will actually run, and memoize the probe promise per executor instance
26
+ * so concurrent turns share one probe and we do not re-shell on every command. The instance
27
+ * is stable for a channel's lifetime, so this is effectively "probe once".
30
28
  */
31
29
  const availabilityByExecutor = new WeakMap();
32
30
  function probeRtk(executor) {
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { APP_HOME_DIR, TOOLS_CONFIG_PATH } from "../paths.js";
3
+ import { APP_HOME_DIR } from "../paths.js";
4
+ import { errorMessage } from "../shared/text-utils.js";
4
5
  import { isRecord } from "../shared/type-guards.js";
5
6
  const WEB_SEARCH_PROVIDERS = ["brave", "tavily", "jina", "searxng", "duckduckgo"];
6
7
  export const DEFAULT_TOOLS_CONFIG = {
@@ -217,7 +218,7 @@ function mergeToolsConfig(source, configPath, diagnostics) {
217
218
  };
218
219
  }
219
220
  export function getToolsConfigPath(appHomeDir = APP_HOME_DIR) {
220
- return appHomeDir === APP_HOME_DIR ? TOOLS_CONFIG_PATH : join(appHomeDir, "tools.json");
221
+ return join(appHomeDir, "tools.json");
221
222
  }
222
223
  export function loadToolsConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
223
224
  const configPath = getToolsConfigPath(appHomeDir);
@@ -240,7 +241,7 @@ export function loadToolsConfigWithDiagnostics(appHomeDir = APP_HOME_DIR) {
240
241
  source: "tools",
241
242
  path: configPath,
242
243
  severity: "error",
243
- message: error instanceof Error ? error.message : String(error),
244
+ message: errorMessage(error),
244
245
  },
245
246
  ],
246
247
  };
@@ -1,6 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../sandbox.js";
3
+ import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const editSchema: Type.TObject<{
6
6
  label: Type.TString;
Binary file
@@ -26,7 +26,6 @@ export interface EventManageRequest {
26
26
  }
27
27
  export interface EventManageToolOptions {
28
28
  workspaceDir: string;
29
- workspacePath: string;
30
29
  channelId: string;
31
30
  commandGuardConfig: SecurityConfig["commandGuard"];
32
31
  }