@oyasmi/pipiclaw 0.9.1-beta.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/agent/channel-runner.d.ts +7 -0
  2. package/dist/agent/channel-runner.js +42 -13
  3. package/dist/agent/command-extension.js +24 -27
  4. package/dist/agent/commands.d.ts +51 -7
  5. package/dist/agent/commands.js +199 -59
  6. package/dist/agent/prompt/manifest.js +5 -6
  7. package/dist/agent/prompt/sections.js +1 -0
  8. package/dist/agent/reply-limits.d.ts +16 -0
  9. package/dist/agent/reply-limits.js +17 -0
  10. package/dist/agent/session-events.js +2 -2
  11. package/dist/agent/status-render.js +12 -12
  12. package/dist/executor.d.ts +14 -0
  13. package/dist/executor.js +36 -6
  14. package/dist/main.js +3 -4
  15. package/dist/memory/commands.js +79 -38
  16. package/dist/memory/consolidation.d.ts +5 -1
  17. package/dist/memory/consolidation.js +33 -12
  18. package/dist/memory/extraction.d.ts +8 -1
  19. package/dist/memory/extraction.js +47 -4
  20. package/dist/memory/files.d.ts +0 -1
  21. package/dist/memory/files.js +24 -5
  22. package/dist/memory/lifecycle.js +9 -2
  23. package/dist/memory/maintenance-jobs.js +14 -4
  24. package/dist/memory/metadata.d.ts +3 -0
  25. package/dist/memory/metadata.js +7 -0
  26. package/dist/memory/recall.d.ts +9 -0
  27. package/dist/memory/recall.js +101 -17
  28. package/dist/memory/review-log.d.ts +0 -2
  29. package/dist/memory/review-log.js +0 -0
  30. package/dist/memory/session-corpus.js +5 -0
  31. package/dist/memory/session-search.js +9 -0
  32. package/dist/memory/sidecar-worker.js +4 -0
  33. package/dist/memory/source-window.d.ts +0 -1
  34. package/dist/memory/source-window.js +0 -5
  35. package/dist/playbooks/agent-delegation.md +32 -25
  36. package/dist/playbooks/background-jobs.md +8 -16
  37. package/dist/playbooks/event-scheduling.md +13 -15
  38. package/dist/playbooks/memory-and-learning.md +29 -22
  39. package/dist/playbooks/outbound-media.md +15 -8
  40. package/dist/playbooks/runtime-orientation.md +40 -37
  41. package/dist/playbooks/task-driving.md +34 -36
  42. package/dist/playbooks/task-planning.md +18 -18
  43. package/dist/runtime/app-home.d.ts +6 -0
  44. package/dist/runtime/app-home.js +15 -6
  45. package/dist/runtime/bootstrap.js +44 -13
  46. package/dist/runtime/channel-context.d.ts +2 -1
  47. package/dist/runtime/delivery.js +3 -3
  48. package/dist/runtime/dingtalk.d.ts +9 -1
  49. package/dist/runtime/dingtalk.js +27 -13
  50. package/dist/runtime/event-commands.d.ts +15 -0
  51. package/dist/runtime/event-commands.js +48 -40
  52. package/dist/runtime/project-commands.d.ts +16 -0
  53. package/dist/runtime/project-commands.js +13 -17
  54. package/dist/runtime/subagent-commands.d.ts +20 -0
  55. package/dist/runtime/subagent-commands.js +61 -58
  56. package/dist/runtime/task-commands.d.ts +37 -0
  57. package/dist/runtime/task-commands.js +106 -64
  58. package/dist/security/path-guard.js +33 -2
  59. package/dist/security/types.d.ts +9 -0
  60. package/dist/subagents/discovery.d.ts +7 -2
  61. package/dist/subagents/discovery.js +31 -7
  62. package/dist/subagents/external/claude-code.js +42 -2
  63. package/dist/subagents/external/run.js +61 -8
  64. package/dist/subagents/runs.js +6 -0
  65. package/dist/subagents/tool.d.ts +1 -0
  66. package/dist/subagents/tool.js +62 -53
  67. package/dist/tasks/verification.d.ts +7 -5
  68. package/dist/tools/bash.d.ts +1 -1
  69. package/dist/tools/bash.js +77 -59
  70. package/dist/tools/edit.js +17 -4
  71. package/dist/tools/grep.js +3 -2
  72. package/dist/tools/index.js +4 -0
  73. package/dist/tools/job.js +2 -1
  74. package/dist/tools/memory-manage.d.ts +1 -0
  75. package/dist/tools/memory-manage.js +54 -16
  76. package/dist/tools/read.js +21 -5
  77. package/dist/tools/send-media.js +17 -6
  78. package/dist/tools/skill-manage.js +12 -11
  79. package/dist/tools/skill-security.js +1 -1
  80. package/dist/tools/task-manage.js +1 -1
  81. package/dist/tools/truncate.d.ts +8 -0
  82. package/dist/tools/truncate.js +8 -0
  83. package/dist/tools/web-fetch.js +9 -1
  84. package/dist/tools/write-content.js +11 -1
  85. package/dist/tui/app.js +1 -1
  86. package/dist/tui/commands.d.ts +1 -1
  87. package/dist/tui/commands.js +1 -1
  88. package/dist/tui/turn-controller.d.ts +1 -1
  89. package/dist/tui/turn-controller.js +14 -4
  90. package/dist/usage/render.js +10 -8
  91. package/examples/sub-agents/README.md +2 -0
  92. package/package.json +3 -2
