pi-crew 0.11.24 → 0.11.26

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 (112) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +2 -2
  3. package/agents/designer.md +23 -0
  4. package/agents/orchestrator.md +17 -0
  5. package/agents/verifier.md +1 -1
  6. package/dist/index.mjs +568 -559
  7. package/{workflows/chain.workflow.md → docs/chain-workflow.md} +8 -0
  8. package/docs/dynamic-workflows.md +23 -0
  9. package/docs/publishing.md +34 -5
  10. package/docs/troubleshooting.md +50 -2
  11. package/docs/usage.md +7 -2
  12. package/install.mjs +2 -1
  13. package/package.json +4 -2
  14. package/skills/read-only-explorer/SKILL.md +15 -5
  15. package/skills/real-test-pi-crew/SKILL.md +7 -7
  16. package/src/config/config-validation.ts +58 -0
  17. package/src/config/config.ts +90 -5
  18. package/src/config/env-vars.ts +14 -7
  19. package/src/config/role-tools.ts +7 -5
  20. package/src/config/types.ts +4 -1
  21. package/src/extension/crew-cleanup.ts +6 -0
  22. package/src/extension/project-init.ts +19 -1
  23. package/src/extension/register.ts +68 -30
  24. package/src/extension/registration/artifact-cleanup.ts +52 -11
  25. package/src/extension/registration/commands/manage.ts +9 -2
  26. package/src/extension/registration/hook-registration.ts +3 -0
  27. package/src/extension/registration/lazy-configurers.ts +2 -0
  28. package/src/extension/registration/lifecycle-handlers.ts +79 -18
  29. package/src/extension/registration/render-loop.ts +27 -2
  30. package/src/extension/registration/tool-loop-guard.ts +5 -3
  31. package/src/extension/registration/verify-gate-tool.ts +7 -3
  32. package/src/extension/team-tool/api/read.ts +12 -3
  33. package/src/extension/team-tool/cancel.ts +11 -0
  34. package/src/extension/team-tool/config-patch.ts +56 -11
  35. package/src/extension/team-tool/destructive-gate.ts +72 -12
  36. package/src/extension/team-tool/dispatch/manage.ts +9 -1
  37. package/src/extension/team-tool/handle-schedule.ts +38 -4
  38. package/src/extension/team-tool/handle-settings.ts +76 -6
  39. package/src/extension/team-tool/health-monitor.ts +14 -2
  40. package/src/extension/team-tool/lifecycle-actions.ts +28 -10
  41. package/src/extension/team-tool/respond.ts +12 -5
  42. package/src/extension/team-tool/run-deadline.ts +29 -2
  43. package/src/extension/team-tool/run.ts +11 -0
  44. package/src/extension/team-tool/status.ts +64 -8
  45. package/src/extension/team-tool/workflow-manage.ts +5 -1
  46. package/src/extension/team-tool.ts +3 -0
  47. package/src/i18n.ts +18 -14
  48. package/src/prompt/inbox-poll.ts +14 -2
  49. package/src/prompt/message-tool.ts +1 -1
  50. package/src/prompt/prompt-runtime.ts +25 -3
  51. package/src/prompt/scratchpad-lifecycle.ts +14 -13
  52. package/src/prompt/surface-worker.ts +35 -9
  53. package/src/runtime/broker/crew-broker.ts +113 -111
  54. package/src/runtime/broker/delegate/delegate-abort.ts +118 -0
  55. package/src/runtime/broker/delegate/delegate-event.ts +3 -1
  56. package/src/runtime/broker/delegate/delegate-finalize.ts +179 -0
  57. package/src/runtime/broker/protocol/wait-resolve.ts +71 -5
  58. package/src/runtime/budget-enforcement.ts +26 -6
  59. package/src/runtime/chain-parser.ts +5 -3
  60. package/src/runtime/chain-runner.ts +41 -22
  61. package/src/runtime/child-pi/mock-fixtures.ts +12 -5
  62. package/src/runtime/compaction/tool-output-pruner.ts +8 -3
  63. package/src/runtime/delegate-spawn.ts +61 -8
  64. package/src/runtime/dispatch-batch.ts +10 -4
  65. package/src/runtime/effectiveness.ts +31 -3
  66. package/src/runtime/goal-workflow/plan-templates.ts +2 -2
  67. package/src/runtime/live-session/live-agent-control.ts +89 -6
  68. package/src/runtime/live-session/live-agent-manager.ts +94 -10
  69. package/src/runtime/live-session/live-session-runtime.ts +9 -2
  70. package/src/runtime/model/model-fallback.ts +6 -9
  71. package/src/runtime/model/pi-args.ts +3 -3
  72. package/src/runtime/model/runtime-policy.ts +4 -2
  73. package/src/runtime/model/runtime-resolver.ts +6 -2
  74. package/src/runtime/process/orphan-reaper.ts +143 -0
  75. package/src/runtime/process-status.ts +38 -16
  76. package/src/runtime/resilient-edit.ts +170 -93
  77. package/src/runtime/role-permission.ts +3 -1
  78. package/src/runtime/run-tracker.ts +9 -1
  79. package/src/runtime/sanitize/worker-text.ts +98 -0
  80. package/src/runtime/scheduling/run-coalesced-task-group.ts +82 -28
  81. package/src/runtime/spawn-policy.ts +190 -8
  82. package/src/runtime/stale-reconciler.ts +36 -1
  83. package/src/runtime/subagent-manager.ts +29 -0
  84. package/src/runtime/surface/herdr-provider.ts +31 -1
  85. package/src/runtime/task-output-context.ts +58 -11
  86. package/src/runtime/task-runner/post-execution.ts +150 -0
  87. package/src/runtime/task-runner/prompt-builder.ts +41 -8
  88. package/src/runtime/task-runner.ts +16 -3
  89. package/src/runtime/verification/classifier-pre-gate.ts +27 -6
  90. package/src/runtime/verification/verify-gate.ts +153 -30
  91. package/src/state/atomic-write.ts +73 -4
  92. package/src/state/contracts.ts +7 -0
  93. package/src/state/coordination/mailbox.ts +40 -11
  94. package/src/state/event-log/event-log-rotation.ts +28 -6
  95. package/src/state/event-log/poison-marker.ts +16 -1
  96. package/src/state/stores/artifact-store.ts +181 -6
  97. package/src/state/stores/manifest-io.ts +126 -8
  98. package/src/state/stores/state-store.ts +30 -31
  99. package/src/state/types.ts +13 -0
  100. package/src/state/usage.ts +41 -0
  101. package/src/ui/run-dashboard.ts +3 -3
  102. package/src/ui/settings-overlay.ts +19 -1
  103. package/src/utils/internal-error.ts +5 -1
  104. package/src/utils/timer-limits.ts +30 -0
  105. package/src/utils/token-counter.ts +47 -0
  106. package/src/workflows/discover-workflows.ts +9 -1
  107. package/src/worktree/worktree-manager.ts +128 -18
  108. package/workflows/default.workflow.md +1 -1
  109. package/workflows/fast-fix.workflow.md +1 -1
  110. package/workflows/plan-execute.workflow.md +1 -1
  111. package/workflows/review.workflow.md +1 -1
  112. package/workflows/strict-fast-fix.workflow.md +1 -1
