@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.2

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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -1,9 +1,8 @@
1
1
  import type { Static } from "typebox";
2
2
  import type { TaskControl } from "../../tasks/control.js";
3
- import type { taskManageSchema } from "./schema.js";
4
- export type TaskManageAction = Static<typeof taskManageSchema>["action"];
3
+ import type { taskCloseSchema, taskCreateSchema, taskUpdateSchema, taskVerifySchema } from "./schema.js";
5
4
  export interface TaskManageResult {
6
- action: TaskManageAction;
5
+ action: "create" | "update" | "close" | "verify" | "list";
7
6
  id?: string;
8
7
  path?: string;
9
8
  status?: string;
@@ -21,22 +20,22 @@ export interface TaskManageResult {
21
20
  notice: string;
22
21
  }
23
22
  /**
24
- * A `task_manage` call, derived from the schema the model actually sees (spec 036, D8).
23
+ * Five request types, derived from the five schemas the model actually sees (spec 046, D3.3) —
24
+ * the spec 036 D8 "derive from schema" discipline, doubled: each action's required fields are now
25
+ * non-optional in the type, not merely documented as "required for X" in a shared schema's prose.
25
26
  *
26
- * It used to be a hand-written mirror of `taskManageSchema`, and the two drifted apart in both
27
- * directions without a single type error: the schema advertised `parent`, `dependsOn` and
28
- * `verificationMode`, all three silently dropped on write, while the one field that turns on
29
- * independent acceptance — `verificationRequired` — was read by the implementation and absent
30
- * from the schema, so no model could ever ask for it. Deriving the request type makes that class
31
- * of drift a compile error. `label` is the tool's UI affordance, not part of the request.
32
- *
33
- * `status` stays a plain string: it is validated in code against the transition table so a legacy
34
- * or closing legacy value gets a fixable error naming the right action, rather than a
35
- * bare schema rejection.
27
+ * `status`/`outcome` stay plain strings where the underlying schema uses a literal union: they are
28
+ * validated in code against the transition table so a legacy or closing value gets a fixable error
29
+ * naming the right tool, rather than a bare schema rejection.
36
30
  */
37
- export type TaskManageRequest = Omit<Static<typeof taskManageSchema>, "label" | "status"> & {
31
+ export type TaskCreateRequest = Omit<Static<typeof taskCreateSchema>, "status"> & {
32
+ status?: string;
33
+ };
34
+ export type TaskUpdateRequest = Omit<Static<typeof taskUpdateSchema>, "status"> & {
38
35
  status?: string;
39
36
  };
37
+ export type TaskCloseRequest = Static<typeof taskCloseSchema>;
38
+ export type TaskVerifyRequest = Static<typeof taskVerifySchema>;
40
39
  export interface TaskManageToolOptions {
41
40
  workspaceDir: string;
42
41
  channelDir: string;
@@ -1,13 +1,13 @@
1
1
  import { type VerificationAttestation } from "../../tasks/verification.js";
2
- import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ import type { TaskManageResult, TaskManageToolOptions, TaskVerifyRequest } from "./types.js";
3
3
  /**
4
4
  * Import a verifier's attestation. The task's own lifecycle status is not the authorization
5
5
  * check — a real, matching, on-disk attestation for this task id is (spec 040's threat model:
6
- * the task Markdown is agent-writable and proves nothing). `verify` works whether the task is
7
- * still `waiting` (e.g. called right after its completion wake reactivated it) or already
6
+ * the task Markdown is agent-writable and proves nothing). `task_verify` works whether the task
7
+ * is still `waiting` (e.g. called right after its completion wake reactivated it) or already
8
8
  * `active`.
9
9
  */
10
- export declare function verifyTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
10
+ export declare function verifyTask(options: TaskManageToolOptions, request: TaskVerifyRequest): Promise<TaskManageResult>;
11
11
  /**
12
12
  * `verify` writes control.verification from a real attestation file, but the task Markdown
13
13
  * itself is writable by the agent's own write/edit tools — nothing stops it from hand-crafting
@@ -16,4 +16,4 @@ export declare function verifyTask(options: TaskManageToolOptions, request: Task
16
16
  * against the task's *current* body hash directly — not a mirrored value the task file could
17
17
  * itself have drifted.
18
18
  */
19
- export declare function assertVerificationAttestationMatches(channelDir: string, id: string, runId: string | undefined, currentBodyHash: string): Promise<VerificationAttestation>;
19
+ export declare function assertVerificationAttestationMatches(channelDir: string, id: string, runId: string | undefined, currentBodyHash: string, trustedWorkingDirectory?: string): Promise<VerificationAttestation>;
@@ -1,45 +1,48 @@
1
1
  import { writeFileAtomically } from "../../shared/atomic-file.js";
2
+ import { getSubAgentRunManager } from "../../subagents/runs.js";
2
3
  import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
3
4
  import { createDefaultTaskControl } from "../../tasks/control.js";
4
5
  import { normalizeTaskId } from "../../tasks/ledger.js";
5
6
  import { readStoredTask, taskBodyHash } from "../../tasks/store.js";
6
7
  import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
7
- import { readVerificationAttestation } from "../../tasks/verification.js";
8
+ import { getVerificationSubjectHashOptions, readVerificationAttestation, } from "../../tasks/verification.js";
8
9
  import { RecoverableToolError } from "../tool-details.js";
9
- import { renderTaskFile, requiredField } from "./shared.js";
10
+ import { renderTaskFile } from "./shared.js";
10
11
  /**
11
12
  * Import a verifier's attestation. The task's own lifecycle status is not the authorization
12
13
  * check — a real, matching, on-disk attestation for this task id is (spec 040's threat model:
13
- * the task Markdown is agent-writable and proves nothing). `verify` works whether the task is
14
- * still `waiting` (e.g. called right after its completion wake reactivated it) or already
14
+ * the task Markdown is agent-writable and proves nothing). `task_verify` works whether the task
15
+ * is still `waiting` (e.g. called right after its completion wake reactivated it) or already
15
16
  * `active`.
16
17
  */
17
18
  export async function verifyTask(options, request) {
18
- if (!request.id)
19
- throw new RecoverableToolError('action "verify" requires an id.');
20
19
  const id = normalizeTaskId(request.id);
21
- const runId = requiredField(request.verifierRunId, "verifierRunId", "verify");
20
+ const runId = request.verifierRunId;
22
21
  const task = await readStoredTask(options.channelDir, id);
23
22
  if (!task)
24
23
  throw new RecoverableToolError(`Task "${id}" does not exist; create it before verification.`);
25
24
  resolveTaskTransition("verify", id, normalizeStoredStatus(task.fields.status));
26
- const attestation = await readVerificationAttestation(options.channelDir, runId);
25
+ const trustedWorkingDirectory = getSubAgentRunManager(options.channelId).get(runId)?.workingDirectory;
26
+ const attestation = await readVerificationAttestation(options.channelDir, runId, {
27
+ trustedWorkingDirectory,
28
+ });
27
29
  if (attestation.taskId !== id) {
28
30
  throw new RecoverableToolError(`Verification run "${runId}" belongs to task "${attestation.taskId}", not "${id}".`);
29
31
  }
30
32
  if (attestation.workspaceChanged) {
31
- throw new RecoverableToolError(`Verification run "${runId}" changed the workspace; rerun a read-only verifier.`);
33
+ throw new RecoverableToolError(`Verification run "${runId}" changed protected workspace content; rerun the verifier on the current content. Test/build outputs under the documented transient artifact scope are allowed, but implementation changes are not.`);
32
34
  }
33
35
  if (attestation.bodyHash !== taskBodyHash(task.body)) {
34
36
  throw new RecoverableToolError(`Task "${id}" changed after verification run "${runId}"; rerun the verifier on current content.`);
35
37
  }
36
38
  if (attestation.subjectHash) {
37
- const currentSubject = await workspaceSubjectHash(attestation.subjectDir ?? options.workingDirectory ?? process.cwd());
39
+ const subjectDir = attestation.subjectDir ?? trustedWorkingDirectory ?? options.workingDirectory ?? process.cwd();
40
+ const currentSubject = await workspaceSubjectHash(subjectDir, getVerificationSubjectHashOptions(attestation));
38
41
  if (!currentSubject) {
39
42
  throw new RecoverableToolError(`Verification run "${runId}" is bound to a Git artifact subject, but the current checkout cannot be read. Rerun verification from the project checkout.`);
40
43
  }
41
44
  if (currentSubject !== attestation.subjectHash) {
42
- throw new RecoverableToolError(`Task "${id}" artifacts changed after verification run "${runId}"; rerun the verifier.`);
45
+ throw new RecoverableToolError(`Task "${id}" artifacts changed after verification run "${runId}"; rerun the verifier. Legacy attestations without a base commit are HEAD-sensitive and may also require re-verification after a normal Git commit.`);
43
46
  }
44
47
  }
45
48
  const control = task.fields.control ?? createDefaultTaskControl(true);
@@ -70,11 +73,11 @@ export async function verifyTask(options, request) {
70
73
  * against the task's *current* body hash directly — not a mirrored value the task file could
71
74
  * itself have drifted.
72
75
  */
73
- export async function assertVerificationAttestationMatches(channelDir, id, runId, currentBodyHash) {
76
+ export async function assertVerificationAttestationMatches(channelDir, id, runId, currentBodyHash, trustedWorkingDirectory) {
74
77
  if (!runId) {
75
- throw new RecoverableToolError(`Task "${id}" has no verification run id; rerun task_manage verify before complete.`);
78
+ throw new RecoverableToolError(`Task "${id}" has no verification run id; rerun task_verify before task_close.`);
76
79
  }
77
- const attestation = await readVerificationAttestation(channelDir, runId);
80
+ const attestation = await readVerificationAttestation(channelDir, runId, { trustedWorkingDirectory });
78
81
  if (attestation.taskId !== id) {
79
82
  throw new RecoverableToolError(`Verification run "${runId}" belongs to task "${attestation.taskId}", not "${id}"; rerun verification.`);
80
83
  }
@@ -82,7 +85,7 @@ export async function assertVerificationAttestationMatches(channelDir, id, runId
82
85
  throw new RecoverableToolError(`Verification run "${runId}" recorded a FAIL, not a PASS; rerun verification.`);
83
86
  }
84
87
  if (attestation.bodyHash !== currentBodyHash) {
85
- throw new RecoverableToolError(`Task "${id}" changed since verification run "${runId}"; rerun task_manage verify.`);
88
+ throw new RecoverableToolError(`Task "${id}" changed since verification run "${runId}"; rerun task_verify.`);
86
89
  }
87
90
  return attestation;
88
91
  }
@@ -1,12 +1,9 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { taskManageSchema } from "./task-manage/schema.js";
3
- import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./task-manage/types.js";
4
- export type { TaskManageAction, TaskManageRequest, TaskManageResult, TaskManageToolOptions, } from "./task-manage/types.js";
5
- /**
6
- * The `task_manage` dispatcher. Each action lives in a focused module — `create`,
7
- * `lifecycle` (progress/set/complete/skip/cancel/list) and `verification` (verify) — over a
8
- * shared helper layer, with the status transition table in `src/tasks/transitions.ts` (spec
9
- * 029, D7). This entry only routes and wraps the tool.
10
- */
11
- export declare function manageTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
12
- export declare function createTaskManageTool(options: TaskManageToolOptions): AgentTool<typeof taskManageSchema>;
2
+ import { taskCloseSchema, taskCreateSchema, taskListSchema, taskUpdateSchema, taskVerifySchema } from "./task-manage/schema.js";
3
+ import type { TaskManageToolOptions } from "./task-manage/types.js";
4
+ export type { TaskCloseRequest, TaskCreateRequest, TaskManageResult, TaskManageToolOptions, TaskUpdateRequest, TaskVerifyRequest, } from "./task-manage/types.js";
5
+ export declare function createTaskListTool(options: TaskManageToolOptions): AgentTool<typeof taskListSchema>;
6
+ export declare function createTaskCreateTool(options: TaskManageToolOptions): AgentTool<typeof taskCreateSchema>;
7
+ export declare function createTaskUpdateTool(options: TaskManageToolOptions): AgentTool<typeof taskUpdateSchema>;
8
+ export declare function createTaskCloseTool(options: TaskManageToolOptions): AgentTool<typeof taskCloseSchema>;
9
+ export declare function createTaskVerifyTool(options: TaskManageToolOptions): AgentTool<typeof taskVerifySchema>;
@@ -1,63 +1,76 @@
1
1
  import { normalizeTaskId } from "../tasks/ledger.js";
2
2
  import { withTaskMutation } from "../tasks/mutation-lock.js";
3
3
  import { createTask } from "./task-manage/create.js";
4
- import { cancelTask, completeTask, listTasks, progressTask, setTask, skipTask } from "./task-manage/lifecycle.js";
5
- import { parseAction, taskManageSchema } from "./task-manage/schema.js";
4
+ import { closeTask, listTasks, updateTask } from "./task-manage/lifecycle.js";
5
+ import { taskCloseSchema, taskCreateSchema, taskListSchema, taskUpdateSchema, taskVerifySchema, } from "./task-manage/schema.js";
6
6
  import { verifyTask } from "./task-manage/verification.js";
7
7
  /**
8
- * The `task_manage` dispatcher. Each action lives in a focused module — `create`,
9
- * `lifecycle` (progress/set/complete/skip/cancel/list) and `verification` (verify) — over a
10
- * shared helper layer, with the status transition table in `src/tasks/transitions.ts` (spec
11
- * 029, D7). This entry only routes and wraps the tool.
8
+ * Five tools, one per payload shape (spec 046, D3.1) — replaces the single `task_manage`
9
+ * dispatcher. Each factory only wires its own schema and, for the four that carry an `id`, the
10
+ * same per-task serial lock `manageTask` used to apply centrally (spec 029, D7): a task file
11
+ * write must never race another write to the same task, and that guarantee has to travel with
12
+ * the split, not get silently dropped in the split (spec 046, D3.4).
12
13
  */
13
- export async function manageTask(options, request) {
14
- if (request.action === "list")
15
- return listTasks(options);
16
- if (!request.id)
17
- return dispatchTaskMutation(options, request);
18
- const id = normalizeTaskId(request.id);
19
- return withTaskMutation(options.channelDir, id, () => dispatchTaskMutation(options, request));
14
+ async function withLock(options, id, mutate) {
15
+ return withTaskMutation(options.channelDir, normalizeTaskId(id), mutate);
20
16
  }
21
- function dispatchTaskMutation(options, request) {
22
- switch (request.action) {
23
- case "create":
24
- return createTask(options, request);
25
- case "progress":
26
- return progressTask(options, request);
27
- case "set":
28
- return setTask(options, request);
29
- case "verify":
30
- return verifyTask(options, request);
31
- case "complete":
32
- return completeTask(options, request);
33
- case "skip":
34
- return skipTask(options, request);
35
- case "cancel":
36
- return cancelTask(options, request);
37
- case "list":
38
- return listTasks(options);
39
- }
17
+ export function createTaskListTool(options) {
18
+ return {
19
+ name: "task_list",
20
+ label: "task_list",
21
+ description: "List persistent tasks in this channel's active directory.",
22
+ parameters: taskListSchema,
23
+ execute: async () => {
24
+ const result = await listTasks(options);
25
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
26
+ },
27
+ };
28
+ }
29
+ export function createTaskCreateTool(options) {
30
+ return {
31
+ name: "task_create",
32
+ label: "task_create",
33
+ description: "Create a persistent task: goal, DoD, and optional plan, manual, verification plan, and schedule.",
34
+ parameters: taskCreateSchema,
35
+ execute: async (_toolCallId, args) => {
36
+ const result = await withLock(options, args.id, () => createTask(options, args));
37
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
38
+ },
39
+ };
40
+ }
41
+ export function createTaskUpdateTool(options) {
42
+ return {
43
+ name: "task_update",
44
+ label: "task_update",
45
+ description: "With `note`: checkpoint an open task cycle. Without: metadata-only edit (status/wake/schedule/planSteps/control), also the only path that repairs a bad control line.",
46
+ parameters: taskUpdateSchema,
47
+ execute: async (_toolCallId, args) => {
48
+ const result = await withLock(options, args.id, () => updateTask(options, args));
49
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
50
+ },
51
+ };
52
+ }
53
+ export function createTaskCloseTool(options) {
54
+ return {
55
+ name: "task_close",
56
+ label: "task_close",
57
+ description: "Close a task: outcome complete, skip (one recurring occurrence), or cancel.",
58
+ parameters: taskCloseSchema,
59
+ execute: async (_toolCallId, args) => {
60
+ const result = await withLock(options, args.id, () => closeTask(options, args));
61
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
62
+ },
63
+ };
40
64
  }
41
- export function createTaskManageTool(options) {
65
+ export function createTaskVerifyTool(options) {
42
66
  return {
43
- name: "task_manage",
44
- label: "task_manage",
45
- description: "Manage persistent tasks: create, atomically checkpoint progress/control state, request/import independent " +
46
- "verification, complete work, skip one recurring occurrence, cancel abandoned work, or list tasks. Use progress for routine " +
47
- "end-of-turn checkpoints; use write/edit only for substantial Goal/DoD/Manual/Verification changes.",
48
- parameters: taskManageSchema,
49
- // `args` is typed from `taskManageSchema`, and so is `TaskManageRequest`: the request is
50
- // the validated arguments minus `label`, with no third hand-written copy to drift.
67
+ name: "task_verify",
68
+ label: "task_verify",
69
+ description: "Import a purpose=verify sub-agent's attestation by run id.",
70
+ parameters: taskVerifySchema,
51
71
  execute: async (_toolCallId, args) => {
52
- const { label: _label, ...request } = args;
53
- const result = await manageTask(options, {
54
- ...request,
55
- action: parseAction(request.action),
56
- });
57
- return {
58
- content: [{ type: "text", text: JSON.stringify(result) }],
59
- details: { ...result },
60
- };
72
+ const result = await withLock(options, args.id, () => verifyTask(options, args));
73
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: { ...result } };
61
74
  },
62
75
  };
63
76
  }
@@ -18,7 +18,7 @@ export { RecoverableToolError } from "../shared/recoverable-error.js";
18
18
  * Every tool that can appear in a tool set. Equal to the registry's tool names plus
19
19
  * `subagent`, which is registered separately (see the note on TOOL_REGISTRY).
20
20
  */
21
- export type ToolDetailsKind = "read" | "bash" | "edit" | "grep" | "write" | "web_search" | "web_fetch" | "send_media" | "session_search" | "memory_manage" | "skill_manage" | "event_manage" | "task_manage" | "job" | "subagent" | "subagent_manage";
21
+ export type ToolDetailsKind = "read" | "bash" | "edit" | "grep" | "glob" | "write" | "web_search" | "web_fetch" | "send_media" | "session_search" | "memory_save" | "memory_search" | "memory_forget" | "skill" | "event_manage" | "task_list" | "task_create" | "task_update" | "task_close" | "task_verify" | "job" | "subagent" | "subagent_inline" | "subagent_list" | "subagent_run";
22
22
  /** The fields every tool result's `details` carries. Tool-specific fields extend this. */
23
23
  export interface ToolDetails {
24
24
  /** Which tool produced this result. Stamped by `withToolDetails`; never written by hand. */
@@ -33,6 +33,22 @@ export interface ToolDetails {
33
33
  export declare function toolResultDetails(result: unknown): ToolDetails | null;
34
34
  /** True when the result is a rejection the model can resolve on its own. */
35
35
  export declare function isRecoverableRejection(result: unknown): boolean;
36
+ /**
37
+ * True when a tool result is the SDK's own argument-validation failure (spec 047, D4.2).
38
+ *
39
+ * pi validates tool arguments against the schema *before* `execute` runs (`agent-loop.js`'s
40
+ * `validateToolArguments` → `createErrorToolResult`), so this rejection never passes through
41
+ * `withToolDetails`: it carries no `details.kind`, and its text begins with a fixed prefix.
42
+ * A schema-invalid call is by definition something the model can fix by re-issuing correct
43
+ * arguments — the same class as a `RecoverableToolError` — so the runtime treats it as a
44
+ * recoverable rejection rather than a user-visible tool error.
45
+ *
46
+ * This is a deliberate coupling to a string the SDK emits; `test/tool-error-contract.test.ts`
47
+ * drives a real schema-invalid call through the SDK and asserts this still matches, so a
48
+ * wording change upstream fails loudly there rather than silently regressing progress-card
49
+ * behavior.
50
+ */
51
+ export declare function isArgumentValidationFailure(result: unknown, isError: boolean): boolean;
36
52
  /**
37
53
  * Bind a tool to the contract: stamp `kind` on every result it returns, and convert a
38
54
  * `RecoverableToolError` into a normal result the model can read and act on.
@@ -27,6 +27,30 @@ export function toolResultDetails(result) {
27
27
  export function isRecoverableRejection(result) {
28
28
  return toolResultDetails(result)?.recoverable === true;
29
29
  }
30
+ /**
31
+ * True when a tool result is the SDK's own argument-validation failure (spec 047, D4.2).
32
+ *
33
+ * pi validates tool arguments against the schema *before* `execute` runs (`agent-loop.js`'s
34
+ * `validateToolArguments` → `createErrorToolResult`), so this rejection never passes through
35
+ * `withToolDetails`: it carries no `details.kind`, and its text begins with a fixed prefix.
36
+ * A schema-invalid call is by definition something the model can fix by re-issuing correct
37
+ * arguments — the same class as a `RecoverableToolError` — so the runtime treats it as a
38
+ * recoverable rejection rather than a user-visible tool error.
39
+ *
40
+ * This is a deliberate coupling to a string the SDK emits; `test/tool-error-contract.test.ts`
41
+ * drives a real schema-invalid call through the SDK and asserts this still matches, so a
42
+ * wording change upstream fails loudly there rather than silently regressing progress-card
43
+ * behavior.
44
+ */
45
+ export function isArgumentValidationFailure(result, isError) {
46
+ if (!isError || toolResultDetails(result) !== null || !isRecord(result)) {
47
+ return false;
48
+ }
49
+ const text = Array.isArray(result.content)
50
+ ? result.content.map((part) => (isRecord(part) && typeof part.text === "string" ? part.text : "")).join("")
51
+ : "";
52
+ return text.startsWith('Validation failed for tool "');
53
+ }
30
54
  /**
31
55
  * Bind a tool to the contract: stamp `kind` on every result it returns, and convert a
32
56
  * `RecoverableToolError` into a normal result the model can read and act on.
@@ -10,11 +10,11 @@
10
10
  export declare const DEFAULT_MAX_LINES = 2000;
11
11
  export declare const DEFAULT_MAX_BYTES: number;
12
12
  /**
13
- * Upper bound for a file read/sent as base64 in one `sh -c` (fix plan §2.3). `base64` inflates a
14
- * file to 4/3 of its size, and the executor caps captured stdout at 10MB -- above this threshold
15
- * the encoded output would be silently cut mid-stream, producing a buffer that still decodes (so
16
- * failure is invisible) but is corrupt. 5MB leaves headroom for the 4/3 blow-up plus protocol
17
- * overhead. A code constant, not a settings.json key, per CLAUDE.md's rule for numeric thresholds.
13
+ * Upper bound for a file read or sent inline as base64 (`read`'s image branch, `send_media`).
14
+ * `read`/`send_media` go through `FileStore.readBytes` (spec 044, D7), which has no capture cap of
15
+ * its own to worry about -- this is now purely a product limit: what's reasonable to inflate 4/3
16
+ * via base64 and hand to the model or a chat transport in one message. A code constant, not a
17
+ * settings.json key, per CLAUDE.md's rule for numeric thresholds.
18
18
  */
19
19
  export declare const MAX_INLINE_BINARY_BYTES: number;
20
20
  export interface TruncationResult {
@@ -10,11 +10,11 @@
10
10
  export const DEFAULT_MAX_LINES = 2000;
11
11
  export const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB
12
12
  /**
13
- * Upper bound for a file read/sent as base64 in one `sh -c` (fix plan §2.3). `base64` inflates a
14
- * file to 4/3 of its size, and the executor caps captured stdout at 10MB -- above this threshold
15
- * the encoded output would be silently cut mid-stream, producing a buffer that still decodes (so
16
- * failure is invisible) but is corrupt. 5MB leaves headroom for the 4/3 blow-up plus protocol
17
- * overhead. A code constant, not a settings.json key, per CLAUDE.md's rule for numeric thresholds.
13
+ * Upper bound for a file read or sent inline as base64 (`read`'s image branch, `send_media`).
14
+ * `read`/`send_media` go through `FileStore.readBytes` (spec 044, D7), which has no capture cap of
15
+ * its own to worry about -- this is now purely a product limit: what's reasonable to inflate 4/3
16
+ * via base64 and hand to the model or a chat transport in one message. A code constant, not a
17
+ * settings.json key, per CLAUDE.md's rule for numeric thresholds.
18
18
  */
19
19
  export const MAX_INLINE_BINARY_BYTES = 5 * 1024 * 1024;
20
20
  /**
@@ -3,7 +3,6 @@ import { Type } from "typebox";
3
3
  import type { SecurityConfig } from "../security/types.js";
4
4
  import type { PipiclawWebToolsConfig } from "./config.js";
5
5
  declare const webFetchSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  url: Type.TString;
8
7
  extractMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"markdown">, Type.TLiteral<"text">]>>;
9
8
  maxChars: Type.TOptional<Type.TNumber>;
@@ -8,7 +8,6 @@ import { readWebCache, webCacheKey, writeWebCache } from "./web-cache.js";
8
8
  // configured/requested maxChars. Still smaller than maxResponseBytes so a hostile page can't OOM us.
9
9
  const FULL_FETCH_MAX_CHARS = 2_000_000;
10
10
  const webFetchSchema = Type.Object({
11
- label: Type.String({ description: "Brief description of what you're fetching and why (shown to user)" }),
12
11
  url: Type.String({ description: "HTTP or HTTPS URL to fetch" }),
13
12
  extractMode: Type.Optional(Type.Union([Type.Literal("markdown"), Type.Literal("text")], {
14
13
  description: "Preferred text extraction format for HTML pages",
@@ -3,7 +3,6 @@ import { Type } from "typebox";
3
3
  import type { SecurityConfig } from "../security/types.js";
4
4
  import type { PipiclawWebToolsConfig } from "./config.js";
5
5
  declare const webSearchSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  query: Type.TString;
8
7
  count: Type.TOptional<Type.TInteger>;
9
8
  }>;
@@ -2,7 +2,6 @@ import { Type } from "typebox";
2
2
  import { resolveWebSearchRequest } from "../web/config.js";
3
3
  import { runWebSearch } from "../web/search.js";
4
4
  const webSearchSchema = Type.Object({
5
- label: Type.String({ description: "Brief description of what you're searching for and why (shown to user)" }),
6
5
  query: Type.String({ description: "Search query" }),
7
6
  count: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, description: "Maximum number of results to return (1-10)" })),
8
7
  });
@@ -1,9 +1,9 @@
1
- import type { Executor } from "../executor.js";
1
+ import type { FileStore } from "../file-store.js";
2
2
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
3
- export declare function writeContent(executor: Executor, path: string, content: string, signal: AbortSignal | undefined, options?: {
3
+ export declare function writeContent(fileStore: FileStore, path: string, content: string, signal: AbortSignal | undefined, options?: {
4
4
  createParentDir?: boolean;
5
5
  securityConfig?: SecurityConfig;
6
6
  securityContext?: SecurityRuntimeContext;
7
7
  channelId?: string;
8
8
  toolName?: string;
9
- }): Promise<void>;
9
+ }): Promise<string>;
@@ -1,60 +1,21 @@
1
- import { dirname } from "node:path";
2
1
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
3
- import { logSecurityEvent } from "../security/logger.js";
4
- import { guardPath } from "../security/path-guard.js";
5
- import { shellEscape } from "../shared/shell-escape.js";
6
- function getDir(path) {
7
- return dirname(path);
8
- }
9
- function ensureSuccess(result, path) {
10
- if (result.code !== 0) {
11
- throw new Error(result.stderr || `Failed to write file: ${path}`);
12
- }
13
- }
14
- export async function writeContent(executor, path, content, signal, options) {
2
+ import { checkPathGuard } from "../security/path-guard-check.js";
3
+ export async function writeContent(fileStore, path, content, signal, options) {
15
4
  const createParentDir = options?.createParentDir ?? false;
16
5
  const securityConfig = options?.securityConfig ?? DEFAULT_SECURITY_CONFIG;
17
6
  const securityContext = options?.securityContext ?? {
18
7
  agentWorkspaceDir: process.cwd(),
19
8
  projectRoot: process.cwd(),
20
9
  };
21
- if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
22
- const guardResult = guardPath(path, "write", { ...securityContext, config: securityConfig.pathGuard });
23
- if (!guardResult.allowed) {
24
- await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
25
- type: "path",
26
- tool: options?.toolName ?? "write",
27
- channelId: options?.channelId,
28
- rawPath: path,
29
- operation: "write",
30
- resolvedPath: guardResult.resolvedPath,
31
- category: guardResult.category,
32
- reason: guardResult.reason,
33
- });
34
- const lines = [`Path blocked${guardResult.category ? ` [${guardResult.category}]` : ""}`];
35
- if (guardResult.reason) {
36
- lines.push(`Reason: ${guardResult.reason}`);
37
- }
38
- if (guardResult.resolvedPath) {
39
- lines.push(`Resolved path: ${guardResult.resolvedPath}`);
40
- }
41
- throw new Error(lines.join("\n"));
42
- }
43
- }
44
- const dirPrefix = createParentDir ? `mkdir -p ${shellEscape(getDir(path))} && ` : "";
45
- // Atomic write via a same-directory temp file + rename (fix plan §4.1): `cat > path` truncates
46
- // before writing, so a process death or full disk mid-write leaves a corrupted file. `cp -p`
47
- // copies the existing file's permission bits onto the temp file first -- `mv` onto an existing
48
- // path otherwise keeps the *destination's* inode and mode, but a fresh temp file created by the
49
- // shell has its own default mode, and simply overwriting via a new inode would silently strip
50
- // an executable file's permission bit on its very next edit.
51
- const tempPath = `${path}.pipiclaw-tmp`;
52
- const script = `${dirPrefix}tmp=${shellEscape(tempPath)}; ` +
53
- `[ -f ${shellEscape(path)} ] && cp -p ${shellEscape(path)} "$tmp" 2>/dev/null; ` +
54
- `cat > "$tmp" && mv -f "$tmp" ${shellEscape(path)}`;
55
- const result = await executor.exec(script, {
56
- signal,
57
- stdin: content,
10
+ const target = await checkPathGuard(path, "write", securityConfig, securityContext, {
11
+ tool: options?.toolName ?? "write",
12
+ channelId: options?.channelId,
58
13
  });
59
- ensureSuccess(result, path);
14
+ // Atomic write via a same-directory temp file + rename, with fsync (spec 044, D3): `writeAtomic`
15
+ // preserves the existing file's permission bits across the rename, exactly as the old
16
+ // `cp -p` + `cat > tmp && mv` shell script did, but content now goes straight to `node:fs`
17
+ // instead of a stdin pipe into `sh -c` -- it never exists in memory twice, and there is no
18
+ // shell script to escape or an EPIPE to swallow.
19
+ await fileStore.writeAtomic(target, content, { createParentDir, preserveMode: true, signal });
20
+ return target;
60
21
  }
@@ -1,9 +1,8 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../executor.js";
3
+ import type { FileStore } from "../file-store.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const writeSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  path: Type.TString;
8
7
  content: Type.TString;
9
8
  }>;
@@ -12,5 +11,5 @@ export interface WriteToolOptions {
12
11
  securityContext?: SecurityRuntimeContext;
13
12
  channelId?: string;
14
13
  }
15
- export declare function createWriteTool(executor: Executor, options?: WriteToolOptions): AgentTool<typeof writeSchema>;
14
+ export declare function createWriteTool(fileStore: FileStore, options?: WriteToolOptions): AgentTool<typeof writeSchema>;
16
15
  export {};
@@ -1,18 +1,17 @@
1
1
  import { Type } from "typebox";
2
2
  import { writeContent } from "./write-content.js";
3
3
  const writeSchema = Type.Object({
4
- label: Type.String({ description: "Brief description of what you're writing (shown to user)" }),
5
4
  path: Type.String({ description: "Path to the file to write (relative or absolute)" }),
6
5
  content: Type.String({ description: "Content to write to the file" }),
7
6
  });
8
- export function createWriteTool(executor, options = {}) {
7
+ export function createWriteTool(fileStore, options = {}) {
9
8
  return {
10
9
  name: "write",
11
10
  label: "write",
12
11
  description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
13
12
  parameters: writeSchema,
14
13
  execute: async (_toolCallId, { path, content }, signal) => {
15
- await writeContent(executor, path, content, signal, {
14
+ const target = await writeContent(fileStore, path, content, signal, {
16
15
  createParentDir: true,
17
16
  securityConfig: options.securityConfig,
18
17
  securityContext: options.securityContext,
@@ -22,7 +21,7 @@ export function createWriteTool(executor, options = {}) {
22
21
  const bytesWritten = Buffer.byteLength(content, "utf-8");
23
22
  return {
24
23
  content: [{ type: "text", text: `Successfully wrote ${bytesWritten} bytes to ${path}` }],
25
- details: undefined,
24
+ details: { path: target },
26
25
  };
27
26
  },
28
27
  };
@@ -9,7 +9,7 @@
9
9
  * not raise SIGINT). The two-stage Ctrl-C policy lives in the app; here we just
10
10
  * surface the events.
11
11
  */
12
- import { CombinedAutocompleteProvider, Container, Editor, Loader, Markdown, matchesKey, ProcessTerminal, Text, TUI, } from "@earendil-works/pi-tui";
12
+ import { CombinedAutocompleteProvider, Container, Editor, Loader, Markdown, matchesKey, ProcessTerminal, Text, TuiMainScreen, } from "@earendil-works/pi-tui";
13
13
  import { bold, cyan, dim, gray, italic, red, strikethrough, underline, yellow } from "./colors.js";
14
14
  const MARKDOWN_THEME = {
15
15
  heading: (t) => bold(cyan(t)),
@@ -45,7 +45,7 @@ export class PiTuiFrontend {
45
45
  this.editorContainer = new Container();
46
46
  this.turnProgress = [];
47
47
  this.spinnerShown = false;
48
- this.ui = new TUI(new ProcessTerminal(), true);
48
+ this.ui = new TuiMainScreen(new ProcessTerminal(), true);
49
49
  this.editor = new Editor(this.ui, EDITOR_THEME, { paddingX: 1 });
50
50
  this.loader = new Loader(this.ui, (s) => cyan(s), (s) => gray(s), "Working…");
51
51
  if (options.commands?.length) {
@@ -99,7 +99,7 @@ export class PiTuiFrontend {
99
99
  this.ui.requestRender();
100
100
  }
101
101
  showFinal(markdown) {
102
- this.transcript.addChild(new Markdown(markdown, 1, 1, MARKDOWN_THEME));
102
+ this.transcript.addChild(new Markdown(markdown, 1, 1, MARKDOWN_THEME, undefined, { renderLatex: false }));
103
103
  // The turn's progress becomes permanent scrollback; stop tracking it so a
104
104
  // later clearProgress cannot retract it.
105
105
  this.turnProgress = [];