pi-subagents 0.32.0 → 0.33.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 (52) hide show
  1. package/CHANGELOG.md +30 -3
  2. package/README.md +147 -58
  3. package/install.mjs +2 -1
  4. package/package.json +3 -2
  5. package/skills/pi-subagents/SKILL.md +70 -14
  6. package/src/agents/agent-management.ts +177 -5
  7. package/src/agents/agent-memory.ts +254 -0
  8. package/src/agents/agent-serializer.ts +11 -0
  9. package/src/agents/agents.ts +142 -12
  10. package/src/agents/chain-serializer.ts +27 -2
  11. package/src/extension/doctor.ts +1 -9
  12. package/src/extension/fanout-child.ts +2 -2
  13. package/src/extension/index.ts +65 -90
  14. package/src/extension/rpc.ts +369 -0
  15. package/src/extension/schemas.ts +52 -8
  16. package/src/extension/tool-description.ts +200 -0
  17. package/src/intercom/intercom-bridge.ts +21 -253
  18. package/src/intercom/native-supervisor-channel.ts +510 -0
  19. package/src/runs/background/async-execution.ts +51 -7
  20. package/src/runs/background/async-job-tracker.ts +12 -2
  21. package/src/runs/background/async-status.ts +27 -2
  22. package/src/runs/background/completion-batcher.ts +166 -0
  23. package/src/runs/background/control-channel.ts +106 -1
  24. package/src/runs/background/fleet-view.ts +515 -0
  25. package/src/runs/background/notify.ts +161 -44
  26. package/src/runs/background/result-watcher.ts +1 -2
  27. package/src/runs/background/run-id-resolver.ts +3 -2
  28. package/src/runs/background/run-status.ts +166 -6
  29. package/src/runs/background/scheduled-runs.ts +514 -0
  30. package/src/runs/background/subagent-runner.ts +409 -35
  31. package/src/runs/background/wait.ts +353 -0
  32. package/src/runs/foreground/chain-execution.ts +95 -21
  33. package/src/runs/foreground/execution.ts +150 -21
  34. package/src/runs/foreground/subagent-executor.ts +378 -64
  35. package/src/runs/shared/dynamic-fanout.ts +1 -1
  36. package/src/runs/shared/model-fallback.ts +167 -20
  37. package/src/runs/shared/model-scope.ts +128 -0
  38. package/src/runs/shared/nested-events.ts +31 -0
  39. package/src/runs/shared/parallel-utils.ts +1 -0
  40. package/src/runs/shared/pi-args.ts +30 -1
  41. package/src/runs/shared/subagent-prompt-runtime.ts +108 -2
  42. package/src/runs/shared/tool-budget.ts +74 -0
  43. package/src/runs/shared/turn-budget.ts +52 -0
  44. package/src/shared/artifacts.ts +1 -0
  45. package/src/shared/atomic-json.ts +15 -2
  46. package/src/shared/child-transcript.ts +212 -0
  47. package/src/shared/settings.ts +3 -1
  48. package/src/shared/types.ts +134 -19
  49. package/src/slash/prompt-workflows.ts +330 -0
  50. package/src/slash/slash-commands.ts +16 -2
  51. package/src/tui/render.ts +16 -8
  52. package/src/extension/companion-suggestions.ts +0 -359