@@ -1,4 +1,5 @@
1
1
  import type { PiTeamsConfig } from "../../config/config.ts";
2
+ import { getCrewEnv } from "../../config/env-vars.ts";
2
3
  import type { RuntimeResolutionState } from "../../state/types.ts";
3
4
  import type { CrewRuntimeKind } from "../crew-agent-runtime.ts";
4
5
  import { mockLiveSessionEnabled } from "./runtime-policy.ts";
@@ -90,7 +91,10 @@ export async function isLiveSessionRuntimeAvailable(
90
91
 
91
92
  export async function resolveCrewRuntime(config: PiTeamsConfig, env: NodeJS.ProcessEnv = process.env): Promise<CrewRuntimeCapabilities> {
92
93
  const requestedMode = config.runtime?.mode ?? "auto";
93
- const workersDisabled = config.executeWorkers === false || env.PI_CREW_EXECUTE_WORKERS === "0" || env.PI_TEAMS_EXECUTE_WORKERS === "0";
94
+ const workersDisabled =
95
+ config.executeWorkers === false ||
96
+ getCrewEnv("PI_CREW_EXECUTE_WORKERS", env) === "0" ||
97
+ getCrewEnv("PI_TEAMS_EXECUTE_WORKERS", env) === "0";
94
98
  if (requestedMode === "scaffold") return scaffoldCaps(requestedMode, undefined, "explicit_dry_run");
95
99
  if (workersDisabled)
96
100
  return scaffoldCaps(
@@ -100,7 +104,7 @@ export async function resolveCrewRuntime(config: PiTeamsConfig, env: NodeJS.Proc
100
104
  );
101
105
  if (requestedMode === "child-process") return childCaps(requestedMode);
102
106
  // When a child-process mock is active (tests), force auto-mode to child-process where the mock is active.
103
- if (requestedMode === "auto" && env.PI_TEAMS_MOCK_CHILD_PI)
107
+ if (requestedMode === "auto" && getCrewEnv("PI_TEAMS_MOCK_CHILD_PI", env))
104
108
  return childCaps(requestedMode, "PI_TEAMS_MOCK_CHILD_PI mock forces child-process runtime in auto mode.");
105
109
  if (requestedMode === "live-session") {
106
110
  const live = await isLiveSessionRuntimeAvailable(1500, env);
@@ -0,0 +1,143 @@
1
+ /**
2
+ * orphan-reaper.ts — R39-M3 (fix-wave 6, EP3): reclaim orphaned pi-crew worker
3
+ * processes.
4
+ *
5
+ * Root cause: when the host pi process is SIGKILLed mid-run, the spawned worker
6
+ * is re-parented to PID 1 and keeps running with NO automatic reaper. The stale
7
+ * reconciler repairs run *state* (cancels tasks) but never touches the recorded
8
+ * worker process, and `cleanupOrphanWorkers` (session-start only) only knows
9
+ * about *registered* workers — a reparented orphan is never in the registry.
10
+ *
11
+ * Safety model (mirrors zombie-scanner.ts): this module NEVER kills on a bare
12
+ * pid-liveness guess. A pid is reaped only when it is (a) recorded as the
13
+ * worker of a run whose reconcile verdict was already "stale", AND (b) confirmed
14
+ * by the AUTHORITATIVE zombie signal — `PI_CREW_KIND=subagent` with a DEAD
15
+ * `PI_CREW_PARENT_PID` (i.e. its host is gone). A worker whose parent is still
16
+ * alive is never a candidate, so a healthy in-flight worker cannot be killed by
17
+ * accident. All IO is injectable for unit testing (no real kills in tests).
18
+ */
19
+
20
+ import type { TeamTaskState } from "../../state/types.ts";
21
+ import { checkProcessLiveness } from "../process-status.ts";
22
+ import { scanZombieSubagents } from "./zombie-scanner.ts";
23
+
24
+ /** A recorded worker process for a run task (from heartbeat.pid / checkpoint.childPid). */
25
+ export interface WorkerPidEvidence {
26
+ taskId: string;
27
+ pid: number;
28
+ }
29
+
30
+ export interface ReapOrphanOptions {
31
+ /** Liveness probe (default: process.kill(pid, 0)). */
32
+ isAlive?: (pid: number) => boolean;
33
+ /** Signal sender (default: process.kill). Injected in tests. */
34
+ kill?: (pid: number, signal: NodeJS.Signals) => void;
35
+ /** Signal to send first (default SIGTERM — graceful). */
36
+ signal?: NodeJS.Signals;
37
+ /** Pids that must never be touched (self/ancestors). */
38
+ protectedPids?: ReadonlySet<number>;
39
+ /** When set, ONLY reap these pids (the authoritative orphan-zombie set). */
40
+ allowedPids?: ReadonlySet<number>;
41
+ /** Report candidates without killing (used by doctor/dry-run). */
42
+ dryRun?: boolean;
43
+ }
44
+
45
+ export interface ReapOrphanResult {
46
+ reaped: number[];
47
+ skipped: { pid: number; reason: string }[];
48
+ /** Every distinct pid considered. */
49
+ candidates: number[];
50
+ }
51
+
52
+ /**
53
+ * Collect the recorded worker pids of a run's in-flight tasks. A `running` or
54
+ * `waiting` task that recorded its child pid (heartbeat or checkpoint) is the
55
+ * evidence we reap against. Deduped by pid.
56
+ */
57
+ export function collectWorkerPidEvidence(tasks: TeamTaskState[]): WorkerPidEvidence[] {
58
+ const seen = new Set<number>();
59
+ const evidence: WorkerPidEvidence[] = [];
60
+ for (const task of tasks) {
61
+ if (task.status !== "running" && task.status !== "waiting") continue;
62
+ const pid = task.heartbeat?.pid ?? task.checkpoint?.childPid;
63
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 1) continue;
64
+ if (seen.has(pid)) continue;
65
+ seen.add(pid);
66
+ evidence.push({ taskId: task.id, pid });
67
+ }
68
+ return evidence;
69
+ }
70
+
71
+ /**
72
+ * Reap orphaned worker processes. Conservative by construction:
73
+ * * invalid / pid<=1 → skipped,
74
+ * * protected (self/ancestors) → skipped,
75
+ * * not alive → skipped (nothing to reap),
76
+ * * `allowedPids` set → any pid outside it is skipped (authoritative gate),
77
+ * * otherwise SIGTERM.
78
+ */
79
+ export function reapOrphanWorkers(evidences: WorkerPidEvidence[], opts: ReapOrphanOptions = {}): ReapOrphanResult {
80
+ const isAlive = opts.isAlive ?? ((pid: number) => checkProcessLiveness(pid).alive);
81
+ const kill = opts.kill ?? ((pid: number, signal: NodeJS.Signals) => process.kill(pid, signal));
82
+ const protectedPids = opts.protectedPids ?? new Set<number>([process.pid, process.ppid]);
83
+ const signal = opts.signal ?? "SIGTERM";
84
+ const reaped: number[] = [];
85
+ const skipped: { pid: number; reason: string }[] = [];
86
+ const candidates: number[] = [];
87
+ const seen = new Set<number>();
88
+
89
+ for (const { pid } of evidences) {
90
+ if (seen.has(pid)) continue;
91
+ seen.add(pid);
92
+ candidates.push(pid);
93
+ if (!Number.isInteger(pid) || pid <= 1) {
94
+ skipped.push({ pid, reason: "invalid-or-init-pid" });
95
+ continue;
96
+ }
97
+ if (protectedPids.has(pid)) {
98
+ skipped.push({ pid, reason: "protected-self-or-ancestor" });
99
+ continue;
100
+ }
101
+ if (opts.allowedPids && !opts.allowedPids.has(pid)) {
102
+ skipped.push({ pid, reason: "not-an-authoritative-orphan" });
103
+ continue;
104
+ }
105
+ if (!isAlive(pid)) {
106
+ skipped.push({ pid, reason: "already-dead" });
107
+ continue;
108
+ }
109
+ if (opts.dryRun) {
110
+ skipped.push({ pid, reason: "dry-run" });
111
+ continue;
112
+ }
113
+ try {
114
+ kill(pid, signal);
115
+ reaped.push(pid);
116
+ } catch (error) {
117
+ skipped.push({ pid, reason: error instanceof Error ? error.message : String(error) });
118
+ }
119
+ }
120
+ return { reaped, skipped, candidates };
121
+ }
122
+
123
+ /**
124
+ * R39-M3: reap the recorded worker processes of a stale run, gated on the
125
+ * AUTHORITATIVE orphan signal. `scanZombieSubagents()` classifies a process as a
126
+ * zombie only when it carries `PI_CREW_KIND=subagent` AND its recorded
127
+ * `PI_CREW_PARENT_PID` is dead — i.e. the host is gone and the worker was
128
+ * re-parented (PID 1). Intersecting that set with the run's recorded task pids
129
+ * yields exactly the unreapable orphans, with no false-positive kill risk for a
130
+ * live worker. Linux-only (the scanner needs /proc); on other platforms the
131
+ * scan yields no zombies and this is a no-op. Best-effort: never throws.
132
+ */
133
+ export function reapRecordedWorkerOrphans(tasks: TeamTaskState[], opts: ReapOrphanOptions = {}): ReapOrphanResult {
134
+ const evidence = collectWorkerPidEvidence(tasks);
135
+ if (evidence.length === 0) return { reaped: [], skipped: [], candidates: [] };
136
+ let zombiePids: Set<number>;
137
+ try {
138
+ zombiePids = new Set(scanZombieSubagents().zombies.map((zombie) => zombie.pid));
139
+ } catch {
140
+ return { reaped: [], skipped: evidence.map((item) => ({ pid: item.pid, reason: "zombie-scan-unavailable" })), candidates: [] };
141
+ }
142
+ return reapOrphanWorkers(evidence, { ...opts, allowedPids: zombiePids });
143
+ }
@@ -62,11 +62,35 @@ export function isFinishedRunStatus(status: string): boolean {
62
62
  }
63
63
 
64
64
  /**
65
- * Secondary threshold: runs that have been "running" for more than this without
66
- * any active agents (all queued, no progress) are also considered orphaned.
67
- * This catches foreground team runs where the planner got stuck with 0 tool calls.
65
+ * R48-N2 (2026-10-19): window (ms) within which an agent's last recorded
66
+ * activity timestamp still proves its host process is alive. Mirrors the
67
+ * health-monitor's STUCK_TASK_THRESHOLD_MS (5 min).
68
68
  */
69
- const ORPHANED_NO_PROGRESS_MS = 5 * 60 * 1000;
69
+ const AGENT_ACTIVITY_LIVENESS_MS = 5 * 60 * 1000;
70
+
71
+ /** Agent statuses that are terminal — never count as liveness evidence. */
72
+ const TERMINAL_AGENT_STATUSES = new Set<CrewAgentRecord["status"]>(["completed", "failed", "cancelled", "stopped"]);
73
+
74
+ /** Latest recorded agent activity timestamp (ms epoch), or NaN when none. */
75
+ function agentLatestActivityAt(agent: CrewAgentRecord): number {
76
+ const raw = agent.progress?.lastActivityAt;
77
+ if (!raw) return Number.NaN;
78
+ const parsed = new Date(raw).getTime();
79
+ return Number.isFinite(parsed) ? parsed : Number.NaN;
80
+ }
81
+
82
+ /**
83
+ * R48-N2: does this agent provide RECENT durable activity evidence that its
84
+ * host process is still alive? A frozen `running` agent that never wrote
85
+ * progress (the zombie-sync blind spot) returns false. Terminal agents are
86
+ * never evidence. Deliberately NOT based on `run.summary` — the legacy
87
+ * magic-summary gate is gone.
88
+ */
89
+ export function hasRecentAgentActivityEvidence(agent: CrewAgentRecord, now = Date.now(), livenessMs = AGENT_ACTIVITY_LIVENESS_MS): boolean {
90
+ if (TERMINAL_AGENT_STATUSES.has(agent.status)) return false;
91
+ const at = agentLatestActivityAt(agent);
92
+ return Number.isFinite(at) && now - at < livenessMs;
93
+ }
70
94
 
71
95
  export function isLikelyOrphanedActiveRun(
72
96
  run: TeamRunManifest,
@@ -79,19 +103,17 @@ export function isLikelyOrphanedActiveRun(
79
103
  const updatedAt = new Date(run.updatedAt).getTime();
80
104
  if (!Number.isFinite(updatedAt)) return false;
81
105
 
82
- // Primary check: run hasn't been updated in a while
106
+ // R48-N2: structural orphan test. A run whose manifest has not been updated
107
+ // within `staleMs` is orphaned UNLESS some agent still reports recent durable
108
+ // activity evidence — which proves the executing host is alive. This replaces
109
+ // the legacy magic-string summary gate plus the all-queued-only check, both of
110
+ // which were structurally blind:
111
+ // * a FROZEN `running` agent (never queued) defeated both branches, and
112
+ // * any 0-agent stale run whose summary happened not to match was ignored.
113
+ // The `summary` field is now irrelevant — the decision is purely structural.
83
114
  if (now - updatedAt >= staleMs) {
84
- if (agents.length === 0) return run.summary === "Creating workflow prompts and placeholder results.";
85
- return agents.every((agent) => agent.status === "queued" && !agent.completedAt && !agent.progress);
86
- }
87
-
88
- // Secondary check: run has been running without any progress for too long
89
- if (now - updatedAt >= ORPHANED_NO_PROGRESS_MS) {
90
- // If no agent is "running" or has made progress, the run is likely stuck
91
- const hasActiveAgent = agents.some((agent) => agent.status === "running" || agent.progress || agent.toolUses);
92
- if (!hasActiveAgent && agents.length > 0) {
93
- return true;
94
- }
115
+ const livenessMs = Math.max(staleMs, AGENT_ACTIVITY_LIVENESS_MS);
116
+ return !agents.some((agent) => hasRecentAgentActivityEvidence(agent, now, livenessMs));
95
117
  }
96
118
 
97
119
  return false;
@@ -1,21 +1,33 @@
1
1
  /**
2
2
  * Resilient edit wrapper — uses the cascading replace() engine as a fallback
3
- * when the native edit tool fails with "old_string not found".
3
+ * when the native edit tool fails to find `oldText`.
4
4
  *
5
5
  * Multi-agent runs (crew workers) often provide slightly-wrong oldText:
6
6
  * - indentation drift (tabs vs spaces)
7
7
  * - trailing whitespace differences
8
8
  * - line-ending normalization (\r\n vs \n)
9
9
  *
10
- * The native edit tool is exact-match only and fails hard on these. This
11
- * wrapper catches that failure and retries with the cascading engine, which
10
+ * The native edit tool matches (near-)exactly and fails hard on these. This
11
+ * module hooks the tool result and retries with the cascading engine, which
12
12
  * tries (in order): exact → escape-normalized → line-trimmed → block-anchor →
13
13
  * whitespace-normalized → trimmed-boundary.
14
14
  *
15
+ * R49-F1 (wave-6 M3-15) — REAL API ONLY. The previous implementation read
16
+ * `pi.tools.edit` / `pi.extensions` / `pi._extensions`, none of which exist on
17
+ * the 1.0.4 extension API (the loader-created api object has no such keys), so
18
+ * `wrapEditWithResilientReplace()` always returned false in production and the
19
+ * whole feature was dead code (the call site in register.ts ignores the
20
+ * return value). `pi.getAllTools()` cannot replace it either: it returns
21
+ * metadata-only `ToolInfo` (Pick<ToolDefinition, name|description|parameters|
22
+ * promptGuidelines>) with NO `execute`, so there is nothing to monkey-patch.
23
+ * The supported seam is the `tool_result` hook: a handler may return
24
+ * `{ content, isError }` to replace the failed result — the resilient retry
25
+ * performs the file write itself, so a success result can be substituted.
26
+ *
15
27
  * CONFLICT AWARENESS: pi-diff (`@heyhuynhgiabuu/pi-diff`) also overrides the
16
- * edit tool with its own replace() integration. To avoid double-wrapping,
17
- * this module is OPT-IN via the `CREW_RESILIENT_EDIT=1` env var, and
18
- * auto-disables if pi-diff is detected in the loaded extensions.
28
+ * edit tool with its own replace() integration. To avoid double-wrapping, this
29
+ * module is OPT-IN via the `CREW_RESILIENT_EDIT=1` env var, and auto-disables
30
+ * when pi-diff is detected in the session's tool listing (getAllTools).
19
31
  *
20
32
  * Usage (in register.ts, guarded):
21
33
  * if (process.env.CREW_RESILIENT_EDIT === "1") {
@@ -25,16 +37,19 @@
25
37
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
26
38
  import { type ReplaceResult, replace } from "../runtime/replace.ts";
27
39
 
28
- interface EditToolLike {
29
- name: string;
30
- description: string;
31
- parameters: unknown;
32
- execute: (toolCallId: string, params: unknown, signal: unknown, onUpdate: unknown) => Promise<unknown>;
40
+ /** One replacement as the 1.0.4 edit tool models it (`{ path, edits: [...] }`). */
41
+ interface EditEntry {
42
+ oldText: string;
43
+ newText: string;
44
+ replaceAll?: boolean;
33
45
  }
34
46
 
35
- interface EditParams {
47
+ /** Flat edit arguments (1.0.4 single-edit form and pre-1.0 legacy names). */
48
+ interface LegacyEditParams {
36
49
  path?: string;
37
50
  filePath?: string;
51
+ oldText?: string;
52
+ newText?: string;
38
53
  oldString?: string;
39
54
  old_string?: string;
40
55
  newString?: string;
@@ -43,111 +58,173 @@ interface EditParams {
43
58
  replace_all?: boolean;
44
59
  }
45
60
 
46
- interface EditResult {
47
- content?: unknown[];
48
- [key: string]: unknown;
61
+ interface ToolResultEventLike {
62
+ toolName?: unknown;
63
+ input?: unknown;
64
+ content?: unknown;
65
+ isError?: unknown;
66
+ }
67
+
68
+ interface ToolResultEventResultLike {
69
+ content: Array<{ type: "text"; text: string }>;
70
+ isError: boolean;
71
+ }
72
+
73
+ interface ToolInfoLike {
74
+ name?: unknown;
75
+ namespace?: { name?: unknown } | unknown;
76
+ sourceInfo?: { path?: unknown; source?: unknown } | unknown;
49
77
  }
50
78
 
51
79
  const NOT_FOUND_PATTERNS = [/old_string not found/i, /oldstring not found/i, /no match/i, /could not find/i, /string not found/i];
52
80
 
53
- function isNotFoundResult(result: unknown): boolean {
54
- if (!result || typeof result !== "object") return false;
55
- const r = result as EditResult;
56
- const text = JSON.stringify(r.content ?? r);
81
+ function isNotFoundResult(content: unknown): boolean {
82
+ const text = JSON.stringify(content ?? "");
57
83
  return NOT_FOUND_PATTERNS.some((re) => re.test(text));
58
84
  }
59
85
 
60
- /** Detect whether pi-diff is loaded (to avoid double-wrapping edit). */
86
+ function stringField(value: unknown, key: string): string | undefined {
87
+ if (!value || typeof value !== "object") return undefined;
88
+ const field = (value as Record<string, unknown>)[key];
89
+ return typeof field === "string" ? field : undefined;
90
+ }
91
+
92
+ /**
93
+ * Detect whether pi-diff is loaded (to avoid double-wrapping edit).
94
+ *
95
+ * R49-F1: reads the REAL `getAllTools()` listing (the phantom
96
+ * `pi.extensions` / `pi._extensions` are simply not on the api). A tool's
97
+ * owning extension shows up in `namespace.name` (e.g. `mcp__docs`) and
98
+ * `sourceInfo.path`/`sourceInfo.source`.
99
+ */
61
100
  function isPiDiffLoaded(pi: ExtensionAPI): boolean {
62
101
  try {
63
- const piExt = pi as unknown as { extensions?: unknown[] | Record<string, unknown>; _extensions?: unknown[] };
64
- const extensions = piExt?.extensions ?? piExt?._extensions ?? [];
65
- const names = Array.isArray(extensions)
66
- ? extensions.map((e: unknown) => (typeof e === "string" ? e : ((e as { name?: string })?.name ?? "")))
67
- : Object.keys(extensions as Record<string, unknown>);
68
- return names.some((n: string) => typeof n === "string" && n.includes("pi-diff"));
102
+ const getAllTools = (pi as unknown as { getAllTools?: () => unknown }).getAllTools;
103
+ if (typeof getAllTools !== "function") return false;
104
+ const tools = getAllTools.call(pi);
105
+ if (!Array.isArray(tools)) return false;
106
+ return (tools as ToolInfoLike[]).some((tool) => {
107
+ if (!tool || typeof tool !== "object") return false;
108
+ const namespaceName = tool.namespace && typeof tool.namespace === "object" ? stringField(tool.namespace, "name") : undefined;
109
+ const sourcePath = tool.sourceInfo && typeof tool.sourceInfo === "object" ? stringField(tool.sourceInfo, "path") : undefined;
110
+ const sourceName = tool.sourceInfo && typeof tool.sourceInfo === "object" ? stringField(tool.sourceInfo, "source") : undefined;
111
+ return [namespaceName, sourcePath, sourceName].some((value) => typeof value === "string" && value.includes("pi-diff"));
112
+ });
69
113
  } catch {
70
114
  return false;
71
115
  }
72
116
  }
73
117
 
74
118
  /**
75
- * Wrap the native `edit` tool so that on "old_string not found" failures, it
76
- * retries using the cascading replace() engine (lenient matching).
119
+ * Normalize the edit tool input into one or more replacements.
77
120
  *
78
- * @param pi the Pi extension API
79
- * @param tools optional injected tool registry (for testing)
80
- * @returns true if the wrapper was applied, false if skipped
121
+ * 1.0.4 shape is `{ path, edits: [{ oldText, newText }] }`; older hosts (and
122
+ * the module's own history) used `{ path|filePath, oldString|old_string,
123
+ * newString|new_string, replaceAll }`. Both are accepted so the hook keeps
124
+ * working across hosts.
81
125
  */
82
- export function wrapEditWithResilientReplace(pi: ExtensionAPI, tools?: { edit: EditToolLike }): boolean {
83
- // Auto-disable if pi-diff is present (it has its own replace integration).
84
- if (isPiDiffLoaded(pi)) {
85
- return false;
126
+ function toEditEntries(input: unknown): { filePath: string; entries: EditEntry[] } | undefined {
127
+ if (!input || typeof input !== "object") return undefined;
128
+ const params = input as Record<string, unknown>;
129
+ const filePath = stringField(params, "path") ?? stringField(params, "filePath");
130
+ if (!filePath) return undefined;
131
+
132
+ const rawEdits = params.edits;
133
+ if (Array.isArray(rawEdits)) {
134
+ const entries: EditEntry[] = [];
135
+ for (const raw of rawEdits) {
136
+ const oldText = stringField(raw, "oldText") ?? stringField(raw, "old_string") ?? stringField(raw, "oldString");
137
+ const newText = stringField(raw, "newText") ?? stringField(raw, "new_string") ?? stringField(raw, "newString");
138
+ if (oldText === undefined || newText === undefined) return undefined;
139
+ const flag = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
140
+ entries.push({ oldText, newText, replaceAll: flag.replaceAll === true || flag.replace_all === true });
141
+ }
142
+ return entries.length > 0 ? { filePath, entries } : undefined;
86
143
  }
87
144
 
88
- const t = tools ?? (pi as unknown as { tools?: { edit?: EditToolLike } }).tools;
89
- if (!t?.edit?.execute) return false;
145
+ const legacy = params as LegacyEditParams;
146
+ const oldText = legacy.oldText ?? legacy.oldString ?? legacy.old_string;
147
+ const newText = legacy.newText ?? legacy.newString ?? legacy.new_string;
148
+ if (oldText === undefined || newText === undefined) return undefined;
149
+ return { filePath, entries: [{ oldText, newText, replaceAll: legacy.replaceAll ?? legacy.replace_all ?? false }] };
150
+ }
90
151
 
91
- const nativeExecute = t.edit.execute.bind(t.edit);
152
+ /**
153
+ * Apply the resilient cascade to the edit retry. All-or-nothing: the file is
154
+ * written ONLY when every requested replacement matched, so a partially
155
+ * fuzz-matched multi-edit can never leave the file half-edited (the native
156
+ * tool has the same guarantee, and a hook that wrote partially would be worse
157
+ * than the failure it replaces).
158
+ *
159
+ * @returns the replacement result, or undefined when nothing could be applied
160
+ */
161
+ async function retryWithReplace(input: unknown): Promise<ToolResultEventResultLike | undefined> {
162
+ const target = toEditEntries(input);
163
+ if (!target) return undefined;
164
+ const { filePath, entries } = target;
165
+
166
+ // LAZY: defer dynamic import of node:fs/promises to its call site.
167
+ const fs = await import("node:fs/promises");
168
+ let original: string;
169
+ try {
170
+ original = await fs.readFile(filePath, "utf8");
171
+ } catch {
172
+ return undefined; // unreadable file — leave the original tool failure in place
173
+ }
92
174
 
93
- t.edit.execute = async function resilientExecute(
94
- toolCallId: string,
95
- params: unknown,
96
- signal: unknown,
97
- onUpdate: unknown,
98
- ): Promise<unknown> {
99
- try {
100
- const result = await nativeExecute(toolCallId, params, signal, onUpdate);
101
- if (!isNotFoundResult(result)) return result;
102
- // Fall through to resilient retry.
103
- return await retryWithReplace(params as EditParams, toolCallId, signal, onUpdate);
104
- } catch (err) {
105
- const msg = err instanceof Error ? err.message : String(err);
106
- if (NOT_FOUND_PATTERNS.some((re) => re.test(msg))) {
107
- return await retryWithReplace(params as EditParams, toolCallId, signal, onUpdate);
108
- }
109
- throw err;
110
- }
175
+ const strategies: string[] = [];
176
+ let content = original;
177
+ for (const entry of entries) {
178
+ const result: ReplaceResult = replace(content, entry.oldText, entry.newText, {
179
+ replaceAll: entry.replaceAll ?? false,
180
+ });
181
+ if (!result.changed) return undefined; // any unmatched edit → no write at all
182
+ content = result.content;
183
+ strategies.push(result.strategy);
184
+ }
185
+ if (content === original) return undefined;
186
+
187
+ await fs.writeFile(filePath, content, "utf8");
188
+ return {
189
+ content: [
190
+ {
191
+ type: "text",
192
+ text: `Edited ${filePath} via resilient cascade (strategy: ${strategies.join(", ")}).`,
193
+ },
194
+ ],
195
+ isError: false,
111
196
  };
197
+ }
112
198
 
113
- return true;
114
-
115
- async function retryWithReplace(params: EditParams, toolCallId: string, signal: unknown, onUpdate: unknown): Promise<unknown> {
116
- const filePath = params.path ?? params.filePath;
117
- const oldStr = params.oldString ?? params.old_string;
118
- const newStr = params.newString ?? params.new_string;
119
- const replaceAll = params.replaceAll ?? params.replace_all ?? false;
120
-
121
- if (!filePath || typeof oldStr !== "string" || typeof newStr !== "string") {
122
- // Can't retry — rethrow a not-found style error.
123
- throw new Error("old_string not found (and resilient retry skipped: missing path/old/new)");
124
- }
125
-
126
- // LAZY: defer dynamic import of node:fs/promises to its call site.
127
- const fs = await import("node:fs/promises");
128
- let content: string;
199
+ /**
200
+ * Hook the native `edit` tool result so that "old text not found" failures are
201
+ * retried with the cascading replace() engine (lenient matching).
202
+ *
203
+ * @param pi the Pi extension API
204
+ * @returns true if the hook was registered, false if skipped
205
+ */
206
+ export function wrapEditWithResilientReplace(pi: ExtensionAPI): boolean {
207
+ // Auto-disable if pi-diff is present (it has its own replace integration).
208
+ if (isPiDiffLoaded(pi)) return false;
209
+
210
+ const on = (pi as unknown as { on?: (event: string, handler: unknown) => unknown }).on;
211
+ if (typeof on !== "function") return false;
212
+
213
+ on.call(pi, "tool_result", async (event: ToolResultEventLike) => {
214
+ if (event?.toolName !== "edit") return undefined;
215
+ // Only the not-found family is retryable: a duplicate / overlap /
216
+ // invalid-input failure keeps its original error (the cascade cannot fix
217
+ // those and a fuzzy retry would be unsafe). The check covers both a
218
+ // thrown tool error surfaced as isError:true and a not-found result.
219
+ if (!isNotFoundResult(event.content)) return undefined;
129
220
  try {
130
- content = await fs.readFile(filePath, "utf8");
131
- } catch (readErr) {
132
- throw new Error(`resilient edit: could not read ${filePath}: ${readErr instanceof Error ? readErr.message : String(readErr)}`);
221
+ return await retryWithReplace(event.input);
222
+ } catch {
223
+ // A retry failure must never turn a clean tool error into a thrown
224
+ // extension error — fall back to the native result.
225
+ return undefined;
133
226
  }
227
+ });
134
228
 
135
- const result: ReplaceResult = replace(content, oldStr, newStr, {
136
- replaceAll,
137
- });
138
- if (!result.changed) {
139
- throw new Error(`old_string not found (resilient cascade exhausted, strategy=${result.strategy})`);
140
- }
141
-
142
- await fs.writeFile(filePath, result.content, "utf8");
143
- return {
144
- content: [
145
- {
146
- type: "text",
147
- text: `Edited ${filePath} via resilient cascade (strategy: ${result.strategy}).`,
148
- },
149
- ],
150
- _replaceStrategy: result.strategy,
151
- };
152
- }
229
+ return true;
153
230
  }
@@ -1,3 +1,5 @@
1
+ import { getCrewEnv } from "../config/env-vars.ts";
2
+
1
3
  export type RolePermissionMode = "read_only" | "workspace_write" | "danger_full_access" | "explicit_confirm";
2
4
 
3
5
  // (FIND-12 R1 review: the AgentPermissionOptions opt-in was dropped — no caller
@@ -43,7 +45,7 @@ export function permissionForRole(role: string): RolePermissionMode {
43
45
  }
44
46
 
45
47
  export function currentCrewRole(env: NodeJS.ProcessEnv = process.env): string | undefined {
46
- return env.PI_CREW_ROLE?.trim() || env.PI_TEAMS_ROLE?.trim() || undefined;
48
+ return getCrewEnv("PI_CREW_ROLE", env)?.trim() || getCrewEnv("PI_TEAMS_ROLE", env)?.trim() || undefined;
47
49
  }
48
50
 
49
51
  export function checkSubagentSpawnPermission(role: string | undefined): PermissionCheckResult {
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import { createRunPaths, loadRunManifestById } from "../state/stores/state-store.ts";
3
3
  import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
4
+ import { clampTimerDelayMs } from "../utils/timer-limits.ts";
4
5
  import { isFinishedRunStatus } from "./process-status.ts";
5
6
 
6
7
  export interface RunWaitResult {
@@ -178,7 +179,14 @@ export async function waitForRun(
178
179
  cwd: string,
179
180
  options: { timeoutMs?: number; pollIntervalMs?: number } = {},
180
181
  ): Promise<RunWaitResult> {
181
- const { timeoutMs = 300_000, pollIntervalMs = 500 } = options;
182
+ const defaultedTimeoutMs = options.timeoutMs ?? 300_000;
183
+ // R37-F1: the caller's timeout comes from `resolveRunDeadline().deadlineMs`
184
+ // (extension/team-tool/run.ts) and from the `wait` action. A value above
185
+ // 2^31-1 overflows `setTimeout` in raceRunPromise → fires in ~1 ms → the
186
+ // waiter rejects instantly ("waitForRun timed out after 2.5e9ms"). Clamp at
187
+ // THIS boundary too (defense in depth — the caller may pass anything).
188
+ const timeoutMs = clampTimerDelayMs(defaultedTimeoutMs) ?? 300_000;
189
+ const { pollIntervalMs = 500 } = options;
182
190
  const deadline = Date.now() + timeoutMs;
183
191
 
184
192
  // A detach requested before this waiter existed applies to it (and is