@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.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 (149) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -1
  2. package/dist/agent/channel-runner.js +9 -5
  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 +6 -4
  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 +5 -5
  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 +10 -10
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/security/block-message.d.ts +11 -0
  50. package/dist/security/block-message.js +12 -0
  51. package/dist/security/path-guard-check.d.ts +13 -0
  52. package/dist/security/path-guard-check.js +39 -0
  53. package/dist/security/path-guard.js +32 -14
  54. package/dist/settings.js +3 -2
  55. package/dist/shared/atomic-file.d.ts +17 -1
  56. package/dist/shared/atomic-file.js +50 -3
  57. package/dist/shared/duration.d.ts +2 -0
  58. package/dist/shared/duration.js +7 -0
  59. package/dist/shared/safe-id.d.ts +19 -0
  60. package/dist/shared/safe-id.js +24 -0
  61. package/dist/shared/text-utils.d.ts +1 -1
  62. package/dist/shared/text-utils.js +3 -8
  63. package/dist/shared/type-guards.d.ts +2 -0
  64. package/dist/shared/type-guards.js +4 -0
  65. package/dist/subagents/discovery.d.ts +44 -17
  66. package/dist/subagents/discovery.js +82 -111
  67. package/dist/subagents/external/claude-code.js +1 -3
  68. package/dist/subagents/external/harness.d.ts +1 -1
  69. package/dist/subagents/format.d.ts +3 -2
  70. package/dist/subagents/format.js +3 -7
  71. package/dist/subagents/runs.d.ts +1 -1
  72. package/dist/subagents/runs.js +4 -9
  73. package/dist/subagents/tool.d.ts +31 -19
  74. package/dist/subagents/tool.js +582 -561
  75. package/dist/subagents/workspace-lease.js +1 -1
  76. package/dist/tasks/control.js +7 -9
  77. package/dist/tasks/ledger.d.ts +2 -2
  78. package/dist/tasks/ledger.js +3 -7
  79. package/dist/tasks/transitions.d.ts +5 -1
  80. package/dist/tasks/transitions.js +2 -2
  81. package/dist/tools/bash.d.ts +0 -1
  82. package/dist/tools/bash.js +45 -40
  83. package/dist/tools/config.d.ts +6 -1
  84. package/dist/tools/config.js +9 -0
  85. package/dist/tools/edit.d.ts +2 -3
  86. package/dist/tools/edit.js +274 -86
  87. package/dist/tools/event-manage.d.ts +13 -7
  88. package/dist/tools/event-manage.js +52 -14
  89. package/dist/tools/glob-match.d.ts +11 -0
  90. package/dist/tools/glob-match.js +75 -0
  91. package/dist/tools/glob.d.ts +15 -0
  92. package/dist/tools/glob.js +113 -0
  93. package/dist/tools/grep.d.ts +0 -1
  94. package/dist/tools/grep.js +57 -42
  95. package/dist/tools/ignore-dirs.d.ts +6 -0
  96. package/dist/tools/ignore-dirs.js +15 -0
  97. package/dist/tools/index.d.ts +3 -0
  98. package/dist/tools/index.js +50 -40
  99. package/dist/tools/job.d.ts +0 -1
  100. package/dist/tools/job.js +1 -8
  101. package/dist/tools/line-index.d.ts +16 -0
  102. package/dist/tools/line-index.js +76 -0
  103. package/dist/tools/memory-manage.d.ts +20 -8
  104. package/dist/tools/memory-manage.js +65 -92
  105. package/dist/tools/presentation.d.ts +2 -0
  106. package/dist/tools/presentation.js +109 -0
  107. package/dist/tools/read.d.ts +2 -2
  108. package/dist/tools/read.js +97 -133
  109. package/dist/tools/registry.d.ts +4 -1
  110. package/dist/tools/registry.js +89 -22
  111. package/dist/tools/send-media.d.ts +6 -6
  112. package/dist/tools/send-media.js +16 -49
  113. package/dist/tools/session-search.d.ts +0 -1
  114. package/dist/tools/session-search.js +0 -1
  115. package/dist/tools/skill-security.d.ts +0 -2
  116. package/dist/tools/skill-security.js +0 -24
  117. package/dist/tools/skill.d.ts +31 -0
  118. package/dist/tools/skill.js +153 -0
  119. package/dist/tools/subagent-manage.d.ts +6 -5
  120. package/dist/tools/subagent-manage.js +47 -47
  121. package/dist/tools/task-manage/create.d.ts +2 -2
  122. package/dist/tools/task-manage/create.js +1 -3
  123. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  124. package/dist/tools/task-manage/lifecycle.js +49 -56
  125. package/dist/tools/task-manage/schema.d.ts +27 -15
  126. package/dist/tools/task-manage/schema.js +58 -74
  127. package/dist/tools/task-manage/shared.d.ts +11 -6
  128. package/dist/tools/task-manage/shared.js +30 -21
  129. package/dist/tools/task-manage/types.d.ts +14 -15
  130. package/dist/tools/task-manage/verification.d.ts +4 -4
  131. package/dist/tools/task-manage/verification.js +6 -8
  132. package/dist/tools/task-manage.d.ts +8 -11
  133. package/dist/tools/task-manage.js +63 -50
  134. package/dist/tools/tool-details.d.ts +17 -1
  135. package/dist/tools/tool-details.js +24 -0
  136. package/dist/tools/truncate.d.ts +5 -5
  137. package/dist/tools/truncate.js +5 -5
  138. package/dist/tools/web-fetch.d.ts +0 -1
  139. package/dist/tools/web-fetch.js +0 -1
  140. package/dist/tools/web-search.d.ts +0 -1
  141. package/dist/tools/web-search.js +0 -1
  142. package/dist/tools/write-content.d.ts +3 -3
  143. package/dist/tools/write-content.js +12 -51
  144. package/dist/tools/write.d.ts +2 -3
  145. package/dist/tools/write.js +3 -4
  146. package/dist/usage/ledger.js +7 -4
  147. package/package.json +1 -1
  148. package/dist/tools/skill-manage.d.ts +0 -41
  149. package/dist/tools/skill-manage.js +0 -232
