pi-subagents 0.35.1 → 0.37.0

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 (89) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +224 -31
  3. package/agents/advisor.md +73 -0
  4. package/agents/delegate.md +2 -0
  5. package/agents/worker.md +2 -0
  6. package/package.json +11 -13
  7. package/skills/pi-subagents/SKILL.md +42 -13
  8. package/src/agents/agent-management.ts +7 -1
  9. package/src/agents/agents.ts +121 -17
  10. package/src/api/capability-ceiling.ts +17 -0
  11. package/src/api/delegation.ts +127 -0
  12. package/src/api/preflight.ts +399 -0
  13. package/src/extension/config.ts +7 -1
  14. package/src/extension/index.ts +52 -38
  15. package/src/extension/rpc.ts +31 -2
  16. package/src/extension/schemas.ts +29 -3
  17. package/src/extension/tool-description.ts +4 -2
  18. package/src/intercom/intercom-bridge.ts +1 -1
  19. package/src/intercom/native-supervisor-channel.ts +45 -6
  20. package/src/intercom/result-intercom.ts +7 -0
  21. package/src/runs/background/async-execution.ts +158 -17
  22. package/src/runs/background/async-job-tracker.ts +4 -0
  23. package/src/runs/background/async-resume.ts +47 -8
  24. package/src/runs/background/async-status.ts +94 -3
  25. package/src/runs/background/chain-append.ts +2 -0
  26. package/src/runs/background/completion-batcher.ts +6 -4
  27. package/src/runs/background/completion-dedupe.ts +2 -11
  28. package/src/runs/background/fleet-view.ts +9 -4
  29. package/src/runs/background/notify.ts +132 -120
  30. package/src/runs/background/process-terminal.ts +280 -0
  31. package/src/runs/background/result-watcher.ts +138 -78
  32. package/src/runs/background/run-status.ts +10 -2
  33. package/src/runs/background/scheduled-runs.ts +6 -1
  34. package/src/runs/background/stale-run-reconciler.ts +6 -0
  35. package/src/runs/background/subagent-runner.ts +406 -54
  36. package/src/runs/background/subagent-wait.ts +130 -4
  37. package/src/runs/background/wait-tool.ts +2 -2
  38. package/src/runs/foreground/chain-execution.ts +181 -111
  39. package/src/runs/foreground/execution.ts +147 -47
  40. package/src/runs/foreground/foreground-control.ts +90 -0
  41. package/src/runs/foreground/subagent-executor.ts +426 -165
  42. package/src/runs/shared/acceptance.ts +94 -41
  43. package/src/runs/shared/agent-contract.ts +38 -0
  44. package/src/runs/shared/capability-ceiling.ts +177 -0
  45. package/src/runs/shared/child-protocol.ts +1 -1
  46. package/src/runs/shared/completion-guard.ts +36 -5
  47. package/src/runs/shared/context-mode.ts +44 -0
  48. package/src/runs/shared/dynamic-fanout.ts +5 -5
  49. package/src/runs/shared/long-running-guard.ts +4 -0
  50. package/src/runs/shared/mcp-direct-tool-allowlist.ts +12 -6
  51. package/src/runs/shared/nested-events.ts +35 -3
  52. package/src/runs/shared/parallel-handoff.ts +154 -0
  53. package/src/runs/shared/parallel-utils.ts +11 -0
  54. package/src/runs/shared/pi-args.ts +148 -56
  55. package/src/runs/shared/run-history.ts +90 -5
  56. package/src/runs/shared/session-lease.ts +25 -5
  57. package/src/runs/shared/structured-output.ts +112 -7
  58. package/src/runs/shared/subagent-control.ts +4 -0
  59. package/src/runs/shared/subagent-prompt-runtime.ts +31 -19
  60. package/src/runs/shared/task-intent.ts +10 -5
  61. package/src/runs/shared/tool-availability.ts +21 -3
  62. package/src/runs/shared/tool-budget.ts +11 -5
  63. package/src/runs/shared/turn-budget.ts +2 -1
  64. package/src/runs/shared/worktree.ts +63 -14
  65. package/src/shared/accessible-dir.ts +25 -0
  66. package/src/shared/artifacts.ts +37 -7
  67. package/src/shared/atomic-json.ts +14 -42
  68. package/src/shared/child-transcript.ts +52 -0
  69. package/src/shared/file-system-retry.ts +47 -0
  70. package/src/shared/launch-contract.ts +123 -0
  71. package/src/shared/settings.ts +9 -1
  72. package/src/shared/types.ts +314 -28
  73. package/src/shared/utils.ts +17 -42
  74. package/src/slash/delegation-adapters.ts +153 -6
  75. package/src/slash/delegation-json.ts +108 -0
  76. package/src/slash/delegation-request.ts +182 -36
  77. package/src/slash/prompt-template-bridge.ts +222 -37
  78. package/src/slash/selector.ts +147 -0
  79. package/src/slash/slash-commands.ts +15 -6
  80. package/src/slash/slash-live-state.ts +2 -2
  81. package/src/slash/subagents-admin.ts +42 -42
  82. package/src/tui/fleet-status.ts +362 -0
  83. package/src/tui/fleet-transcript.ts +472 -0
  84. package/src/tui/fleet.ts +318 -59
  85. package/src/tui/render.ts +17 -15
  86. package/src/watchdog/change-signature.ts +105 -12
  87. package/src/watchdog/review.ts +7 -2
  88. package/src/watchdog/runtime.ts +5 -3
  89. package/src/slash/subagents-editor.ts +0 -86