@@ -0,0 +1,74 @@
1
+ import type { ResolvedToolBudget, ToolBudgetConfig, ToolBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"] as const;
4
+ export const TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
5
+
6
+ export function normalizeToolBudgetBlock(block: ToolBudgetConfig["block"] | undefined): "*" | string[] {
7
+ if (block === "*") return "*";
8
+ if (block === undefined) return [...DEFAULT_TOOL_BUDGET_BLOCK];
9
+ return [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
10
+ }
11
+
12
+ export function validateToolBudgetConfig(raw: unknown, label = "toolBudget"): { budget?: ResolvedToolBudget; error?: string } {
13
+ if (raw === undefined) return {};
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: `${label} must be an object with hard and optional soft/block.` };
15
+ const value = raw as ToolBudgetConfig;
16
+ if (typeof value.hard !== "number" || !Number.isInteger(value.hard) || value.hard < 1) {
17
+ return { error: `${label}.hard must be an integer >= 1.` };
18
+ }
19
+ if (value.soft !== undefined && (typeof value.soft !== "number" || !Number.isInteger(value.soft) || value.soft < 1)) {
20
+ return { error: `${label}.soft must be an integer >= 1 when provided.` };
21
+ }
22
+ if (value.soft !== undefined && value.soft > value.hard) {
23
+ return { error: `${label}.soft must be <= ${label}.hard.` };
24
+ }
25
+ if (value.block !== undefined && value.block !== "*") {
26
+ if (!Array.isArray(value.block)) return { error: `${label}.block must be "*" or an array of tool names.` };
27
+ if (value.block.length === 0) return { error: `${label}.block must contain at least one tool name.` };
28
+ for (const item of value.block) {
29
+ if (typeof item !== "string" || !item.trim()) return { error: `${label}.block must contain non-empty tool names.` };
30
+ }
31
+ }
32
+ return { budget: { hard: value.hard, ...(value.soft !== undefined ? { soft: value.soft } : {}), block: normalizeToolBudgetBlock(value.block) } };
33
+ }
34
+
35
+ export function initialToolBudgetState(budget: ResolvedToolBudget): ToolBudgetState {
36
+ return { ...budget, toolCount: 0, outcome: "within-budget" };
37
+ }
38
+
39
+ export function toolBudgetState(budget: ResolvedToolBudget, toolCount: number, blockedTool?: string): ToolBudgetState {
40
+ const overHard = toolCount > budget.hard;
41
+ const overSoft = budget.soft !== undefined && toolCount >= budget.soft;
42
+ return {
43
+ ...budget,
44
+ toolCount,
45
+ outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
46
+ ...(overSoft ? { softReachedAt: budget.soft } : {}),
47
+ ...(overHard ? { hardReachedAt: budget.hard, blockedTool } : {}),
48
+ };
49
+ }
50
+
51
+ export function shouldBlockToolForBudget(budget: ResolvedToolBudget, toolName: string, nextToolCount: number): boolean {
52
+ if (nextToolCount <= budget.hard) return false;
53
+ return budget.block === "*" || budget.block.includes(toolName);
54
+ }
55
+
56
+ export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: number): string {
57
+ return `Tool budget soft limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (soft ${budget.soft}, hard ${budget.hard}). Stop starting new browsing/search work and finalize from the context you already have.`;
58
+ }
59
+
60
+ export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
61
+ return `Tool budget hard limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (hard ${budget.hard}). The '${toolName}' tool is blocked so you can finalize from the context you already have.`;
62
+ }
63
+
64
+ export function encodeToolBudgetEnv(budget: ResolvedToolBudget | undefined): string | undefined {
65
+ return budget ? JSON.stringify(budget) : undefined;
66
+ }
67
+
68
+ export function decodeToolBudgetEnv(value: string | undefined): ResolvedToolBudget | undefined {
69
+ if (!value?.trim()) return undefined;
70
+ const parsed = JSON.parse(value) as unknown;
71
+ const normalized = validateToolBudgetConfig(parsed, TOOL_BUDGET_ENV);
72
+ if (normalized.error) throw new Error(normalized.error);
73
+ return normalized.budget;
74
+ }
@@ -0,0 +1,52 @@
1
+ import type { ResolvedTurnBudget, TurnBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TURN_BUDGET_GRACE_TURNS = 1;
4
+
5
+ export function appendTurnBudgetSystemPrompt(systemPrompt: string, budget: ResolvedTurnBudget | undefined): string {
6
+ if (!budget) return systemPrompt;
7
+ const grace = budget.graceTurns === 1 ? "1 additional assistant turn" : `${budget.graceTurns} additional assistant turns`;
8
+ const block = [
9
+ "## Turn budget",
10
+ `This child run has a soft budget of ${budget.maxTurns} assistant turn${budget.maxTurns === 1 ? "" : "s"}.`,
11
+ `After that, ${grace} may be allowed only for a final wrap-up.`,
12
+ "When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.",
13
+ "This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.",
14
+ "If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output.",
15
+ ].join("\n");
16
+ return systemPrompt.trim() ? `${systemPrompt.trim()}\n\n${block}` : block;
17
+ }
18
+
19
+ export function turnBudgetSoftNote(budget: ResolvedTurnBudget, turnCount: number): string {
20
+ return `Turn budget wrap-up was requested after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns}, grace ${budget.graceTurns}). Process-mode live steering is unavailable, so the child was warned at launch to wrap up by this budget. Output may be partial.`;
21
+ }
22
+
23
+ export function turnBudgetExceededMessage(budget: ResolvedTurnBudget, turnCount: number): string {
24
+ return `Subagent exceeded turn budget after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns} + grace ${budget.graceTurns}).`;
25
+ }
26
+
27
+ export function formatTurnBudgetOutput(message: string, output: string): string {
28
+ return output.trim()
29
+ ? `${message}\n\nPartial output before turn-budget abort:\n${output}`
30
+ : message;
31
+ }
32
+
33
+ export function initialTurnBudgetState(budget: ResolvedTurnBudget): TurnBudgetState {
34
+ return { ...budget, outcome: "within-budget", turnCount: 0 };
35
+ }
36
+
37
+ export function turnBudgetState(budget: ResolvedTurnBudget, turnCount: number, exceeded: boolean): TurnBudgetState {
38
+ return {
39
+ ...budget,
40
+ turnCount,
41
+ outcome: exceeded ? "exceeded" : "wrap-up-requested",
42
+ wrapUpRequestedAtTurn: budget.maxTurns,
43
+ ...(exceeded ? { exceededAtTurn: turnCount } : {}),
44
+ };
45
+ }
46
+
47
+ export function shouldAbortForTurnBudget(budget: ResolvedTurnBudget, turnCount: number, terminalAssistantStop: boolean): boolean {
48
+ const hardLimit = budget.maxTurns + budget.graceTurns;
49
+ if (turnCount < hardLimit) return false;
50
+ if (turnCount > hardLimit) return true;
51
+ return !terminalAssistantStop;
52
+ }
@@ -34,6 +34,7 @@ export function getArtifactPaths(artifactsDir: string, runId: string, agent: str
34
34
  inputPath: path.join(artifactsDir, `${base}_input.md`),
35
35
  outputPath: path.join(artifactsDir, `${base}_output.md`),
36
36
  jsonlPath: path.join(artifactsDir, `${base}.jsonl`),
37
+ transcriptPath: path.join(artifactsDir, `${base}_transcript.jsonl`),
37
38
  metadataPath: path.join(artifactsDir, `${base}_meta.json`),
38
39
  };
39
40
  }