@@ -13,21 +13,73 @@ import { getSubAgentRunManager } from "../runs.js";
13
13
  import { getExternalHarness } from "./registry.js";
14
14
  import { finalizeExternalRun } from "./settlement.js";
15
15
  /**
16
- * Env vars the daemon's own credentials tend to live in — dropped by default from an external
16
+ * Env vars pipiclaw's own credentials tend to live in — dropped by default from an external
17
17
  * process's environment. A target repo's `CLAUDE.md`/prompt can steer an external agent's actions
18
18
  * (it is a separate, untrusted host process, not sandboxed by pipiclaw's own guards), so it should
19
- * not inherit pipiclaw's own provider keys or DingTalk credentials just because it inherits the
20
- * daemon's shell (review 2026-08-23 §2.4). A role can add any of these back explicitly via `env:`.
19
+ * not inherit pipiclaw's own LLM provider keys or DingTalk credentials just because it inherits
20
+ * the daemon's shell (review 2026-08-23 §2.4). A role can add any of these back explicitly via
21
+ * `env:`.
22
+ *
23
+ * An explicit name list, not a suffix pattern (fix plan §4.3): a `_API_KEY`/`_SECRET`/`_TOKEN`/
24
+ * `_PASSWORD` suffix regex both over-blocks (a role that shells out to `gh`/`npm` loses
25
+ * `GITHUB_TOKEN`/`NPM_TOKEN` with zero explanation) and under-blocks (`AWS_SECRET_ACCESS_KEY`,
26
+ * `GOOGLE_APPLICATION_CREDENTIALS`, `SSH_AUTH_SOCK` do not match the suffix at all). This list is
27
+ * therefore deliberately narrow: only the env vars pipiclaw's own LLM calls and DingTalk transport
28
+ * read (`src/models/api-keys.ts`, the `pi-ai` provider registry). It is a courtesy against
29
+ * accidental inheritance, not a security boundary — the real boundary is the role's own command,
30
+ * CLI sandbox, and host account (AGENTS.md).
21
31
  */
22
- const SENSITIVE_ENV_PATTERN = /(?:_API_KEY|_SECRET|_TOKEN|_PASSWORD)$/i;
32
+ const SENSITIVE_ENV_VAR_NAMES = new Set([
33
+ "ANTHROPIC_API_KEY",
34
+ "ANTHROPIC_AUTH_TOKEN",
35
+ "ANTHROPIC_OAUTH_TOKEN",
36
+ "OPENAI_API_KEY",
37
+ "GOOGLE_API_KEY",
38
+ "GEMINI_API_KEY",
39
+ "GOOGLE_CLOUD_API_KEY",
40
+ "AZURE_OPENAI_API_KEY",
41
+ "MISTRAL_API_KEY",
42
+ "GROQ_API_KEY",
43
+ "CEREBRAS_API_KEY",
44
+ "DEEPSEEK_API_KEY",
45
+ "XAI_API_KEY",
46
+ "OPENROUTER_API_KEY",
47
+ "TOGETHER_API_KEY",
48
+ "FIREWORKS_API_KEY",
49
+ "MOONSHOT_API_KEY",
50
+ "MINIMAX_API_KEY",
51
+ "MINIMAX_CN_API_KEY",
52
+ "KIMI_API_KEY",
53
+ "ZAI_API_KEY",
54
+ "QWEN_TOKEN_PLAN_API_KEY",
55
+ "QWEN_TOKEN_PLAN_CN_API_KEY",
56
+ "NVIDIA_API_KEY",
57
+ "OPENCODE_API_KEY",
58
+ "CLOUDFLARE_API_KEY",
59
+ "AI_GATEWAY_API_KEY",
60
+ ]);
61
+ /** Filters an external process's inherited env, returning the keys it actually dropped so the
62
+ * caller can surface them in `invocationWarnings` — silently dropping `GITHUB_TOKEN` or
63
+ * similar with zero trace is exactly what made this hard to diagnose before (fix plan §4.3). */
23
64
  function filterSensitiveEnv(env) {
24
65
  const filtered = {};
66
+ const dropped = [];
25
67
  for (const [key, value] of Object.entries(env)) {
26
- if (SENSITIVE_ENV_PATTERN.test(key) || key.startsWith("DINGTALK_"))
68
+ if (SENSITIVE_ENV_VAR_NAMES.has(key) || key.startsWith("DINGTALK_")) {
69
+ dropped.push(key);
27
70
  continue;
71
+ }
28
72
  filtered[key] = value;
29
73
  }
30
- return filtered;
74
+ return { filtered, dropped };
75
+ }
76
+ /** Only set when at least one credential was actually present and dropped -- a role that never
77
+ * had `GITHUB_TOKEN` set in the first place gets no noise about it. */
78
+ function mergeInvocationWarnings(warnings, droppedEnvVars) {
79
+ if (droppedEnvVars.length === 0)
80
+ return warnings;
81
+ const envWarning = `Dropped from this process's environment (add back via the role's env: if needed): ${droppedEnvVars.join(", ")}`;
82
+ return warnings ? [...warnings, envWarning] : [envWarning];
31
83
  }
