@oyasmi/pipiclaw 0.9.1-beta.2 → 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 (189) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -1
  2. package/dist/agent/channel-runner.js +51 -18
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/effect-ledger.js +9 -2
  7. package/dist/agent/job-manager.d.ts +4 -0
  8. package/dist/agent/job-manager.js +17 -2
  9. package/dist/agent/prompt/manifest.d.ts +1 -1
  10. package/dist/agent/prompt/manifest.js +6 -7
  11. package/dist/agent/prompt/sections.js +9 -5
  12. package/dist/agent/reply-limits.d.ts +16 -0
  13. package/dist/agent/reply-limits.js +17 -0
  14. package/dist/agent/session-events.d.ts +2 -0
  15. package/dist/agent/session-events.js +29 -14
  16. package/dist/agent/status-render.js +12 -12
  17. package/dist/agent/turn-recovery.js +2 -2
  18. package/dist/agent/type-guards.js +5 -1
  19. package/dist/agent/workspace-resources.d.ts +2 -2
  20. package/dist/agent/workspace-resources.js +41 -3
  21. package/dist/executor.d.ts +28 -0
  22. package/dist/executor.js +120 -18
  23. package/dist/file-store.d.ts +96 -0
  24. package/dist/file-store.js +189 -0
  25. package/dist/main.js +3 -4
  26. package/dist/memory/commands.js +79 -38
  27. package/dist/memory/consolidation.d.ts +5 -1
  28. package/dist/memory/consolidation.js +35 -38
  29. package/dist/memory/extraction.d.ts +8 -1
  30. package/dist/memory/extraction.js +47 -4
  31. package/dist/memory/files.d.ts +0 -1
  32. package/dist/memory/files.js +31 -12
  33. package/dist/memory/lifecycle.js +9 -2
  34. package/dist/memory/maintenance-jobs.js +16 -38
  35. package/dist/memory/maintenance-state.js +2 -1
  36. package/dist/memory/metadata.d.ts +3 -0
  37. package/dist/memory/metadata.js +7 -0
  38. package/dist/memory/recall.d.ts +19 -0
  39. package/dist/memory/recall.js +116 -24
  40. package/dist/memory/review-log.d.ts +0 -2
  41. package/dist/memory/review-log.js +0 -0
  42. package/dist/memory/session-corpus.js +5 -0
  43. package/dist/memory/session-search.js +15 -22
  44. package/dist/memory/sidecar-worker.js +4 -0
  45. package/dist/memory/source-window.d.ts +0 -1
  46. package/dist/memory/source-window.js +0 -5
  47. package/dist/memory/transcript.d.ts +10 -0
  48. package/dist/memory/transcript.js +39 -0
  49. package/dist/playbooks/agent-delegation.md +34 -25
  50. package/dist/playbooks/background-jobs.md +8 -16
  51. package/dist/playbooks/catalog.d.ts +1 -1
  52. package/dist/playbooks/catalog.js +1 -1
  53. package/dist/playbooks/event-scheduling.md +15 -15
  54. package/dist/playbooks/memory-and-learning.md +30 -23
  55. package/dist/playbooks/outbound-media.md +15 -8
  56. package/dist/playbooks/runtime-orientation.md +40 -37
  57. package/dist/playbooks/task-driving.md +36 -38
  58. package/dist/playbooks/task-planning.md +21 -21
  59. package/dist/runtime/app-home.d.ts +6 -0
  60. package/dist/runtime/app-home.js +16 -7
  61. package/dist/runtime/bootstrap.js +54 -13
  62. package/dist/runtime/channel-context.d.ts +2 -1
  63. package/dist/runtime/delivery.js +3 -3
  64. package/dist/runtime/dingtalk.d.ts +9 -1
  65. package/dist/runtime/dingtalk.js +30 -15
  66. package/dist/runtime/durable-dispatch.d.ts +26 -1
  67. package/dist/runtime/durable-dispatch.js +51 -5
  68. package/dist/runtime/event-commands.d.ts +15 -0
  69. package/dist/runtime/event-commands.js +55 -56
  70. package/dist/runtime/events.d.ts +4 -2
  71. package/dist/runtime/events.js +15 -20
  72. package/dist/runtime/project-commands.d.ts +16 -0
  73. package/dist/runtime/project-commands.js +13 -17
  74. package/dist/runtime/subagent-commands.d.ts +20 -0
  75. package/dist/runtime/subagent-commands.js +61 -58
  76. package/dist/runtime/task-commands.d.ts +37 -0
  77. package/dist/runtime/task-commands.js +108 -66
  78. package/dist/runtime/task-driver.js +2 -2
  79. package/dist/security/block-message.d.ts +11 -0
  80. package/dist/security/block-message.js +12 -0
  81. package/dist/security/path-guard-check.d.ts +13 -0
  82. package/dist/security/path-guard-check.js +39 -0
  83. package/dist/security/path-guard.js +61 -12
  84. package/dist/security/types.d.ts +9 -0
  85. package/dist/settings.js +3 -2
  86. package/dist/shared/atomic-file.d.ts +17 -1
  87. package/dist/shared/atomic-file.js +50 -3
  88. package/dist/shared/duration.d.ts +2 -0
  89. package/dist/shared/duration.js +7 -0
  90. package/dist/shared/safe-id.d.ts +19 -0
  91. package/dist/shared/safe-id.js +24 -0
  92. package/dist/shared/text-utils.d.ts +1 -1
  93. package/dist/shared/text-utils.js +3 -8
  94. package/dist/shared/type-guards.d.ts +2 -0
  95. package/dist/shared/type-guards.js +4 -0
  96. package/dist/subagents/discovery.d.ts +51 -19
  97. package/dist/subagents/discovery.js +93 -98
  98. package/dist/subagents/external/claude-code.js +40 -2
  99. package/dist/subagents/external/harness.d.ts +1 -1
  100. package/dist/subagents/external/run.js +61 -8
  101. package/dist/subagents/format.d.ts +3 -2
  102. package/dist/subagents/format.js +3 -7
  103. package/dist/subagents/runs.d.ts +1 -1
  104. package/dist/subagents/runs.js +10 -9
  105. package/dist/subagents/tool.d.ts +31 -18
  106. package/dist/subagents/tool.js +592 -562
  107. package/dist/subagents/workspace-lease.js +1 -1
  108. package/dist/tasks/control.js +7 -9
  109. package/dist/tasks/ledger.d.ts +2 -2
  110. package/dist/tasks/ledger.js +3 -7
  111. package/dist/tasks/transitions.d.ts +5 -1
  112. package/dist/tasks/transitions.js +2 -2
  113. package/dist/tasks/verification.d.ts +7 -5
  114. package/dist/tools/bash.d.ts +1 -2
  115. package/dist/tools/bash.js +99 -76
  116. package/dist/tools/config.d.ts +6 -1
  117. package/dist/tools/config.js +9 -0
  118. package/dist/tools/edit.d.ts +2 -3
  119. package/dist/tools/edit.js +276 -75
  120. package/dist/tools/event-manage.d.ts +13 -7
  121. package/dist/tools/event-manage.js +52 -14
  122. package/dist/tools/glob-match.d.ts +11 -0
  123. package/dist/tools/glob-match.js +75 -0
  124. package/dist/tools/glob.d.ts +15 -0
  125. package/dist/tools/glob.js +113 -0
  126. package/dist/tools/grep.d.ts +0 -1
  127. package/dist/tools/grep.js +60 -44
  128. package/dist/tools/ignore-dirs.d.ts +6 -0
  129. package/dist/tools/ignore-dirs.js +15 -0
  130. package/dist/tools/index.d.ts +3 -0
  131. package/dist/tools/index.js +54 -40
  132. package/dist/tools/job.d.ts +0 -1
  133. package/dist/tools/job.js +3 -9
  134. package/dist/tools/line-index.d.ts +16 -0
  135. package/dist/tools/line-index.js +76 -0
  136. package/dist/tools/memory-manage.d.ts +21 -8
  137. package/dist/tools/memory-manage.js +114 -103
  138. package/dist/tools/presentation.d.ts +2 -0
  139. package/dist/tools/presentation.js +109 -0
  140. package/dist/tools/read.d.ts +2 -2
  141. package/dist/tools/read.js +100 -120
  142. package/dist/tools/registry.d.ts +4 -1
  143. package/dist/tools/registry.js +89 -22
  144. package/dist/tools/send-media.d.ts +6 -6
  145. package/dist/tools/send-media.js +21 -43
  146. package/dist/tools/session-search.d.ts +0 -1
  147. package/dist/tools/session-search.js +0 -1
  148. package/dist/tools/skill-security.d.ts +0 -2
  149. package/dist/tools/skill-security.js +1 -25
  150. package/dist/tools/skill.d.ts +31 -0
  151. package/dist/tools/skill.js +153 -0
  152. package/dist/tools/subagent-manage.d.ts +6 -5
  153. package/dist/tools/subagent-manage.js +47 -47
  154. package/dist/tools/task-manage/create.d.ts +2 -2
  155. package/dist/tools/task-manage/create.js +1 -3
  156. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  157. package/dist/tools/task-manage/lifecycle.js +49 -56
  158. package/dist/tools/task-manage/schema.d.ts +27 -15
  159. package/dist/tools/task-manage/schema.js +58 -74
  160. package/dist/tools/task-manage/shared.d.ts +11 -6
  161. package/dist/tools/task-manage/shared.js +30 -21
  162. package/dist/tools/task-manage/types.d.ts +14 -15
  163. package/dist/tools/task-manage/verification.d.ts +4 -4
  164. package/dist/tools/task-manage/verification.js +6 -8
  165. package/dist/tools/task-manage.d.ts +8 -11
  166. package/dist/tools/task-manage.js +63 -50
  167. package/dist/tools/tool-details.d.ts +17 -1
  168. package/dist/tools/tool-details.js +24 -0
  169. package/dist/tools/truncate.d.ts +8 -0
  170. package/dist/tools/truncate.js +8 -0
  171. package/dist/tools/web-fetch.d.ts +0 -1
  172. package/dist/tools/web-fetch.js +9 -2
  173. package/dist/tools/web-search.d.ts +0 -1
  174. package/dist/tools/web-search.js +0 -1
  175. package/dist/tools/write-content.d.ts +3 -3
  176. package/dist/tools/write-content.js +12 -41
  177. package/dist/tools/write.d.ts +2 -3
  178. package/dist/tools/write.js +3 -4
  179. package/dist/tui/app.js +1 -1
  180. package/dist/tui/commands.d.ts +1 -1
  181. package/dist/tui/commands.js +1 -1
  182. package/dist/tui/turn-controller.d.ts +1 -1
  183. package/dist/tui/turn-controller.js +14 -4
  184. package/dist/usage/ledger.js +7 -4
  185. package/dist/usage/render.js +10 -8
  186. package/examples/sub-agents/README.md +2 -0
  187. package/package.json +3 -2
  188. package/dist/tools/skill-manage.d.ts +0 -41
  189. package/dist/tools/skill-manage.js +0 -231