@@ -13,13 +13,26 @@ type AtomicJsonWriterOptions = {
13
13
  wait?: (delayMs: number) => void;
14
14
  };
15
15
 
16
- const DEFAULT_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200] as const;
16
+ const DEFAULT_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 500, 1000, 2000, 4000] as const;
17
17
  const RETRYABLE_RENAME_ERROR_CODES = new Set(["EACCES", "EBUSY", "EPERM"]);
18
+ const WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
19
+ const WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : undefined;
18
20
 
19
21
  function waitSync(delayMs: number): void {
22
+ if (delayMs <= 0) return;
23
+ if (WAIT_VIEW) {
24
+ try {
25
+ // writeAtomicJson is synchronous because callers often update status from sync callbacks.
26
+ // Atomics.wait gives Windows rename locks time to clear without burning CPU.
27
+ Atomics.wait(WAIT_VIEW, 0, 0, delayMs);
28
+ return;
29
+ } catch {
30
+ // Fall through to the portable busy wait below.
31
+ }
32
+ }
20
33
  const end = Date.now() + delayMs;
21
34
  while (Date.now() < end) {
22
- // writeAtomicJson is synchronous because callers often update status from sync callbacks.
35
+ // Portable fallback for runtimes where Atomics.wait is unavailable.
23
36
  }
24
37
  }
25
38
 