32
84
  function classifySpawnError(error) {
33
85
  const code = error.code;
@@ -149,13 +201,14 @@ export async function launchExternalRun(input) {
149
201
  await runManager.settle(input.runId, failedSettleInput(reason), { announce: false });
150
202
  return { ok: false, kind: "launch-failed", reason };
151
203
  }
204
+ const envFilterResult = filterSensitiveEnv(process.env);
152
205
  const spawnFn = input.spawnFn ?? nodeSpawn;
153
206
  let child;
154
207
  try {
155
208
  child = spawnFn(invocation.executable, invocation.args, {
156
209
  detached: true,
157
210
  cwd: input.workingDirectory,
158
- env: { ...filterSensitiveEnv(process.env), ...input.env },
211
+ env: { ...envFilterResult.filtered, ...input.env },
159
212
  // stdout/stderr point straight at the artifact files (P0-1): the child writes them
160
213
  // itself, so they land on disk even if this daemon disappears before it exits.
161
214
  stdio: ["pipe", eventsFd, stderrFd],
@@ -226,7 +279,7 @@ export async function launchExternalRun(input) {
226
279
  maxWallTimeSec: input.maxWallTimeSec,
227
280
  processStartedAt,
228
281
  channelDir: input.channelDir,
229
- invocationWarnings: invocation.warnings,
282
+ invocationWarnings: mergeInvocationWarnings(invocation.warnings, envFilterResult.dropped),
230
283
  // Spec 042 D12: distinguishes "the target CLI's schema drifted" from "the agent failed".
231
284
  parserVersion: harness.parserVersion,
232
285
  cliVersion,
@@ -512,6 +512,12 @@ export class SubAgentRunManager {
512
512
  }
513
513
  : {}),
514
514
  };
515
+ // The `boolean` return value (queue-full/backpressure -> `false`) is deliberately not
516
+ // checked here, unlike the thrown-error case above: `DurableDispatchService.enqueueEvent`
517
+ // puts a rejected record back into `pending` rather than dropping it, and the 30s periodic
518
+ // drain retries it from there -- so marking `wakeEnqueued` on a `false` return is still safe,
519
+ // not a lost wake (fix plan §1.7 / review 2026-08-24 §1.7). Re-verify this against
520
+ // `durable-dispatch.ts` before changing either side.
515
521
  try {
516
522
  await this.options.dispatch(event);
517
523
  }
@@ -25,6 +25,7 @@ declare const subagentSchema: Type.TObject<{
25
25
  taskId: Type.TOptional<Type.TString>;
26
26
  returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
27
27
  thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
28
+ mutates: Type.TOptional<Type.TUnion<[Type.TLiteral<"read">, Type.TLiteral<"write">]>>;
28
29
  }>;
29
30
  /**
30
31
  * Fields the `subagent` tool itself constructs. `kind` is not among them: `withToolDetails`
@@ -2,7 +2,7 @@ import { existsSync, realpathSync, statSync } from "node:fs";
2
2
  import { mkdir } from "node:fs/promises";
3
3
  import { isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { Agent } from "@earendil-works/pi-agent-core";
5
- import { streamSimple } from "@earendil-works/pi-ai/compat";
5
+ import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
6
6
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
7
7
  import { Type } from "typebox";
8
8
  import * as log from "../log.js";
@@ -20,7 +20,7 @@ import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
20
20
  import { readStoredTask } from "../tasks/store.js";
21
21
  import { writeVerificationAttestation } from "../tasks/verification.js";
22
22
  import { buildToolSet } from "../tools/registry.js";
23
- import { externalRoleFingerprint, formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
23
+ import { DEFAULT_THINKING_LEVEL, externalRoleFingerprint, formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
24
24
  import { launchExternalRun } from "./external/run.js";
25
25
  import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
26
26
  import { resolveVerificationOutcome } from "./verification-outcome.js";
@@ -63,7 +63,13 @@ const subagentSchema = Type.Object({
63
63
  Type.Literal("xhigh"),
64
64
  Type.Literal("max"),
65
65
  ], {
66
- description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for purpose=verify, "off" otherwise.',
66
+ description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for internal delegations and for external purpose=verify; ' +
67
+ "an external purpose=work delegation with no explicit value leaves this unset, so the target CLI's own configuration decides.",
68
+ })),
69
+ mutates: Type.Optional(Type.Union([Type.Literal("read"), Type.Literal("write")], {
70
+ description: 'Whether this delegation will modify the working directory. Declare "write" whenever the sub-agent may write ' +
71
+ "files (including through bash) so it takes the exclusive workspace write lease. Defaults to inference from " +
72
+ "`tools` (write/edit only), which does not see bash.",
67
73
  })),
68
74
  });
69
75
  const DEFAULT_SUBAGENT_MEMORY_RECALL_SETTINGS = {
@@ -288,6 +294,9 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
288
294
  executor,
289
295
  securityConfig,
290
296
  securityContext: {
297
+ // No `channelDir`: a sub-agent receives channel state through its injected context
298
+ // blocks, not by reading the channel's own files, so it does not inherit the parent's
299
+ // channel-directory exception (see security/types.ts).
291
300
  agentWorkspaceDir: options.workspaceDir,
292
301
  projectRoot: runContext.workingDirectory,
293
302
  boundary: options.projectBoundary,
@@ -449,8 +458,8 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
449
458
  return {
450
459
  agent: config.name,
451
460
  source: config.source,
452
- model: formatModelReference(config.model),
453
- tools: [...config.tools],
461
+ model: extras?.modelOverride ?? formatModelReference(config.model),
462
+ tools: extras?.toolsOverride ?? [...config.tools],
454
463
  turns,
455
464
  toolCalls,
456
465
  durationMs,
@@ -467,6 +476,7 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
467
476
  artifactDir: runContext.artifactDir,
468
477
  artifactPath: extras?.artifactPath,
469
478
  resultTruncated: extras?.resultTruncated ?? false,
479
+ dispatched: extras?.dispatched,
470
480
  };
471
481
  }
472
482
  /**
@@ -507,6 +517,9 @@ export function createSubAgentTool(options) {
507
517
  throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
508
518
  }
509
519
  const config = invocation.config;
520
+ // Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
521
+ // `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
522
+ const mutatesNote = invocation.warning ? `Note: ${invocation.warning}\n\n` : "";
510
523
  const returns = params.returns ?? "text";
511
524
  // Spec 042 D3: `returns: "artifact"` has no external equivalent — the marker protocol
512
525
  // scopes a produced file to `artifactDir`, but an external agent's real output lives in
@@ -555,7 +568,12 @@ export function createSubAgentTool(options) {
555
568
  // always "text" here — passed literally rather than the `returns` variable so the
556
569
  // ARTIFACT marker protocol is never injected into an external envelope, which no
557
570
  // external result parser has ever read.
558
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
571
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
572
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
573
+ // beats failing a dispatch that would otherwise have run fine.
574
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
575
+ return [];
576
+ });
559
577
  const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, "text");
560
578
  launchResult = await launchExternalRun({
561
579
  runId: runContext.runId,
@@ -611,23 +629,11 @@ export function createSubAgentTool(options) {
611
629
  "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
612
630
  },
613
631
  ],
614
- details: {
615
- agent: config.name,
616
- source: config.source,
617
- model: config.externalModelRef ?? "unknown",
618
- tools: [],
619
- turns: 0,
620
- toolCalls: 0,
621
- durationMs: 0,
622
- failed: false,
623
- usage: createEmptyUsageTotals(),
624
- runId: runContext.runId,
625
- purpose: runContext.purpose,
626
- taskId: runContext.taskId,
627
- artifactDir: runContext.artifactDir,
628
- resultTruncated: false,
632
+ details: createDetails(config, runContext, createEmptyUsageTotals(), 0, 0, 0, false, undefined, undefined, {
629
633
  dispatched: true,
630
- },
634
+ modelOverride: config.externalModelRef ?? "unknown",
635
+ toolsOverride: [],
636
+ }),
631
637
  };
632
638
  }
633
639
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
@@ -710,7 +716,12 @@ export function createSubAgentTool(options) {
710
716
  initialState: {
711
717
  systemPrompt: config.systemPrompt,
712
718
  model: config.model,
713
- thinkingLevel: config.thinkingLevel,
719
+ // Same clamp the main agent applies (channel-runner.ts) before setting a model's
720
+ // thinkingLevel: a model with `reasoning: false` gets "off", an unsupported tier
721
+ // snaps to the nearest one, instead of a raw unsupported value reaching the provider.
722
+ // The internal path's resolved config always fills thinkingLevel; the fallback
723
+ // here only closes the type.
724
+ thinkingLevel: clampThinkingLevel(config.model, config.thinkingLevel ?? DEFAULT_THINKING_LEVEL),
714
725
  tools: filterToolsByName(availableTools, config.tools),
715
726
  },
716
727
  convertToLlm,
@@ -800,7 +811,12 @@ export function createSubAgentTool(options) {
800
811
  */
801
812
  async function runToCompletion() {
802
813
  try {
803
- const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
814
+ const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel).catch((error) => {
815
+ // Context injection is an enhancement, not a precondition -- degrading to no context blocks
816
+ // beats failing a dispatch that would otherwise have run fine.
817
+ log.logWarning(`[${options.runtimeContext.channelId}] Sub-agent context injection failed; continuing without it`, errorMessage(error));
818
+ return [];
819
+ });
804
820
  await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
805
821
  await activeWorker.waitForIdle();
806
822
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
@@ -853,8 +869,8 @@ export function createSubAgentTool(options) {
853
869
  const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
854
870
  // Spec 042 D1: the pass/fail judgment rule is shared with the external verify path
855
871
  // (`resolveVerificationOutcome`) so there is exactly one place deciding what a verify
856
- // run's own output does and does not prove. Only the attestation write (and its
857
- // "enforced" strength) stays here, since only the internal path structurally removes
872
+ // run's own output does and does not prove. Only the attestation write and the
873
+ // strength label stay here, since only the internal path can structurally remove
858
874
  // write/edit from the verifier's tool set.
859
875
  const verification = runContext.purpose === "verify"
860
876
  ? resolveVerificationOutcome({
@@ -867,6 +883,15 @@ export function createSubAgentTool(options) {
867
883
  })
868
884
  : undefined;
869
885
  const verificationVerdict = verification?.verdict;
886
+ // Internal verify always keeps write/edit structurally removed from the verifier's
887
+ // tool set (buildSubagentTools above), but `bash` stays available by default and can
888
+ // write files just as well — labeling that "enforced" would be dishonest (review
889
+ // 2026-08-23 §2.2). Only a role that dropped `bash` from its declared tool list earns
890
+ // the stronger label. Computed once so the attestation and the run record — the
891
+ // latter is what the completion wake and `subagent_manage` display — cannot disagree.
892
+ const internalVerificationStrength = config.tools.includes("bash")
893
+ ? "advisory"
894
+ : "enforced";
870
895
  if (runContext.purpose === "verify" && runContext.taskId && verification) {
871
896
  await writeVerificationAttestation(options.channelDir, {
872
897
  runId: runContext.runId,
@@ -877,12 +902,7 @@ export function createSubAgentTool(options) {
877
902
  workspaceChanged: verification.workspaceChanged,
878
903
  subjectHash: verification.workspaceChanged ? undefined : verifierSubjectAfter,
879
904
  subjectDir: runContext.workingDirectory,
880
- // Internal verify always keeps write/edit structurally removed from the
881
- // verifier's tool set (buildSubagentTools above), but `bash` stays available by
882
- // default and can write files just as well — labeling that "enforced" would be
883
- // dishonest (review 2026-08-23 §2.2). Only a role that dropped `bash` from its
884
- // declared tool list earns the stronger label.
885
- verificationStrength: config.tools.includes("bash") ? "advisory" : "enforced",
905
+ verificationStrength: internalVerificationStrength,
886
906
  });
887
907
  }
888
908
  // Internal runs always report full usage; cost is "unknown" only for the shape a
@@ -897,7 +917,7 @@ export function createSubAgentTool(options) {
897
917
  toolCalls,
898
918
  durationMs,
899
919
  verificationVerdict,
900
- verificationStrength: runContext.purpose === "verify" ? "enforced" : undefined,
920
+ verificationStrength: runContext.purpose === "verify" ? internalVerificationStrength : undefined,
901
921
  };
902
922
  if (effectiveFailureReason) {
903
923
  if (!finalText.trim()) {
@@ -909,7 +929,10 @@ export function createSubAgentTool(options) {
909
929
  return {
910
930
  toolResult: {
911
931
  content: [
912
- { type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) },
932
+ {
933
+ type: "text",
934
+ text: mutatesNote + buildStoppedText(config, effectiveFailureReason, finalized.replyText),
935
+ },
913
936
  ],
914
937
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
915
938
  },
@@ -929,7 +952,8 @@ export function createSubAgentTool(options) {
929
952
  content: [
930
953
  {
931
954
  type: "text",
932
- text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
955
+ text: mutatesNote +
956
+ (finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`),
933
957
  },
934
958
  ],
935
959
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
@@ -984,28 +1008,13 @@ export function createSubAgentTool(options) {
984
1008
  content: [
985
1009
  {
986
1010
  type: "text",
987
- text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
1011
+ text: mutatesNote +
1012
+ `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
988
1013
  "Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
989
1014
  "Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
990
1015
  },
991
1016
  ],
992
- details: {
993
- agent: config.name,
994
- source: config.source,
995
- model: formatModelReference(config.model),
996
- tools: [...config.tools],
997
- turns: assistantTurns,
998
- toolCalls,
999
- durationMs: Date.now() - startedAt,
1000
- failed: false,
1001
- usage: { ...usage, cost: { ...usage.cost } },
1002
- runId: runContext.runId,
1003
- purpose: runContext.purpose,
1004
- taskId: runContext.taskId,
1005
- artifactDir: runContext.artifactDir,
1006
- resultTruncated: false,
1007
- dispatched: true,
1008
- },
1017
+ details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, false, undefined, undefined, { dispatched: true }),
1009
1018
  };
1010
1019
  },
1011
1020
  };
@@ -28,11 +28,13 @@ export interface VerificationAttestation {
28
28
  */
29
29
  subjectDir?: string;
30
30
  /**
31
- * `enforced` — a built-in verifier, whose write/edit tools are structurally removed before it
32
- * runs (a real gate). `advisory` — an external verifier (spec 040, D9): the tools cannot be
33
- * removed, so the verdict rests on the target CLI's own sandbox flag plus the workspace hash,
34
- * neither of which pipiclaw can prove. Defaults to `enforced` for attestations written before
35
- * this field existed — every verifier was built-in then.
31
+ * `enforced` — a built-in verifier that could not write at all: write/edit are structurally
32
+ * removed before it runs, and its role declared no `bash` either (a real gate). `advisory` —
33
+ * every other shape: an external verifier (spec 040, D9), whose tools cannot be removed so the
34
+ * verdict rests on the target CLI's own sandbox flag plus the workspace hash, and a built-in
35
+ * verifier that kept `bash`, which can write files just as well as `write` can. Defaults to
36
+ * `enforced` for attestations written before this field existed — every verifier was built-in
37
+ * and this distinction did not exist then.
36
38
  */
37
39
  verificationStrength: "enforced" | "advisory";
38
40
  }
@@ -1,7 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
- import type { Executor } from "../executor.js";
4
+ import { type Executor } from "../executor.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  /**
7
7
  * Default wall-clock timeout for bash commands when the caller supplies neither a
@@ -1,9 +1,11 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { writeFile } from "node:fs/promises";
3
3
  import { Type } from "typebox";
4
+ import { CommandTerminatedError } from "../executor.js";
4
5
  import { guardCommand } from "../security/command-guard.js";
5
6
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
6
7
  import { logSecurityEvent } from "../security/logger.js";
8
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
7
9
  import { maybeOptimizeCommand } from "./command-optimizer.js";
8
10
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
9
11
  /**
@@ -120,7 +122,7 @@ export function createBashTool(executor, options = {}) {
120
122
  if (options.interceptorEnabled) {
121
123
  const intercepted = checkBashInterception(command);
122
124
  if (intercepted) {
123
- throw new Error(intercepted);
125
+ throw new RecoverableToolError(intercepted);
124
126
  }
125
127
  }
126
128
  // Optimize *after* the security guard: the guard must inspect the operator's real
@@ -133,7 +135,7 @@ export function createBashTool(executor, options = {}) {
133
135
  // (the main path supplies a jobManager; the sub-agent path never does).
134
136
  if (runAsync) {
135
137
  if (!options.jobManager) {
136
- throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
138
+ throw new RecoverableToolError("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
137
139
  }
138
140
  const willNotify = notify ?? true;
139
141
  const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, {
@@ -155,69 +157,85 @@ export function createBashTool(executor, options = {}) {
155
157
  details: { async: { state: "running", jobId: job.id } },
156
158
  };
157
159
  }
158
- const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
159
- let output = "";
160
- if (result.stdout)
161
- output += result.stdout;
162
- if (result.stderr) {
163
- if (output)
164
- output += "\n";
165
- output += result.stderr;
166
- }
167
- const totalBytes = Buffer.byteLength(output, "utf-8");
168
- // Spill the full output to a temp file when it exceeds the inline limit, so the model
169
- // can page through the rest with `read`. Written straight to disk rather than piped
170
- // through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
171
- // (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
172
- // already runs on. Best-effort: on failure we simply omit the path hint.
173
- let tempFilePath;
174
- if (totalBytes > DEFAULT_MAX_BYTES) {
175
- const candidatePath = getSpillFilePath();
176
- try {
177
- await writeFile(candidatePath, output, { mode: 0o600 });
178
- tempFilePath = candidatePath;
160
+ // Spill + tail-truncate a combined stdout/stderr blob, sharing the same path for a normal
161
+ // result and one cut short by timeout/abort (fix plan §2.2): a timed-out `npm test` used
162
+ // to reject with up to 10MB of raw output stuffed straight into the tool-call error
163
+ // message, which the pi SDK puts into the model's context verbatim and unbounded.
164
+ const buildOutputText = async (stdout, stderr) => {
165
+ let output = "";
166
+ if (stdout)
167
+ output += stdout;
168
+ if (stderr) {
169
+ if (output)
170
+ output += "\n";
171
+ output += stderr;
179
172
  }
180
- catch {
181
- // Ignore spill failures; the truncated output is still returned.
173
+ const totalBytes = Buffer.byteLength(output, "utf-8");
174
+ // Spill the full output to a temp file when it exceeds the inline limit, so the model
175
+ // can page through the rest with `read`. Written straight to disk rather than piped
176
+ // through a second `sh -c 'cat > file'`: that spawned a process and copied the whole
177
+ // (up to 10MB) buffer over a pipe to reach the same local filesystem the executor
178
+ // already runs on. Best-effort: on failure we simply omit the path hint.
179
+ let tempFilePath;
180
+ if (totalBytes > DEFAULT_MAX_BYTES) {
181
+ const candidatePath = getSpillFilePath();
182
+ try {
183
+ await writeFile(candidatePath, output, { mode: 0o600 });
184
+ tempFilePath = candidatePath;
185
+ }
186
+ catch {
187
+ // Ignore spill failures; the truncated output is still returned.
188
+ }
182
189
  }
183
- }
184
- // Apply tail truncation
185
- const truncation = truncateTail(output);
186
- let outputText = truncation.content || "(no output)";
187
- // Build details with truncation info
188
- let details;
189
- if (truncation.truncated) {
190
- details = {
191
- truncation,
192
- fullOutputPath: tempFilePath,
193
- };
194
- // Build actionable notice
195
- const startLine = truncation.totalLines - truncation.outputLines + 1;
196
- const endLine = truncation.totalLines;
197
- const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
198
- if (truncation.lastLinePartial) {
199
- // Edge case: last line alone > 50KB
200
- const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
201
- outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
190
+ const truncation = truncateTail(output);
191
+ let text = truncation.content || "(no output)";
192
+ let details;
193
+ if (truncation.truncated) {
194
+ details = { truncation, fullOutputPath: tempFilePath };
195
+ const startLine = truncation.totalLines - truncation.outputLines + 1;
196
+ const endLine = truncation.totalLines;
197
+ const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
198
+ if (truncation.lastLinePartial) {
199
+ const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
200
+ text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
201
+ }
202
+ else if (truncation.truncatedBy === "lines") {
203
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
204
+ }
205
+ else {
206
+ text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
207
+ }
202
208
  }
203
- else if (truncation.truncatedBy === "lines") {
204
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
205
- }
206
- else {
207
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
209
+ return { text, details: { ...details, producedOutput: output.trim().length > 0 } };
210
+ };
211
+ try {
212
+ const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
213
+ const built = await buildOutputText(result.stdout, result.stderr);
214
+ let outputText = built.text;
215
+ // A non-zero exit code is a normal result, not a tool failure: commands like
216
+ // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
217
+ // Report the code inline so the model can react without treating it as an error.
218
+ if (result.code !== 0) {
219
+ outputText += `\n\nExit code: ${result.code}`;
208
220
  }
221
+ // Recorded unconditionally (not only on failure) because the task governor judges a
222
+ // wake's productivity from it: a command that ran clean and returned something is the
223
+ // evidence that a turn spent driving an external tool was not idle.
224
+ const details = { ...built.details, exitCode: result.code };
225
+ return { content: [{ type: "text", text: outputText }], details };
209
226
  }
210
- // A non-zero exit code is a normal result, not a tool failure: commands like
211
- // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
212
- // Report the code inline so the model can react without treating it as an error.
213
- if (result.code !== 0) {
214
- outputText += `\n\nExit code: ${result.code}`;
227
+ catch (error) {
228
+ if (!(error instanceof CommandTerminatedError)) {
229
+ throw error;
230
+ }
231
+ const built = await buildOutputText(error.stdout, error.stderr);
232
+ const nextStep = error.reason === "timeout"
233
+ ? `Retry with a larger \`timeout\` (currently ${error.timeoutSeconds}s), or pass \`async: true\` to run it in the background and be woken when it finishes.`
234
+ : "The command was stopped (e.g. by /stop or a run cancellation); partial output above.";
235
+ const outputText = `${built.text}\n\n[${error.message}; partial output above. ${nextStep}]`;
236
+ const details = { ...built.details, timedOut: true };
237
+ return { content: [{ type: "text", text: outputText }], details };
215
238
  }
216
- // Recorded unconditionally (not only on failure) because the task governor judges a
217
- // wake's productivity from it: a command that ran clean and returned something is the
218
- // evidence that a turn spent driving an external tool was not idle.
219
- details = { ...details, exitCode: result.code, producedOutput: output.trim().length > 0 };
220
- return { content: [{ type: "text", text: outputText }], details };
221
239
  },
222
240
  };
223
241
  }
@@ -3,6 +3,7 @@ import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
4
  import { logSecurityEvent } from "../security/logger.js";
5
5
  import { guardPath } from "../security/path-guard.js";
6
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
6
7
  import { shellEscape } from "../shared/shell-escape.js";
7
8
  import { writeContent } from "./write-content.js";
8
9
  /**
@@ -144,17 +145,17 @@ export function createEditTool(executor, options = {}) {
144
145
  // Read the file
145
146
  const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
146
147
  if (readResult.code !== 0) {
147
- throw new Error(readResult.stderr || `File not found: ${path}`);
148
+ throw new RecoverableToolError(readResult.stderr || `File not found: ${path}`);
148
149
  }
149
150
  const content = readResult.stdout;
150
151
  // Check if old text exists
151
152
  if (!content.includes(oldText)) {
152
- throw new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
153
+ throw new RecoverableToolError(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
153
154
  }
154
155
  // Count occurrences
155
156
  const occurrences = content.split(oldText).length - 1;
156
157
  if (occurrences > 1 && !replaceAll) {
157
- throw new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique, or pass replaceAll: true to replace all of them. Please provide more context to make it unique.`);
158
+ throw new RecoverableToolError(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique, or pass replaceAll: true to replace all of them. Please provide more context to make it unique.`);
158
159
  }
159
160
  // Perform replacement
160
161
  let newContent;
@@ -174,11 +175,23 @@ export function createEditTool(executor, options = {}) {
174
175
  `The bug is somewhere else — re-read the file to verify the anchor text before editing again. ` +
175
176
  `Do NOT widen oldText or add lines to force a match.`);
176
177
  }
177
- throw new Error(`No changes made to ${path}: oldText and newText are byte-identical at the match, so the replacement produced no change. ` +
178
+ throw new RecoverableToolError(`No changes made to ${path}: oldText and newText are byte-identical at the match, so the replacement produced no change. ` +
178
179
  `Re-read the file to confirm what actually needs changing before editing again.`);
179
180
  }
180
181
  // A real edit breaks any no-op streak.
181
182
  noopCounts.clear();
183
+ // Re-read immediately before writing back and compare against what was read at the top of
184
+ // this call (fix plan §2.4/§4.2): a background job, an external agent, or a concurrent
185
+ // `bash`/`edit` call (none of which the workspace write lease protects for the caller's own
186
+ // tool calls -- only inter-delegation writes) can change the file in between. Without this,
187
+ // the write below would silently clobber whatever changed it, keeping only this call's
188
+ // edit and discarding the other writer's. This narrows the race to the read-compare-write
189
+ // gap itself rather than closing it -- cheap insurance, not a lock.
190
+ const recheck = await executor.exec(`cat ${shellEscape(path)}`, { signal });
191
+ if (recheck.code === 0 && recheck.stdout !== content) {
192
+ throw new RecoverableToolError(`${path} changed during this edit (likely a background job or another agent writing concurrently). ` +
193
+ "Re-read the file and re-apply the edit against its current content.");
194
+ }
182
195
  // Write the file back
183
196
  await writeContent(executor, path, newContent, signal, {
184
197
  securityConfig,