@@ -57,5 +57,5 @@ export function findWorkspaceLeaseHolder(workingDirectory) {
57
57
  export function formatWorkspaceLeaseConflict(heldBy) {
58
58
  return (`Workspace "${heldBy.workingDirectory}" is already held by a running write delegation ` +
59
59
  `(runId ${heldBy.runId}, channel ${heldBy.channelId}). Wait for it to finish, cancel it with ` +
60
- "subagent_manage, or use a separate `git worktree add` checkout via workingDirectory.");
60
+ "subagent_run op=cancel, or use a separate `git worktree add` checkout via workingDirectory.");
61
61
  }
@@ -1,10 +1,8 @@
1
1
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
+ import { isPlainObject } from "../shared/type-guards.js";
3
4
  const WAITING_FOR = ["time", "user", "job", "external-signal"];
4
5
  const VERIFICATION_STATUSES = ["pending", "passed", "failed"];
5
- function isRecord(value) {
6
- return typeof value === "object" && value !== null && !Array.isArray(value);
7
- }
8
6
  function optionalString(value) {
9
7
  if (typeof value !== "string")
10
8
  return undefined;
@@ -22,7 +20,7 @@ function enumValue(value, values, fallback) {
22
20
  function parseStop(value) {
23
21
  if (value === undefined)
24
22
  return undefined;
25
- if (!isRecord(value))
23
+ if (!isPlainObject(value))
26
24
  throw new Error("control.stop must be an object");
27
25
  const by = enumValue(value.by, ["user", "governor"], "user");
28
26
  const reason = optionalString(value.reason);
@@ -47,10 +45,10 @@ export function parseTaskControl(raw) {
47
45
  catch (error) {
48
46
  throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
49
47
  }
50
- if (!isRecord(value) || value.version !== 3) {
51
- throw new Error("control must be a version 3 JSON object; repair it with task_manage set.");
48
+ if (!isPlainObject(value) || value.version !== 3) {
49
+ throw new Error("control must be a version 3 JSON object; repair it with task_update (no note).");
52
50
  }
53
- const verification = isRecord(value.verification) ? value.verification : {};
51
+ const verification = isPlainObject(value.verification) ? value.verification : {};
54
52
  const deadline = optionalString(value.deadline);
55
53
  if (deadline && parseLocalTime(deadline) === undefined) {
56
54
  throw new Error("control.deadline must be a valid local time");
@@ -83,10 +81,10 @@ export function parseLegacyTaskControl(raw) {
83
81
  catch (error) {
84
82
  throw new Error(`control is not valid JSON: ${errorMessage(error)}`);
85
83
  }
86
- if (!isRecord(value) || (value.version !== 1 && value.version !== 2)) {
84
+ if (!isPlainObject(value) || (value.version !== 1 && value.version !== 2)) {
87
85
  throw new Error("legacy control must be a version 1 or version 2 JSON object");
88
86
  }
89
- const verification = isRecord(value.verification) ? value.verification : {};
87
+ const verification = isPlainObject(value.verification) ? value.verification : {};
90
88
  const deadline = optionalString(value.deadline);
91
89
  const waitingFor = value.waitingFor === undefined ? undefined : enumValue(value.waitingFor, WAITING_FOR, "external-signal");
92
90
  let stop = parseStop(value.stop);
@@ -10,7 +10,7 @@ export type TaskArchiveOutcome = "completed" | "cancelled";
10
10
  * has a single owner. The parsing stays deliberately literal (flat `key: value` fields,
11
11
  * live-vs-archived, wake gating, fail-open on unreadable frontmatter) because task files
12
12
  * are hand-editable and must degrade toward "wake me up so I can be fixed".
13
- * `/tasks`, the task digest, and `task_manage list` all read through here.
13
+ * `/tasks`, the task digest, and `task_list` all read through here.
14
14
  */
15
15
  export interface TaskFrontmatter {
16
16
  /** false => frontmatter could not be read (fail-open: the task is treated as actionable). */
@@ -183,7 +183,7 @@ export declare function missingStandardTaskSections(content: string): string[];
183
183
  * Without the "no checklist items" case, a DoD written as prose or a numbered
184
184
  * list (no `- [ ]` anywhere) makes this function return an empty array —
185
185
  * indistinguishable from "everything is checked" — which would silently let
186
- * `task_manage complete` through with nothing ever actually verified.
186
+ * `task_close outcome=complete` through with nothing ever actually verified.
187
187
  */
188
188
  export declare function uncheckedTaskAcceptanceItems(content: string): string[];
189
189
  /**
@@ -2,6 +2,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
4
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
5
+ import { normalizeSafeId } from "../shared/safe-id.js";
5
6
  import { parseTaskControl } from "./control.js";
6
7
  import { nextTaskWake } from "./task-schedule.js";
7
8
  import { normalizeStoredStatus } from "./transitions.js";
@@ -30,12 +31,7 @@ const HISTORY_OMISSION_NOTE = "- Older cycle details omitted from working contex
30
31
  const HISTORY_TRUNCATION_NOTE = "- Entry truncated in working context; use session_search with the task id or cycle id to inspect the complete cold history.";
31
32
  /** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
32
33
  export function normalizeTaskId(id) {
33
- const trimmed = id.trim();
34
- const normalized = trimmed.endsWith(".md") ? trimmed.slice(0, -".md".length) : trimmed;
35
- if (!normalized || normalized === "." || normalized === ".." || !TASK_ID_PATTERN.test(normalized)) {
36
- throw new Error(`Invalid task id: ${id}`);
37
- }
38
- return normalized;
34
+ return normalizeSafeId(id, { suffix: ".md", pattern: TASK_ID_PATTERN, label: "task id" });
39
35
  }
40
36
  /** The document body after the leading frontmatter block, or the whole content when there is none. */
41
37
  export function taskBody(content) {
@@ -366,7 +362,7 @@ export function missingStandardTaskSections(content) {
366
362
  * Without the "no checklist items" case, a DoD written as prose or a numbered
367
363
  * list (no `- [ ]` anywhere) makes this function return an empty array —
368
364
  * indistinguishable from "everything is checked" — which would silently let
369
- * `task_manage complete` through with nothing ever actually verified.
365
+ * `task_close outcome=complete` through with nothing ever actually verified.
370
366
  */
371
367
  export function uncheckedTaskAcceptanceItems(content) {
372
368
  const unchecked = [];
@@ -4,7 +4,11 @@ export type TaskStatus = (typeof TASK_STATUSES)[number];
4
4
  /** Statuses a model/user may set directly; recurring sleeping is runtime-owned but repairable. */
5
5
  export declare const SETTABLE_TASK_STATUSES: readonly ["active", "waiting", "sleeping"];
6
6
  export type SettableTaskStatus = (typeof SETTABLE_TASK_STATUSES)[number];
7
- export type TaskLifecycleAction = "create" | "progress" | "verify" | "complete" | "skip" | "cancel" | "set" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
7
+ export type TaskLifecycleAction = "create"
8
+ /** task_update with a `note` — a checkpoint on an open cycle. */
9
+ | "checkpoint" | "verify" | "complete" | "skip" | "cancel"
10
+ /** task_update with no `note` — a metadata-only edit (spec 046, D3.2). */
11
+ | "metadata" | "pause" | "resume" | "run" | "governor-stop" | "wait-due" | "cycle-due";
8
12
  /** Canonicalize a stored status value, fail-open to `active` for anything not in the current vocabulary. */
9
13
  export declare function normalizeStoredStatus(raw: string | undefined): TaskStatus;
10
14
  export declare function isSettableTaskStatus(value: string): value is SettableTaskStatus;
@@ -7,7 +7,7 @@ const LIVE = ["active", "waiting", "sleeping"];
7
7
  const WORKABLE = ["active", "waiting"];
8
8
  const TRANSITIONS = {
9
9
  create: { from: [], to: "active" },
10
- progress: { from: WORKABLE, to: "caller" },
10
+ checkpoint: { from: WORKABLE, to: "caller" },
11
11
  // Not gated on a specific waitingFor value: the wake that reactivates a task parked for a
12
12
  // purpose=verify sub-agent already flips it to active before this runs (the same as any other
13
13
  // delegation wake), but `verify` also accepts waiting so it is not sensitive to exactly when
@@ -16,7 +16,7 @@ const TRANSITIONS = {
16
16
  complete: { from: ["active"], to: "caller" },
17
17
  skip: { from: WORKABLE, to: "sleeping" },
18
18
  cancel: { from: LIVE, to: "caller" },
19
- set: { from: LIVE, to: "caller" },
19
+ metadata: { from: LIVE, to: "caller" },
20
20
  pause: { from: LIVE, to: "caller" },
21
21
  resume: { from: LIVE, to: "caller" },
22
22
  run: { from: LIVE, to: "active" },
@@ -28,11 +28,13 @@ export interface VerificationAttestation {
28
28
  */
29
29
  subjectDir?: string;
30
30
  /**
31
- * `enforced` — a built-in verifier, whose write/edit tools are structurally removed before it
32
- * runs (a real gate). `advisory` — an external verifier (spec 040, D9): the tools cannot be
33
- * removed, so the verdict rests on the target CLI's own sandbox flag plus the workspace hash,
34
- * neither of which pipiclaw can prove. Defaults to `enforced` for attestations written before
35
- * this field existed — every verifier was built-in then.
31
+ * `enforced` — a built-in verifier that could not write at all: write/edit are structurally
32
+ * removed before it runs, and its role declared no `bash` either (a real gate). `advisory` —
33
+ * every other shape: an external verifier (spec 040, D9), whose tools cannot be removed so the
34
+ * verdict rests on the target CLI's own sandbox flag plus the workspace hash, and a built-in
35
+ * verifier that kept `bash`, which can write files just as well as `write` can. Defaults to
36
+ * `enforced` for attestations written before this field existed — every verifier was built-in
37
+ * and this distinction did not exist then.
36
38
  */
37
39
  verificationStrength: "enforced" | "advisory";
38
40
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
- import type { Executor } from "../executor.js";
4
+ import { type Executor } from "../executor.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  /**
7
7
  * Default wall-clock timeout for bash commands when the caller supplies neither a
@@ -11,7 +11,6 @@ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.j
11
11
  */
12
12
  export declare const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
13
13
  declare const bashSchema: Type.TObject<{
14
- label: Type.TString;
15
14
  command: Type.TString;
16
15
  timeout: Type.TOptional<Type.TInteger>;
17
16
  async: Type.TOptional<Type.TBoolean>;
@@ -1,9 +1,13 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { writeFile } from "node:fs/promises";
2
+ import { unlink } from "node:fs/promises";
3
3
  import { Type } from "typebox";
4
+ import { CommandTerminatedError } from "../executor.js";
5
+ import { formatBlockMessage } from "../security/block-message.js";
4
6
  import { guardCommand } from "../security/command-guard.js";
5
7
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
6
8
  import { logSecurityEvent } from "../security/logger.js";
9
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
10
+ import { clipText } from "../shared/text-utils.js";
7
11
  import { maybeOptimizeCommand } from "./command-optimizer.js";
8
12
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
9
13
  /**
@@ -23,7 +27,6 @@ function getSpillFilePath() {
23
27
  return `/tmp/pipiclaw-bash-${id}.log`;
24
28
  }
25
29
  const bashSchema = Type.Object({
26
- label: Type.String({ description: "Brief description of what this command does (shown to user)" }),
27
30
  command: Type.String({ description: "Bash command to execute" }),
28
31
  timeout: Type.Optional(Type.Integer({
29
32
  minimum: 1,
@@ -59,6 +62,16 @@ const BASH_INTERCEPTOR_RULES = [
59
62
  why: "it groups, paginates, and bounds output instead of flooding the context",
60
63
  },
61
64
  { test: /^\s*rg\b[^|&;]*$/, tool: "grep", why: "it groups, paginates, and bounds output" },
65
+ {
66
+ test: /^\s*find\s+[^|&;<>`$()]*-name\b[^|&;<>`$()]*$/,
67
+ tool: "glob",
68
+ why: "it discovers paths by pattern without a platform-dependent find dialect, and bounds/sorts the result",
69
+ },
70
+ {
71
+ test: /^\s*ls\s+-[A-Za-z]*R[A-Za-z]*\b[^|&;<>]*$/,
72
+ tool: "glob",
73
+ why: "it discovers file paths without listing directories, and bounds/sorts the result",
74
+ },
62
75
  {
63
76
  test: /\b(?:sed|perl)\b[^|&;]*\s-i\b/,
64
77
  tool: "edit",
@@ -74,18 +87,11 @@ function checkBashInterception(command) {
74
87
  return null;
75
88
  }
76
89
  function formatCommandBlockMessage(command, category, reason, matchedText) {
77
- const lines = [`Command blocked${category ? ` [${category}]` : ""}`];
78
- if (reason) {
79
- lines.push(`Reason: ${reason}`);
80
- }
81
- if (matchedText) {
82
- lines.push(`Matched: ${matchedText}`);
83
- }
84
- else {
85
- lines.push(`Command: ${command}`);
86
- }
87
- lines.push("If this operation is genuinely needed, explain the intent to the user so they can adjust security.json.");
88
- return lines.join("\n");
90
+ const details = [];
91
+ if (reason)
92
+ details.push({ label: "Reason", value: reason });
93
+ details.push(matchedText ? { label: "Matched", value: matchedText } : { label: "Command", value: command });
94
+ return `${formatBlockMessage("Command", category, details)}\nIf this operation is genuinely needed, explain the intent to the user so they can adjust security.json.`;
89
95
  }
90
96
  export function createBashTool(executor, options = {}) {
91
97
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
@@ -98,7 +104,7 @@ export function createBashTool(executor, options = {}) {
98
104
  label: "bash",
99
105
  description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
100
106
  parameters: bashSchema,
101
- execute: async (_toolCallId, { label, command, timeout, async: runAsync, notify, taskId, }, signal) => {
107
+ execute: async (_toolCallId, { command, timeout, async: runAsync, notify, taskId, }, signal) => {
102
108
  if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
103
109
  const guardResult = guardCommand(command, securityConfig.commandGuard);
104
110
  if (!guardResult.allowed) {
@@ -120,7 +126,7 @@ export function createBashTool(executor, options = {}) {
120
126
  if (options.interceptorEnabled) {
121
127
  const intercepted = checkBashInterception(command);
122
128
  if (intercepted) {
123
- throw new Error(intercepted);
129
+ throw new RecoverableToolError(intercepted);
124
130
  }
125
131
  }
126
132
  // Optimize *after* the security guard: the guard must inspect the operator's real
@@ -133,10 +139,11 @@ export function createBashTool(executor, options = {}) {
133
139
  // (the main path supplies a jobManager; the sub-agent path never does).
134
140
  if (runAsync) {
135
141
  if (!options.jobManager) {
136
- throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
142
+ throw new RecoverableToolError("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
137
143
  }
138
144
  const willNotify = notify ?? true;
139
- const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, {
145
+ const jobLabel = clipText(effectiveCommand, 60, { collapseWhitespace: true });
146
+ const job = await options.jobManager.start(effectiveCommand, jobLabel, effectiveTimeout, {
140
147
  signal,
141
148
  notify: willNotify,
142
149
  ...(taskId ? { taskId } : {}),
@@ -145,7 +152,7 @@ export function createBashTool(executor, options = {}) {
145
152
  content: [
146
153
  {
147
154
  type: "text",
148
- text: `Background job ${job.id} started: ${label}\n` +
155
+ text: `Background job ${job.id} started: ${jobLabel}\n` +
149
156
  (willNotify
150
157
  ? "It runs off-turn; end your turn now. You will be woken automatically when it finishes, " +
151
158
  "with its exit code and output — do not schedule a check-in for it."
@@ -155,69 +162,85 @@ export function createBashTool(executor, options = {}) {
155
162
  details: { async: { state: "running", jobId: job.id } },
156
163
  };
157
164
  }
158
- const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
159
- let output = "";
160
- if (result.stdout)
161
- output += result.stdout;
162
- if (result.stderr) {
163
- if (output)
164
- output += "\n";
165
- output += result.stderr;
166
- }
167
- const totalBytes = Buffer.byteLength(output, "utf-8");
168
- // Spill the full output to a temp file when it exceeds the inline limit, so the model
169
- // can page through the rest with `read`. Written straight to disk rather than piped
170
- // through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
171
- // (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
172
- // already runs on. Best-effort: on failure we simply omit the path hint.
173
- let tempFilePath;
174
- if (totalBytes > DEFAULT_MAX_BYTES) {
175
- const candidatePath = getSpillFilePath();
176
- try {
177
- await writeFile(candidatePath, output, { mode: 0o600 });
178
- tempFilePath = candidatePath;
165
+ // Spill + tail-truncate a combined stdout/stderr blob, sharing the same path for a normal
166
+ // result and one cut short by timeout/abort (fix plan §2.2): a timed-out `npm test` used
167
+ // to reject with up to 10MB of raw output stuffed straight into the tool-call error
168
+ // message, which the pi SDK puts into the model's context verbatim and unbounded.
169
+ //
170
+ // `spillPath` was written by the executor as stdout/stderr arrived (`ExecOptions.spillTo`,
171
+ // spec 044 D6.3) -- unlike the in-memory `stdout`/`stderr` here, it is never capped at
172
+ // the 10MB capture bound, so it is the one place that can honestly be called "full
173
+ // output" for a command whose real output exceeds that cap. It is deleted below when it
174
+ // turns out not to be needed.
175
+ const buildOutputText = async (stdout, stderr, spillPath) => {
176
+ let output = "";
177
+ if (stdout)
178
+ output += stdout;
179
+ if (stderr) {
180
+ if (output)
181
+ output += "\n";
182
+ output += stderr;
179
183
  }
180
- catch {
181
- // Ignore spill failures; the truncated output is still returned.
182
- }
183
- }
184
- // Apply tail truncation
185
- const truncation = truncateTail(output);
186
- let outputText = truncation.content || "(no output)";
187
- // Build details with truncation info
188
- let details;
189
- if (truncation.truncated) {
190
- details = {
191
- truncation,
192
- fullOutputPath: tempFilePath,
193
- };
194
- // Build actionable notice
195
- const startLine = truncation.totalLines - truncation.outputLines + 1;
196
- const endLine = truncation.totalLines;
197
- const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
198
- if (truncation.lastLinePartial) {
199
- // Edge case: last line alone > 50KB
200
- const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
201
- outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
202
- }
203
- else if (truncation.truncatedBy === "lines") {
204
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
184
+ const truncation = truncateTail(output);
185
+ let text = truncation.content || "(no output)";
186
+ let details;
187
+ if (truncation.truncated) {
188
+ details = { truncation, fullOutputPath: spillPath };
189
+ const startLine = truncation.totalLines - truncation.outputLines + 1;
190
+ const endLine = truncation.totalLines;
191
+ const fullOutputHint = ` Full output: ${spillPath}`;
192
+ if (truncation.lastLinePartial) {
193
+ const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
194
+ text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
195
+ }
196
+ else if (truncation.truncatedBy === "lines") {
197
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
198
+ }
199
+ else {
200
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
201
+ }
205
202
  }
206
203
  else {
207
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
204
+ // No truncation happened after all -- the spill file was insurance against the
205
+ // in-memory capture cap, not a promised artifact; clean it up rather than leaving
206
+ // tmp clutter behind on every single bash call.
207
+ await unlink(spillPath).catch(() => undefined);
208
208
  }
209
+ return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
210
+ };
211
+ const spillPath = getSpillFilePath();
212
+ try {
213
+ const result = await executor.exec(effectiveCommand, {
214
+ timeout: effectiveTimeout,
215
+ signal,
216
+ spillTo: spillPath,
217
+ });
218
+ const built = await buildOutputText(result.stdout, result.stderr, spillPath);
219
+ let outputText = built.text;
220
+ // A non-zero exit code is a normal result, not a tool failure: commands like
221
+ // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
222
+ // Report the code inline so the model can react without treating it as an error.
223
+ if (result.code !== 0) {
224
+ outputText += `\n\nExit code: ${result.code}`;
225
+ }
226
+ // Recorded unconditionally (not only on failure) because the task governor judges a
227
+ // wake's productivity from it: a command that ran clean and returned something is the
228
+ // evidence that a turn spent driving an external tool was not idle.
229
+ const details = { ...built.details, exitCode: result.code };
230
+ return { content: [{ type: "text", text: outputText }], details };
209
231
  }
210
- // A non-zero exit code is a normal result, not a tool failure: commands like
211
- // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
212
- // Report the code inline so the model can react without treating it as an error.
213
- if (result.code !== 0) {
214
- outputText += `\n\nExit code: ${result.code}`;
232
+ catch (error) {
233
+ if (!(error instanceof CommandTerminatedError)) {
234
+ throw error;
235
+ }
236
+ const built = await buildOutputText(error.stdout, error.stderr, spillPath);
237
+ const nextStep = error.reason === "timeout"
238
+ ? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
239
+ : "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
240
+ const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
241
+ const details = { ...built.details, timedOut: true };
242
+ return { content: [{ type: "text", text: outputText }], details };
215
243
  }
216
- // Recorded unconditionally (not only on failure) because the task governor judges a
217
- // wake's productivity from it: a command that ran clean and returned something is the
218
- // evidence that a turn spent driving an external tool was not idle.
219
- details = { ...details, exitCode: result.code, producedOutput: output.trim().length > 0 };
220
- return { content: [{ type: "text", text: outputText }], details };
221
244
  },
222
245
  };
223
246
  }
@@ -27,7 +27,7 @@ export interface PipiclawToolsConfig {
27
27
  web: PipiclawWebToolsConfig;
28
28
  /**
29
29
  * Master switch for the autonomous long-running task mechanism: gates the
30
- * `task_manage` tool, the native TaskDriver, and the per-turn task digest
30
+ * task_* tools, the native TaskDriver, and the per-turn task digest
31
31
  * together. Core capabilities (read/bash/edit/write/grep, memory, skills,
32
32
  * events, background jobs) are always on and have no switches.
33
33
  */
@@ -40,6 +40,11 @@ export interface PipiclawToolsConfig {
40
40
  rtk: {
41
41
  enabled: boolean;
42
42
  };
43
+ /** Gates the `subagent_inline` tool (spec 046, D2.3). Default true; the role directory
44
+ * covers most delegation, so a deployment can turn this off once it does. */
45
+ subagentInline: {
46
+ enabled: boolean;
47
+ };
43
48
  };
44
49
  }
45
50
  export interface LoadedToolsConfig {
@@ -35,6 +35,9 @@ export const DEFAULT_TOOLS_CONFIG = {
35
35
  rtk: {
36
36
  enabled: false,
37
37
  },
38
+ subagentInline: {
39
+ enabled: true,
40
+ },
38
41
  },
39
42
  };
40
43
  function clampInteger(value, fallback, minimum, maximum) {
@@ -81,6 +84,7 @@ function mergeToolsConfig(source, configPath, diagnostics) {
81
84
  const tasks = isRecord(tools.tasks) ? tools.tasks : {};
82
85
  const bashInterceptor = isRecord(tools.bashInterceptor) ? tools.bashInterceptor : {};
83
86
  const rtk = isRecord(tools.rtk) ? tools.rtk : {};
87
+ const subagentInline = isRecord(tools.subagentInline) ? tools.subagentInline : {};
84
88
  const search = isRecord(web.search) ? web.search : {};
85
89
  const fetch = isRecord(web.fetch) ? web.fetch : {};
86
90
  const providerValue = asTrimmedString(search.provider, DEFAULT_TOOLS_CONFIG.tools.web.search.provider).toLowerCase();
@@ -156,6 +160,11 @@ function mergeToolsConfig(source, configPath, diagnostics) {
156
160
  rtk: {
157
161
  enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
158
162
  },
163
+ subagentInline: {
164
+ enabled: typeof subagentInline.enabled === "boolean"
165
+ ? subagentInline.enabled
166
+ : DEFAULT_TOOLS_CONFIG.tools.subagentInline.enabled,
167
+ },
159
168
  },
160
169
  };
161
170
  }
@@ -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 editSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  path: Type.TString;
8
7
  oldText: Type.TString;
9
8
  newText: Type.TString;
@@ -14,5 +13,5 @@ export interface EditToolOptions {
14
13
  securityContext?: SecurityRuntimeContext;
15
14
  channelId?: string;
16
15
  }
17
- export declare function createEditTool(executor: Executor, options?: EditToolOptions): AgentTool<typeof editSchema>;
16
+ export declare function createEditTool(fileStore: FileStore, options?: EditToolOptions): AgentTool<typeof editSchema>;
18
17
  export {};