@@ -0,0 +1,212 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { Message } from "@earendil-works/pi-ai";
4
+ import { extractTextFromContent, extractToolArgsPreview } from "./utils.ts";
5
+
6
+ export const CHILD_TRANSCRIPT_ARTIFACT_VERSION = 1;
7
+ const DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES = 50 * 1024 * 1024;
8
+
9
+ type ChildTranscriptSource = "foreground" | "async";
10
+ type ChildTranscriptRecordType = "message" | "tool_start" | "tool_end" | "stdout" | "stderr" | "truncated";
11
+
12
+ type ChildTranscriptMessage = Message & {
13
+ model?: string;
14
+ errorMessage?: string;
15
+ stopReason?: string;
16
+ usage?: unknown;
17
+ };
18
+
19
+ interface ChildTranscriptEvent {
20
+ type?: string;
21
+ message?: ChildTranscriptMessage;
22
+ toolName?: string;
23
+ args?: unknown;
24
+ }
25
+
26
+ interface ChildTranscriptWriterInput {
27
+ transcriptPath: string;
28
+ source: ChildTranscriptSource;
29
+ runId: string;
30
+ agent: string;
31
+ childIndex?: number;
32
+ cwd: string;
33
+ maxBytes?: number;
34
+ }
35
+
36
+ export interface ChildTranscriptWriter {
37
+ path: string;
38
+ writeInitialUserMessage(prompt: string): void;
39
+ writeChildEvent(event: ChildTranscriptEvent): void;
40
+ writeStdoutLine(line: string): void;
41
+ writeStderrLine(line: string): void;
42
+ writeStderrText(text: string): void;
43
+ getError(): string | undefined;
44
+ }
45
+
46
+ function errorMessage(error: unknown): string {
47
+ return error instanceof Error ? error.message : String(error);
48
+ }
49
+
50
+ function finiteNumber(value: unknown): number | undefined {
51
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
52
+ }
53
+
54
+ function normalizeUsage(value: unknown): { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number } | undefined {
55
+ if (!value || typeof value !== "object") return undefined;
56
+ const raw = value as Record<string, unknown>;
57
+ const rawCost = raw.cost;
58
+ const cost = rawCost && typeof rawCost === "object"
59
+ ? finiteNumber((rawCost as { total?: unknown }).total) ?? 0
60
+ : finiteNumber(rawCost) ?? 0;
61
+ return {
62
+ input: finiteNumber(raw.input) ?? finiteNumber(raw.inputTokens) ?? 0,
63
+ output: finiteNumber(raw.output) ?? finiteNumber(raw.outputTokens) ?? 0,
64
+ cacheRead: finiteNumber(raw.cacheRead) ?? 0,
65
+ cacheWrite: finiteNumber(raw.cacheWrite) ?? 0,
66
+ cost,
67
+ };
68
+ }
69
+
70
+ function eventArgs(event: ChildTranscriptEvent): Record<string, unknown> {
71
+ return event.args && typeof event.args === "object" && !Array.isArray(event.args)
72
+ ? event.args as Record<string, unknown>
73
+ : {};
74
+ }
75
+
76
+ export function createChildTranscriptWriter(input: ChildTranscriptWriterInput): ChildTranscriptWriter {
77
+ let bytesWritten = 0;
78
+ let writeError: string | undefined;
79
+ let truncated = false;
80
+ const maxBytes = input.maxBytes ?? DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES;
81
+
82
+ const baseRecord = (recordType: ChildTranscriptRecordType) => {
83
+ const ts = Date.now();
84
+ return {
85
+ version: CHILD_TRANSCRIPT_ARTIFACT_VERSION,
86
+ recordType,
87
+ source: input.source,
88
+ runId: input.runId,
89
+ agent: input.agent,
90
+ ...(input.childIndex !== undefined ? { childIndex: input.childIndex } : {}),
91
+ cwd: input.cwd,
92
+ ts,
93
+ timestamp: new Date(ts).toISOString(),
94
+ };
95
+ };
96
+
97
+ const writeTruncatedMarker = () => {
98
+ truncated = true;
99
+ const marker = `${JSON.stringify({
100
+ ...baseRecord("truncated"),
101
+ maxBytes,
102
+ message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
103
+ })}\n`;
104
+ const markerBytes = Buffer.byteLength(marker, "utf-8");
105
+ if (bytesWritten + markerBytes > maxBytes) return false;
106
+ try {
107
+ fs.appendFileSync(input.transcriptPath, marker, "utf-8");
108
+ bytesWritten += markerBytes;
109
+ return true;
110
+ } catch (error) {
111
+ writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
112
+ return false;
113
+ }
114
+ };
115
+
116
+ const writeRecord = (record: Record<string, unknown>) => {
117
+ if (writeError || truncated) return;
118
+ const line = `${JSON.stringify(record)}\n`;
119
+ const bytes = Buffer.byteLength(line, "utf-8");
120
+ if (bytesWritten + bytes > maxBytes) {
121
+ writeTruncatedMarker();
122
+ return;
123
+ }
124
+ const markerProbe = `${JSON.stringify({
125
+ ...baseRecord("truncated"),
126
+ maxBytes,
127
+ message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
128
+ })}\n`;
129
+ if (bytesWritten + bytes + Buffer.byteLength(markerProbe, "utf-8") > maxBytes) {
130
+ writeTruncatedMarker();
131
+ return;
132
+ }
133
+ try {
134
+ fs.appendFileSync(input.transcriptPath, line, "utf-8");
135
+ bytesWritten += bytes;
136
+ } catch (error) {
137
+ writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
138
+ }
139
+ };
140
+
141
+ try {
142
+ fs.mkdirSync(path.dirname(input.transcriptPath), { recursive: true });
143
+ fs.writeFileSync(input.transcriptPath, "", "utf-8");
144
+ } catch (error) {
145
+ writeError = `Failed to initialize child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
146
+ }
147
+
148
+ const writeMessage = (sourceEventType: string, message: ChildTranscriptMessage) => {
149
+ const text = extractTextFromContent(message.content);
150
+ writeRecord({
151
+ ...baseRecord("message"),
152
+ sourceEventType,
153
+ role: message.role,
154
+ ...(text ? { text } : {}),
155
+ ...(message.model ? { model: message.model } : {}),
156
+ ...(message.stopReason ? { stopReason: message.stopReason } : {}),
157
+ ...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
158
+ ...(message.usage ? { usage: normalizeUsage(message.usage) } : {}),
159
+ message,
160
+ });
161
+ };
162
+
163
+ return {
164
+ path: input.transcriptPath,
165
+ writeInitialUserMessage(prompt: string) {
166
+ writeRecord({
167
+ ...baseRecord("message"),
168
+ sourceEventType: "initial_prompt",
169
+ role: "user",
170
+ text: prompt,
171
+ message: { role: "user", content: [{ type: "text", text: prompt }] },
172
+ });
173
+ },
174
+ writeChildEvent(event: ChildTranscriptEvent) {
175
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
176
+ writeMessage(event.type, event.message);
177
+ return;
178
+ }
179
+ if (event.type === "tool_execution_start" && event.toolName) {
180
+ const args = eventArgs(event);
181
+ writeRecord({
182
+ ...baseRecord("tool_start"),
183
+ sourceEventType: event.type,
184
+ toolName: event.toolName,
185
+ ...(Object.keys(args).length > 0 ? { argsPreview: extractToolArgsPreview(args) } : {}),
186
+ });
187
+ return;
188
+ }
189
+ if (event.type === "tool_execution_end") {
190
+ writeRecord({
191
+ ...baseRecord("tool_end"),
192
+ sourceEventType: event.type,
193
+ ...(event.toolName ? { toolName: event.toolName } : {}),
194
+ });
195
+ }
196
+ },
197
+ writeStdoutLine(line: string) {
198
+ if (!line.trim()) return;
199
+ writeRecord({ ...baseRecord("stdout"), text: line });
200
+ },
201
+ writeStderrLine(line: string) {
202
+ if (!line.trim()) return;
203
+ writeRecord({ ...baseRecord("stderr"), text: line });
204
+ },
205
+ writeStderrText(text: string) {
206
+ for (const line of text.split(/\r?\n/)) this.writeStderrLine(line);
207
+ },
208
+ getError() {
209
+ return writeError;
210
+ },
211
+ };
212
+ }
@@ -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 } from "./types.ts";
9
+ import { CHAIN_RUNS_DIR, type AcceptanceInput, 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
 
@@ -55,6 +55,7 @@ export interface SequentialStep {
55
55
  progress?: boolean;
56
56
  skill?: string | string[] | false;
57
57
  model?: string;
58
+ toolBudget?: ToolBudgetConfig;
58
59
  acceptance?: AcceptanceInput;
59
60
  }
60
61
 
@@ -74,6 +75,7 @@ export interface ParallelTaskItem {
74
75
  progress?: boolean;
75
76
  skill?: string | string[] | false;
76
77
  model?: string;
78
+ toolBudget?: ToolBudgetConfig;
77
79
  acceptance?: AcceptanceInput;
78
80
  }
79
81