@@ -3,6 +3,30 @@ import * as path from "node:path";
3
3
  import type { Message } from "@earendil-works/pi-ai";
4
4
  import { extractTextFromContent, extractToolArgsPreview } from "./utils.ts";
5
5
 
6
+ const MAX_TOOL_PAYLOAD_BYTES = 32 * 1024;
7
+ const TOOL_PAYLOAD_TRUNCATION_MARKER = "\n\n… payload truncated";
8
+
9
+ function boundedPayload(value: unknown, maxBytes = MAX_TOOL_PAYLOAD_BYTES): string | undefined {
10
+ let text: string;
11
+ if (typeof value === "string") text = value;
12
+ else {
13
+ try {
14
+ const serialized = JSON.stringify(value, null, 2);
15
+ if (serialized === undefined) return undefined;
16
+ text = serialized;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ if (!text.trim()) return undefined;
22
+ const payload = Buffer.from(text, "utf-8");
23
+ if (payload.length <= maxBytes) return text;
24
+ const markerBytes = Buffer.byteLength(TOOL_PAYLOAD_TRUNCATION_MARKER, "utf-8");
25
+ let end = Math.max(0, maxBytes - markerBytes);
26
+ while (end > 0 && (payload[end]! & 0xc0) === 0x80) end--;
27
+ return `${payload.subarray(0, end).toString("utf-8")}${TOOL_PAYLOAD_TRUNCATION_MARKER}`;
28
+ }
29
+
6
30
  export const CHILD_TRANSCRIPT_ARTIFACT_VERSION = 1;
7
31
  const DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES = 50 * 1024 * 1024;
8
32
 
@@ -19,8 +43,10 @@ type ChildTranscriptMessage = Message & {
19
43
  interface ChildTranscriptEvent {
20
44
  type?: string;
21
45
  message?: ChildTranscriptMessage;
46
+ toolCallId?: string;
22
47
  toolName?: string;
23
48
  args?: unknown;
49
+ isError?: boolean;
24
50
  }
25
51
 
26
52
  interface ChildTranscriptWriterInput {
@@ -147,6 +173,27 @@ export function createChildTranscriptWriter(input: ChildTranscriptWriterInput):
147
173
 
148
174
  const writeMessage = (sourceEventType: string, message: ChildTranscriptMessage) => {
149
175
  const text = extractTextFromContent(message.content);
176
+ if (message.role === "toolResult") {
177
+ const output = boundedPayload(text);
178
+ writeRecord({
179
+ ...baseRecord("message"),
180
+ sourceEventType,
181
+ role: message.role,
182
+ toolCallId: message.toolCallId,
183
+ toolName: message.toolName,
184
+ isError: message.isError,
185
+ ...(output ? { text: output, outputTruncated: output.includes("… payload truncated") } : {}),
186
+ message: {
187
+ role: message.role,
188
+ toolCallId: message.toolCallId,
189
+ toolName: message.toolName,
190
+ isError: message.isError,
191
+ content: output ? [{ type: "text", text: output }] : [],
192
+ ...(message.timestamp !== undefined ? { timestamp: message.timestamp } : {}),
193
+ },
194
+ });
195
+ return;
196
+ }
150
197
  writeRecord({
151
198
  ...baseRecord("message"),
152
199
  sourceEventType,
@@ -178,11 +225,14 @@ export function createChildTranscriptWriter(input: ChildTranscriptWriterInput):
178
225
  }
179
226
  if (event.type === "tool_execution_start" && event.toolName) {
180
227
  const args = eventArgs(event);
228
+ const argsPayload = boundedPayload(args);
181
229
  writeRecord({
182
230
  ...baseRecord("tool_start"),
183
231
  sourceEventType: event.type,
232
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
184
233
  toolName: event.toolName,
185
234
  ...(Object.keys(args).length > 0 ? { argsPreview: extractToolArgsPreview(args) } : {}),
235
+ ...(argsPayload ? { argsPayload } : {}),
186
236
  });
187
237
  return;
188
238
  }
@@ -190,7 +240,9 @@ export function createChildTranscriptWriter(input: ChildTranscriptWriterInput):
190
240
  writeRecord({
191
241
  ...baseRecord("tool_end"),
192
242
  sourceEventType: event.type,
243
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
193
244
  ...(event.toolName ? { toolName: event.toolName } : {}),
245
+ ...(typeof event.isError === "boolean" ? { isError: event.isError } : {}),
194
246
  });
195
247
  }
196
248
  },
@@ -0,0 +1,47 @@
1
+ const WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
2
+ const WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : undefined;
3
+ const RETRYABLE_FILE_SYSTEM_ERROR_CODES = new Set(["EACCES", "EBUSY", "EPERM"]);
4
+
5
+ export const DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 500, 1000, 2000, 4000] as const;
6
+
7
+ export type FileSystemRetryOptions = {
8
+ retryDelaysMs?: readonly number[];
9
+ wait?: (delayMs: number) => void;
10
+ };
11
+
12
+ export function waitForFileSystemRetry(delayMs: number): void {
13
+ if (delayMs <= 0) return;
14
+ if (WAIT_VIEW) {
15
+ try {
16
+ // Callers are synchronous status/result writers; Atomics.wait gives
17
+ // Windows directory and rename locks time to clear without burning CPU.
18
+ Atomics.wait(WAIT_VIEW, 0, 0, delayMs);
19
+ return;
20
+ } catch {
21
+ // Fall through to the portable busy wait below.
22
+ }
23
+ }
24
+ const end = Date.now() + delayMs;
25
+ while (Date.now() < end) {
26
+ // Portable fallback for runtimes where Atomics.wait is unavailable.
27
+ }
28
+ }
29
+
30
+ export function isRetryableFileSystemError(error: unknown): boolean {
31
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
32
+ return typeof code === "string" && RETRYABLE_FILE_SYSTEM_ERROR_CODES.has(code);
33
+ }
34
+
35
+ export function runFileSystemOperationWithRetry<T>(operation: () => T, options: FileSystemRetryOptions = {}): T {
36
+ const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS;
37
+ const wait = options.wait ?? waitForFileSystemRetry;
38
+ for (let attempt = 0; ; attempt++) {
39
+ try {
40
+ return operation();
41
+ } catch (error) {
42
+ const delayMs = retryDelaysMs[attempt];
43
+ if (delayMs === undefined || !isRetryableFileSystemError(error)) throw error;
44
+ wait(delayMs);
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,123 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import type { AgentConfig } from "../agents/agents.ts";
4
+
5
+ export const AGENT_DEFINITION_PROJECTION_VERSION = 1 as const;
6
+ export const LAUNCH_BINDING_PROJECTION_VERSION = 1 as const;
7
+
8
+ function stableJson(value: unknown): string {
9
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
10
+ if (value && typeof value === "object") {
11
+ return `{${Object.entries(value as Record<string, unknown>)
12
+ .filter(([, entry]) => entry !== undefined)
13
+ .sort(([a], [b]) => a.localeCompare(b))
14
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
15
+ .join(",")}}`;
16
+ }
17
+ return JSON.stringify(value);
18
+ }
19
+
20
+ function sha256(value: unknown): string {
21
+ return createHash("sha256").update(stableJson(value)).digest("hex");
22
+ }
23
+
24
+ function fileDigest(filePath: string): string | undefined {
25
+ try {
26
+ return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
32
+ /** Public-safe, deterministic evidence for the parsed launch-affecting agent definition. */
33
+ export function projectAgentDefinition(agent: AgentConfig): Record<string, unknown> {
34
+ return {
35
+ version: AGENT_DEFINITION_PROJECTION_VERSION,
36
+ name: agent.name,
37
+ localName: agent.localName,
38
+ packageName: agent.packageName,
39
+ filePath: agent.filePath,
40
+ fileContentDigest: fileDigest(agent.filePath),
41
+ systemPrompt: agent.systemPrompt,
42
+ systemPromptMode: agent.systemPromptMode,
43
+ inheritProjectContext: agent.inheritProjectContext,
44
+ inheritSkills: agent.inheritSkills,
45
+ model: agent.model,
46
+ fallbackModels: agent.fallbackModels,
47
+ thinking: agent.thinking,
48
+ tools: agent.tools,
49
+ mcpDirectTools: agent.mcpDirectTools,
50
+ extensions: agent.extensions,
51
+ subagentOnlyExtensions: agent.subagentOnlyExtensions,
52
+ skills: agent.skills,
53
+ skillPath: agent.skillPath,
54
+ output: agent.output,
55
+ defaultReads: agent.defaultReads,
56
+ defaultProgress: agent.defaultProgress,
57
+ defaultContext: agent.defaultContext,
58
+ defaultAsync: agent.defaultAsync,
59
+ defaultTimeoutMs: agent.defaultTimeoutMs,
60
+ defaultTurnBudget: agent.defaultTurnBudget,
61
+ defaultAcceptance: agent.defaultAcceptance,
62
+ acceptanceRole: agent.acceptanceRole,
63
+ interactive: agent.interactive,
64
+ maxSubagentDepth: agent.maxSubagentDepth,
65
+ completionGuard: agent.completionGuard,
66
+ toolBudget: agent.toolBudget,
67
+ memory: agent.memory,
68
+ };
69
+ }
70
+
71
+ export function agentDefinitionDigest(agent: AgentConfig): string {
72
+ return sha256(projectAgentDefinition(agent));
73
+ }
74
+
75
+ export interface LaunchBindingInput {
76
+ definitionDigest: string;
77
+ /** Caller task; runtime acceptance/output task annotations are explicitly outside the preflight-known subset. */
78
+ task?: string;
79
+ model?: string;
80
+ modelCandidates?: string[];
81
+ thinking?: string;
82
+ systemPrompt?: string | null;
83
+ systemPromptMode?: AgentConfig["systemPromptMode"];
84
+ inheritProjectContext: boolean;
85
+ inheritSkills: boolean;
86
+ skills?: string[];
87
+ tools?: string[];
88
+ extensions?: string[];
89
+ subagentOnlyExtensions?: string[];
90
+ mcpDirectTools?: string[];
91
+ outputPath?: string;
92
+ outputMode?: string;
93
+ structuredOutputSchema?: unknown;
94
+ }
95
+
96
+ /** Canonical projection of the resolved inputs handed to the child. */
97
+ export function projectLaunchBinding(input: LaunchBindingInput): Record<string, unknown> {
98
+ return {
99
+ version: LAUNCH_BINDING_PROJECTION_VERSION,
100
+ definitionDigest: input.definitionDigest,
101
+ taskDigest: input.task === undefined ? undefined : sha256(input.task),
102
+ // The ordered candidate set already contains each attempted model; keeping only
103
+ // this set makes retries correlate to the same preflight binding.
104
+ modelCandidates: input.modelCandidates,
105
+ thinking: input.thinking,
106
+ systemPromptDigest: input.systemPrompt === undefined || input.systemPrompt === null ? undefined : sha256(input.systemPrompt),
107
+ systemPromptMode: input.systemPromptMode,
108
+ inheritProjectContext: input.inheritProjectContext,
109
+ inheritSkills: input.inheritSkills,
110
+ skills: input.skills,
111
+ tools: input.tools,
112
+ extensions: input.extensions,
113
+ subagentOnlyExtensions: input.subagentOnlyExtensions,
114
+ mcpDirectTools: input.mcpDirectTools,
115
+ outputPath: input.outputPath,
116
+ outputMode: input.outputMode,
117
+ structuredOutputSchema: input.structuredOutputSchema,
118
+ };
119
+ }
120
+
121
+ export function launchBindingDigest(input: LaunchBindingInput): string {
122
+ return sha256(projectLaunchBinding(input));
123
+ }
@@ -6,7 +6,7 @@ import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
7
  import type { AgentConfig } from "../agents/agents.ts";
8
8
  import { normalizeSkillInput } from "../agents/skills.ts";
9
- import { CHAIN_RUNS_DIR, type AcceptanceInput, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "./types.ts";
9
+ import { CHAIN_RUNS_DIR, type AcceptanceInput, type AgentContract, type ChainGateLayer, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "./types.ts";
10
10
  const CHAIN_DIR_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
11
11
  const INITIAL_PROGRESS_CONTENT = "# Progress\n\n## Status\nIn Progress\n\n## Tasks\n\n## Files Changed\n\n## Notes\n";
12
12
 
@@ -57,6 +57,8 @@ export interface SequentialStep {
57
57
  model?: string;
58
58
  toolBudget?: ToolBudgetConfig;
59
59
  acceptance?: AcceptanceInput;
60
+ agentContract?: AgentContract;
61
+ gateOn?: ChainGateLayer;
60
62
  }
61
63
 
62
64
  /** Parallel task item within a parallel step */
@@ -77,6 +79,8 @@ export interface ParallelTaskItem {
77
79
  model?: string;
78
80
  toolBudget?: ToolBudgetConfig;
79
81
  acceptance?: AcceptanceInput;
82
+ agentContract?: AgentContract;
83
+ gateOn?: ChainGateLayer;
80
84
  }
81
85
 
82
86
  export interface DynamicExpandSpec {
@@ -106,6 +110,8 @@ export interface DynamicParallelStep {
106
110
  phase?: string;
107
111
  label?: string;
108
112
  acceptance?: AcceptanceInput;
113
+ agentContract?: AgentContract;
114
+ gateOn?: ChainGateLayer;
109
115
  }
110
116
 
111
117
  /** Parallel step: multiple agents running concurrently */
@@ -115,6 +121,8 @@ export interface ParallelStep {
115
121
  failFast?: boolean;
116
122
  worktree?: boolean;
117
123
  cwd?: string;
124
+ agentContract?: AgentContract;
125
+ gateOn?: ChainGateLayer;
118
126
  }
119
127
 
120
128
  /** Union type for chain steps */