@@ -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
@@ -6,19 +6,17 @@ import { readStoredTask, taskBodyHash } from "../../tasks/store.js";
6
6
  import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
7
7
  import { readVerificationAttestation } from "../../tasks/verification.js";
8
8
  import { RecoverableToolError } from "../tool-details.js";
9
- import { renderTaskFile, requiredField } from "./shared.js";
9
+ import { renderTaskFile } from "./shared.js";
10
10
  /**
11
11
  * Import a verifier's attestation. The task's own lifecycle status is not the authorization
12
12
  * 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
13
+ * the task Markdown is agent-writable and proves nothing). `task_verify` works whether the task
14
+ * is still `waiting` (e.g. called right after its completion wake reactivated it) or already
15
15
  * `active`.
16
16
  */
17
17
  export async function verifyTask(options, request) {
18
- if (!request.id)
19
- throw new RecoverableToolError('action "verify" requires an id.');
20
18
  const id = normalizeTaskId(request.id);
21
- const runId = requiredField(request.verifierRunId, "verifierRunId", "verify");
19
+ const runId = request.verifierRunId;
22
20
  const task = await readStoredTask(options.channelDir, id);
23
21
  if (!task)
24
22
  throw new RecoverableToolError(`Task "${id}" does not exist; create it before verification.`);
@@ -72,7 +70,7 @@ export async function verifyTask(options, request) {
72
70
  */
73
71
  export async function assertVerificationAttestationMatches(channelDir, id, runId, currentBodyHash) {
74
72
  if (!runId) {
75
- throw new RecoverableToolError(`Task "${id}" has no verification run id; rerun task_manage verify before complete.`);
73
+ throw new RecoverableToolError(`Task "${id}" has no verification run id; rerun task_verify before task_close.`);
76
74
  }
77
75
  const attestation = await readVerificationAttestation(channelDir, runId);
78
76
  if (attestation.taskId !== id) {
@@ -82,7 +80,7 @@ export async function assertVerificationAttestationMatches(channelDir, id, runId
82
80
  throw new RecoverableToolError(`Verification run "${runId}" recorded a FAIL, not a PASS; rerun verification.`);
83
81
  }
84
82
  if (attestation.bodyHash !== currentBodyHash) {
85
- throw new RecoverableToolError(`Task "${id}" changed since verification run "${runId}"; rerun task_manage verify.`);
83
+ throw new RecoverableToolError(`Task "${id}" changed since verification run "${runId}"; rerun task_verify.`);
86
84
  }
87
85
  return attestation;
88
86
  }
@@ -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
  };
@@ -5,16 +5,19 @@ import { USAGE_STATE_DIR } from "../paths.js";
5
5
  import { createJsonlAppender } from "../shared/jsonl-appender.js";
6
6
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
7
7
  export const UNTRACKED_CHANNEL_ID = "(untracked)";
8
+ // Bucketed by the host's local calendar month, matching `ts: formatLocalTime()` below — entries
9
+ // are written and queried on local wall-clock time, so a UTC month boundary here would file an
10
+ // entry into the wrong month's ledger file near midnight in any timezone offset from UTC.
8
11
  function monthKey(date) {
9
- return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
12
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
10
13
  }
11
14
  function monthKeysBetween(since, until) {
12
15
  const keys = [];
13
- const cursor = new Date(Date.UTC(since.getUTCFullYear(), since.getUTCMonth(), 1));
14
- const end = new Date(Date.UTC(until.getUTCFullYear(), until.getUTCMonth(), 1));
16
+ const cursor = new Date(since.getFullYear(), since.getMonth(), 1);
17
+ const end = new Date(until.getFullYear(), until.getMonth(), 1);
15
18
  while (cursor <= end) {
16
19
  keys.push(monthKey(cursor));
17
- cursor.setUTCMonth(cursor.getUTCMonth() + 1);
20
+ cursor.setMonth(cursor.getMonth() + 1);
18
21
  }
19
22
  return keys;
20
23
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.9.1",
3
+ "version": "0.9.2-beta.1",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,41 +0,0 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- import { Type } from "typebox";
3
- declare const skillManageSchema: Type.TObject<{
4
- label: Type.TString;
5
- action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"view">, Type.TLiteral<"create">, Type.TLiteral<"patch">, Type.TLiteral<"write_file">]>;
6
- name: Type.TOptional<Type.TString>;
7
- content: Type.TOptional<Type.TString>;
8
- filePath: Type.TOptional<Type.TString>;
9
- find: Type.TOptional<Type.TString>;
10
- replace: Type.TOptional<Type.TString>;
11
- }>;
12
- type SkillWriteAction = "create" | "patch" | "write_file";
13
- export interface SkillManageResult {
14
- action: SkillWriteAction;
15
- name: string;
16
- path: string;
17
- bytesWritten: number;
18
- requiresResourceRefresh: boolean;
19
- notice: string;
20
- }
21
- export interface SkillManageRequest {
22
- action: SkillWriteAction;
23
- name: string;
24
- content?: string;
25
- filePath?: string;
26
- find?: string;
27
- replace?: string;
28
- }
29
- export interface WorkspaceSkillSummary {
30
- name: string;
31
- description: string;
32
- path: string;
33
- warning?: string;
34
- }
35
- export interface SkillManageToolOptions {
36
- workspaceDir: string;
37
- }
38
- export declare function listWorkspaceSkills(options: SkillManageToolOptions): Promise<WorkspaceSkillSummary[]>;
39
- export declare function manageWorkspaceSkill(options: SkillManageToolOptions, request: SkillManageRequest): Promise<SkillManageResult>;
40
- export declare function createSkillManageTool(options: SkillManageToolOptions): AgentTool<typeof skillManageSchema>;
41
- export {};