@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -83,12 +83,13 @@ export function parseFrontmatter(content: string): { frontmatter: Record<string,
83
83
  let currentBlockLines: string[] | null = null;
84
84
  let currentIndent: number | null = null;
85
85
  let currentFolded = false;
86
+ let currentLiteral = false;
86
87
 
87
88
  for (const line of lines) {
88
89
  const indent = line.search(/\S|$/); // position of first non-whitespace char
89
90
  const trimmed = line.trim();
90
91
 
91
- if (currentKey !== null && currentBlockLines !== null && (indent > (currentIndent ?? 0) || (currentFolded && trimmed === ""))) {
92
+ if (currentKey !== null && currentBlockLines !== null && (indent > (currentIndent ?? 0) || ((currentFolded || currentLiteral) && trimmed === ""))) {
92
93
  // This line is part of the current block value
93
94
  currentBlockLines.push(line);
94
95
  continue;
@@ -109,6 +110,7 @@ export function parseFrontmatter(content: string): { frontmatter: Record<string,
109
110
  currentBlockLines = null;
110
111
  currentIndent = null;
111
112
  currentFolded = false;
113
+ currentLiteral = false;
112
114
  }
113
115
 
114
116
  const match = line.match(/^([\w-]+):\s*(.*)$/);
@@ -119,13 +121,15 @@ export function parseFrontmatter(content: string): { frontmatter: Record<string,
119
121
  const isQuoted = (rawValue.startsWith('"') && rawValue.endsWith('"')) || (rawValue.startsWith("'") && rawValue.endsWith("'"));
120
122
  const value = isQuoted ? rawValue.slice(1, -1) : rawValue;
121
123
  const isFolded = !isQuoted && (rawValue === ">" || rawValue === ">-");
124
+ const isLiteral = !isQuoted && (rawValue === "|" || rawValue === "|-");
122
125
 
123
- if (value === "" || isFolded) {
124
- // Key with empty value or folded block indicator — defer storing until we see indent
126
+ if (value === "" || isFolded || isLiteral) {
127
+ // Key with empty value or block scalar indicator — defer storing until we see indent
125
128
  currentKey = key;
126
129
  currentBlockLines = [];
127
130
  currentIndent = indent;
128
131
  currentFolded = isFolded;
132
+ currentLiteral = isLiteral;
129
133
  } else {
130
134
  // Simple key: value
131
135
  frontmatter[key] = value;
@@ -6,6 +6,7 @@ import { execSync } from "node:child_process";
6
6
  import * as fs from "node:fs";
7
7
  import * as os from "node:os";
8
8
  import * as path from "node:path";
9
+ import { parseFrontmatter } from "./frontmatter.ts";
9
10
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
10
11
 
11
12
  export type SkillSource =
@@ -395,15 +396,7 @@ function chooseHigherPrioritySkill(existing: CachedSkillEntry | undefined, candi
395
396
  }
396
397
 
397
398
  function parseSkillDescription(content: string): string | undefined {
398
- const normalized = content.replace(/\r\n/g, "\n");
399
- if (!normalized.startsWith("---")) return undefined;
400
-
401
- const endIndex = normalized.indexOf("\n---", 3);
402
- if (endIndex === -1) return undefined;
403
-
404
- const frontmatter = normalized.slice(3, endIndex).trim();
405
- const match = frontmatter.match(/^description:\s*(.+)$/m);
406
- return match?.[1]?.trim().replace(/^['\"]|['\"]$/g, "");
399
+ return parseFrontmatter(content).frontmatter.description;
407
400
  }
408
401
 
409
402
  function maybeReadSkillDescription(filePath: string): string | undefined {
@@ -285,7 +285,7 @@ export async function resolveSubagentLaunchContract(input: SubagentLaunchContrac
285
285
  return { ok: false, code: "denied_required_tool", message, diagnostics };
286
286
  }
287
287
  const artifactsEnabled = input.artifacts !== false;
288
- const artifactsDir = artifactsEnabled ? getArtifactsDir(input.parentSessionFile ?? null, effectiveCwd, input.artifactDir ?? "project") : undefined;
288
+ const artifactsDir = artifactsEnabled ? getArtifactsDir(input.parentSessionFile ?? null, effectiveCwd, input.artifactDir) : undefined;
289
289
  const artifactPaths = artifactsDir ? getArtifactPaths(artifactsDir, runId, agent.name, 0) : undefined;
290
290
  const outputPath = resolveSingleOutputPath(behavior.output, effectiveCwd, effectiveCwd, artifactsDir ? path.join(artifactsDir, "outputs", runId) : undefined);
291
291
  const sessionRoot = input.sessionDir ? path.resolve(input.sessionDir) : input.sessionRoot ? path.join(path.resolve(input.sessionRoot), runId) : undefined;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Public project-owned Herdr pane lifecycle API for other Pi extensions.
3
+ *
4
+ * This is the supported extension-to-extension surface. Callers must not
5
+ * import `src/inspectors/herdr/*` directly.
6
+ */
7
+ export {
8
+ PROJECT_PANES_API_VERSION,
9
+ PROJECT_PANE_TRUST_STATUS,
10
+ createProjectPaneManager,
11
+ openProjectPane,
12
+ getProjectPaneStatus,
13
+ closeProjectPane,
14
+ readProjectPaneBinding,
15
+ projectPaneBindingPath,
16
+ type ProjectPaneManager,
17
+ type ProjectPaneManagerOptions,
18
+ type ProjectPaneCommandClient,
19
+ type OpenProjectPaneOptions,
20
+ type GetProjectPaneStatusOptions,
21
+ type CloseProjectPaneOptions,
22
+ type OpenProjectPaneData,
23
+ type ProjectPaneStatusData,
24
+ type CloseProjectPaneData,
25
+ type ProjectPaneRuntime,
26
+ type ProjectPaneError,
27
+ type ProjectPaneErrorCode,
28
+ type ProjectPaneResult,
29
+ type HerdrProjectPaneBinding,
30
+ } from "../inspectors/herdr/project-panes.ts";
@@ -1,13 +1,14 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
- import type { ArtifactDirPreference, ExtensionConfig } from "../shared/types.ts";
4
+ import { FLEET_KEYBINDING_ACTIONS, type ArtifactDirPreference, type ExtensionConfig } from "../shared/types.ts";
5
5
  import { validateMissionStoreConfig } from "../missions/store.ts";
6
6
  import { validateAuthorityPolicy } from "../policy/authority.ts";
7
7
  import { getAgentDir } from "../shared/utils.ts";
8
8
  import { validatePermissionConfig } from "../runs/shared/permissions.ts";
9
9
 
10
10
  const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
11
+ const FLEET_KEYBINDING_ACTION_SET = new Set<string>(FLEET_KEYBINDING_ACTIONS);
11
12
 
12
13
  export function resolveScheduledStoreRoot(value: string): string {
13
14
  const expanded = value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : value;
@@ -24,14 +25,66 @@ function validateScheduledRunsConfig(value: unknown): void {
24
25
  resolveScheduledStoreRoot(storeRoot);
25
26
  }
26
27
 
28
+ function validateFleetKeybindingsConfig(value: unknown): void {
29
+ if (value === undefined) return;
30
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.fleetKeybindings must be a JSON object");
31
+ for (const [action, bindings] of Object.entries(value)) {
32
+ if (!FLEET_KEYBINDING_ACTION_SET.has(action)) throw new Error(`config.fleetKeybindings.${action} is not a supported Fleet action`);
33
+ if (!Array.isArray(bindings) || bindings.length === 0) throw new Error(`config.fleetKeybindings.${action} must be a non-empty array of strings`);
34
+ for (const binding of bindings) {
35
+ if (typeof binding !== "string" || !binding.trim()) throw new Error(`config.fleetKeybindings.${action} entries must be non-empty strings`);
36
+ }
37
+ }
38
+ }
39
+
40
+ function validateArtifactConfig(value: unknown): void {
41
+ if (value === undefined) return;
42
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.artifactConfig must be a JSON object");
43
+ const cleanupDays = (value as Record<string, unknown>).cleanupDays;
44
+ if (cleanupDays !== undefined && (typeof cleanupDays !== "number" || !Number.isInteger(cleanupDays) || cleanupDays < 0)) {
45
+ throw new Error("config.artifactConfig.cleanupDays must be a non-negative integer");
46
+ }
47
+ }
48
+
49
+ function validateMainWindowRendererConfig(value: unknown): void {
50
+ if (value === undefined) return;
51
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.mainWindowRenderer must be a JSON object");
52
+ const rendererConfig = value as Record<string, unknown>;
53
+ if (rendererConfig.horizontalSpacing !== undefined
54
+ && (typeof rendererConfig.horizontalSpacing !== "number"
55
+ || !Number.isInteger(rendererConfig.horizontalSpacing)
56
+ || rendererConfig.horizontalSpacing < 0
57
+ || rendererConfig.horizontalSpacing > 4)) {
58
+ throw new Error("config.mainWindowRenderer.horizontalSpacing must be an integer from 0 to 4");
59
+ }
60
+ if (rendererConfig.compactResultMaxLines !== undefined
61
+ && (typeof rendererConfig.compactResultMaxLines !== "number"
62
+ || !Number.isInteger(rendererConfig.compactResultMaxLines)
63
+ || rendererConfig.compactResultMaxLines < 1)) {
64
+ throw new Error("config.mainWindowRenderer.compactResultMaxLines must be a positive integer");
65
+ }
66
+ }
67
+
27
68
  function validateConfig(config: Record<string, unknown>): void {
28
69
  if (config.artifactDir !== undefined && !ARTIFACT_DIR_PREFERENCES.has(config.artifactDir as ArtifactDirPreference)) {
29
70
  throw new Error(`config.artifactDir must be "project", "session", or "temp"`);
30
71
  }
72
+ if (config.legacyChainControls !== undefined && typeof config.legacyChainControls !== "boolean") {
73
+ throw new Error("config.legacyChainControls must be a boolean");
74
+ }
75
+ if (config.maxActiveAsyncRunsPerSession !== undefined
76
+ && (typeof config.maxActiveAsyncRunsPerSession !== "number"
77
+ || !Number.isInteger(config.maxActiveAsyncRunsPerSession)
78
+ || config.maxActiveAsyncRunsPerSession < 0)) {
79
+ throw new Error("config.maxActiveAsyncRunsPerSession must be a non-negative integer");
80
+ }
31
81
  validateMissionStoreConfig(config.missions);
32
82
  validateAuthorityPolicy(config.authorityPolicy);
33
83
  validatePermissionConfig(config.permissions);
34
84
  validateScheduledRunsConfig(config.scheduledRuns);
85
+ validateFleetKeybindingsConfig(config.fleetKeybindings);
86
+ validateArtifactConfig(config.artifactConfig);
87
+ validateMainWindowRendererConfig(config.mainWindowRenderer);
35
88
  }
36
89
 
37
90
  export function getConfigPath(): string {
@@ -3,6 +3,8 @@ import * as path from "node:path";
3
3
  import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
4
4
  import { isAsyncAvailable } from "../runs/background/async-execution.ts";
5
5
  import { formatSpawnBudgetSummary, getSpawnBudgetSnapshot } from "../runs/shared/spawn-budget.ts";
6
+ import { getActiveAsyncCapacitySnapshot, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
7
+ import { decodeRunFanoutBudgetDescriptor, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, RUN_FANOUT_BUDGET_ENV } from "../runs/shared/run-fanout-budget.ts";
6
8
  import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "../intercom/intercom-bridge.ts";
7
9
  import { discoverAvailableSkills, type SkillSource } from "../agents/skills.ts";
8
10
  import {
@@ -11,6 +13,8 @@ import {
11
13
  TEMP_ROOT_DIR,
12
14
  type ExtensionConfig,
13
15
  type SubagentState,
16
+ normalizeMaxSubagentSpawnsPerRun,
17
+ resolveMaxSubagentSpawnsPerRun,
14
18
  } from "../shared/types.ts";
15
19
 
16
20
  interface DoctorPaths {
@@ -175,6 +179,36 @@ function formatSpawnBudgetSection(input: DoctorReportInput): string[] {
175
179
  ];
176
180
  }
177
181
 
182
+ function formatRunFanoutSection(input: DoctorReportInput): string[] {
183
+ try {
184
+ const inherited = decodeRunFanoutBudgetDescriptor(process.env[RUN_FANOUT_BUDGET_ENV]);
185
+ if (inherited) {
186
+ return [`- usage: ${formatRunFanoutBudget(getRunFanoutBudgetSnapshot(inherited)).replace(/^Run fan-out: /, "")}`, `- root run: ${inherited.rootRunId}`, "- reset boundary: cumulative claims are never released; a new top-level run creates a new budget"];
187
+ }
188
+ } catch (error) {
189
+ return [`- inherited budget: invalid — ${errorText(error)}`];
190
+ }
191
+ const configured = resolveMaxSubagentSpawnsPerRun(input.config.maxSubagentSpawnsPerRun);
192
+ const source = normalizeMaxSubagentSpawnsPerRun(process.env.PI_SUBAGENT_MAX_SPAWNS_PER_RUN) !== undefined
193
+ ? "environment"
194
+ : normalizeMaxSubagentSpawnsPerRun(input.config.maxSubagentSpawnsPerRun) !== undefined ? "config" : "default";
195
+ return [`- configured limit: ${configured} (${source})`, "- usage: available after a run starts", "- reset boundary: cumulative claims are never released; a new top-level run creates a new budget"];
196
+ }
197
+
198
+ function formatActiveAsyncCapacitySection(input: DoctorReportInput): string[] {
199
+ const limit = resolveMaxActiveAsyncRunsPerSession(input.config.maxActiveAsyncRunsPerSession);
200
+ const sessionId = input.currentSessionId ?? input.state.currentSessionId;
201
+ const snapshot = sessionId
202
+ ? getActiveAsyncCapacitySnapshot(sessionId, limit, { liveWorkflowRunIds: new Set(input.state.workflowControllers?.keys() ?? []) })
203
+ : { used: 0, limit: limit ?? 0 };
204
+ input.state.activeAsyncCapacity = snapshot;
205
+ return [
206
+ `- usage: ${snapshot.used}/${snapshot.limit || "unlimited"} used`,
207
+ "- scope: top-level async runs in the current parent session; foreground and nested workflow children are not charged again",
208
+ "- release: terminal logical state plus verified process exit; missing or unknown cleanup proof retains capacity",
209
+ ];
210
+ }
211
+
178
212
  function formatPermissionSystemSection(): string[] {
179
213
  const lines: string[] = [];
180
214
  const parentSession = process.env["PI_SUBAGENT_PARENT_SESSION"] ?? "";
@@ -215,6 +249,12 @@ export function buildDoctorReport(input: DoctorReportInput): string {
215
249
  "Spawn budget",
216
250
  ...formatSpawnBudgetSection(input),
217
251
  "",
252
+ "Run fan-out budget",
253
+ ...formatRunFanoutSection(input),
254
+ "",
255
+ "Active async capacity",
256
+ ...formatActiveAsyncCapacitySection(input),
257
+ "",
218
258
  "Permission system",
219
259
  ...formatPermissionSystemSection(),
220
260
  "",
@@ -10,7 +10,7 @@ import { SUBAGENT_CHILD_ENV, SUBAGENT_FANOUT_CHILD_ENV } from "../runs/shared/pi
10
10
  import { readNestedControlRequests, resolveNestedRouteFromEnv, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
11
11
  import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
12
12
  import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
13
- import { SubagentParams } from "./schemas.ts";
13
+ import { createSubagentParamsSchema } from "./schemas.ts";
14
14
  import { loadConfig, resolveAsyncByDefault } from "./config.ts";
15
15
  import { type Details, type SubagentState } from "../shared/types.ts";
16
16
 
@@ -171,15 +171,16 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI):
171
171
  allowMutatingManagementActions: false,
172
172
  });
173
173
 
174
- const tool: ToolDefinition<typeof SubagentParams, Details> = {
174
+ const params = createSubagentParamsSchema(config);
175
+ const tool: ToolDefinition<typeof params, Details> = {
175
176
  name: "subagent",
176
177
  label: "Subagent",
177
178
  description: [
178
179
  "Delegate to subagents from child-safe fanout mode.",
179
- "Allowed management/control actions: list, get, status, interrupt, resume, steer, append-step, doctor.",
180
+ `Allowed management/control actions: list, get, status, interrupt, resume, steer${config.legacyChainControls === true ? ", append-step" : ""}, doctor.`,
180
181
  "Mutating management actions (create, update, delete, eject, disable, enable, reset, grant-spawn-budget) are blocked in this mode.",
181
182
  ].join("\n"),
182
- parameters: SubagentParams,
183
+ parameters: params,
183
184
  execute(id, params, signal, onUpdate, ctx) {
184
185
  return executor.executePublic(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx);
185
186
  },