@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -11,15 +11,18 @@ import { validateAcceptanceReport } from "./acceptance.ts";
11
11
  import { formatChildToolDiagnostic } from "./tool-availability.ts";
12
12
  import { shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
13
13
  import type { ResolvedToolBudget, SubagentState } from "../../shared/types.ts";
14
+ import { INTERCOM_SESSION_IDENTITY_EVENT } from "../../shared/types.ts";
14
15
  import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
15
16
  import { getAgentDir } from "../../shared/utils.ts";
16
17
  import { registerChildWatchdog } from "../../watchdog/register-child.ts";
17
18
  import type { ChildWatchdogConfig } from "../../watchdog/child-status.ts";
18
19
  import { requestWatchdogPermission, type WatchdogPermissionRequest, type WatchdogPermissionResult } from "../../watchdog/permission-arbiter.ts";
19
20
  import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../watchdog/types.ts";
21
+ import { captureWatchdogDiffBaseline, createWatchdogDiffTool, WATCHDOG_DIFF_TOOL_NAME } from "../../watchdog/diff-tool.ts";
20
22
  import { inheritedNestedRouteOf } from "./nested-events.ts";
21
23
  import { registerWaitTool } from "../background/wait-tool.ts";
22
24
  import { drainOutstandingWork } from "../background/auto-drain.ts";
25
+ import { MODEL_ONLY_TOOL } from "../../shared/extension-context.ts";
23
26
  import {
24
27
  childSupervisorMetadata,
25
28
  evaluateChildToolDiagnostic,
@@ -403,6 +406,7 @@ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undef
403
406
  }
404
407
 
405
408
  function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<ChildRuntimeConfig["structuredOutput"]>): void {
409
+ const terminalState = structured.terminalState ??= { captured: false };
406
410
  const required = structured.acceptanceReport === "required";
407
411
  const parameters = createStructuredOutputToolParameters(structured.schema, { acceptanceReport: structured.acceptanceReport });
408
412
  const registerTool = pi.registerTool as unknown as (tool: {
@@ -414,6 +418,7 @@ function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<
414
418
  }) => void;
415
419
  registerTool({
416
420
  name: "structured_output",
421
+ ...MODEL_ONLY_TOOL,
417
422
  label: "Structured Output",
418
423
  description: "Submit the required final structured output for this subagent step. This terminates the step.",
419
424
  parameters,
@@ -432,6 +437,7 @@ function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<
432
437
  }
433
438
  }
434
439
  structured.capture(params.value, structured.acceptanceReport ? params.acceptanceReport : undefined);
440
+ terminalState.captured = true;
435
441
  return {
436
442
  content: [{ type: "text", text: "Structured output captured." }],
437
443
  details: {},
@@ -451,7 +457,15 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
451
457
  registerRuntimeExtensionAcknowledgements(pi, config.runtimeAcknowledgements);
452
458
  registerPermissionGate(pi, config.permissions, config.childWatchdog);
453
459
  registerToolBudget(pi, config.toolBudget);
454
- registerChildWatchdog(pi, config.childWatchdog, config.watchdogStatus);
460
+ if (config.structuredOutput && !config.structuredOutput.terminalState) config.structuredOutput.terminalState = { captured: false };
461
+ registerChildWatchdog(pi, config.childWatchdog, config.watchdogStatus, config.structuredOutput?.terminalState);
462
+ const requestedWatchdogDiff = config.requiredTools?.includes(WATCHDOG_DIFF_TOOL_NAME);
463
+ const reviewerLaunchBaseline = requestedWatchdogDiff && config.cwd
464
+ ? captureWatchdogDiffBaseline(config.cwd)
465
+ : undefined;
466
+ if (requestedWatchdogDiff && typeof pi.registerTool === "function") {
467
+ pi.registerTool(createWatchdogDiffTool(reviewerLaunchBaseline, { workingTreeAtLaunch: true }));
468
+ }
455
469
  const waitState = config.runtimeState ?? {
456
470
  baseCwd: "",
457
471
  currentSessionId: null,
@@ -516,13 +530,23 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
516
530
  return { messages };
517
531
  });
518
532
 
533
+ // pi-intercom asks at session start for this session's intercom ID. Claiming
534
+ // the route there frees the session name for the readable label. An older
535
+ // pi-intercom never asks and routes by name, so the route stays the name.
536
+ const routingName = config.intercomSessionName;
537
+ let intercomIdClaimed = false;
538
+ if (routingName) {
539
+ pi.events.on(INTERCOM_SESSION_IDENTITY_EVENT, (request: unknown) => {
540
+ if (!request || typeof request !== "object" || !("version" in request) || request.version !== 1 || !("claim" in request) || typeof request.claim !== "function") return;
541
+ request.claim(routingName);
542
+ intercomIdClaimed = true;
543
+ });
544
+ }
545
+
519
546
  onRuntimeEvent("before_agent_start", async (event: unknown) => {
520
547
  if (!event || typeof event !== "object" || !("systemPrompt" in event) || typeof event.systemPrompt !== "string") return undefined;
521
548
  registerNativeSupervisorClientOnce();
522
- // The intercom target is a routing address and always wins; the display
523
- // name (agent + task excerpt, computed by the parent at launch) only
524
- // applies when the bridge is not addressing this child.
525
- const childSessionName = config.intercomSessionName || config.sessionName;
549
+ const childSessionName = intercomIdClaimed ? config.sessionName || routingName : routingName || config.sessionName;
526
550
  if (childSessionName && typeof pi.setSessionName === "function") {
527
551
  pi.setSessionName(childSessionName);
528
552
  }
@@ -21,7 +21,7 @@ export function formatChildToolDiagnostic(diagnostic: ChildToolDiagnostic, optio
21
21
  ...(diagnostic.missingMcpDirectTools?.length
22
22
  ? [`MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}.`]
23
23
  : []),
24
- "Agents that need MCP tools (`mcpDirectTools`, or MCP tools from an ambient adapter such as pi-mcp-adapter) or models from a provider extension must run as background children (`async: true`), which load the ambient extensions.",
24
+ "MCP tools require background children (`async: true`) because only they load ambient extensions.",
25
25
  "For extension tools a foreground child can load, add the provider path to `subagentOnlyExtensions` (child-only), `extensions`, or as a path-like entry in `tools`, while keeping each registered tool name in `tools`.",
26
26
  ].join("\n");
27
27
  }
@@ -29,7 +29,7 @@ export function formatChildToolDiagnostic(diagnostic: ChildToolDiagnostic, optio
29
29
  `${subject} requested unavailable child tools: ${diagnostic.missing.join(", ")}.`,
30
30
  "The `tools` field is a strict allowlist; it does not load extension code.",
31
31
  ...(diagnostic.missingMcpDirectTools?.length
32
- ? [`Resolved MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}. This indicates a host/pi-mcp-adapter registration problem, not a tool-call failure.`]
32
+ ? [`Resolved MCP direct tools missing from the child registry: ${diagnostic.missingMcpDirectTools.join(", ")}. Resolved names must match what the host or pi-mcp-adapter registers; check the MCP direct-tool registration before treating this as a tool-call failure.`]
33
33
  : []),
34
34
  "For extension tools, add the provider path to `subagentOnlyExtensions` (child-only), `extensions`, or as a path-like entry in `tools`, while keeping each registered tool name in `tools`.",
35
35
  "For MCP tools, verify the MCP adapter configuration and selected tool names. For builtin tools, verify the name against the installed Pi version.",
@@ -64,3 +64,24 @@ export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: numbe
64
64
  export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
65
65
  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.`;
66
66
  }
67
+
68
+ const TOOL_BUDGET_BLOCKED_MESSAGE = /^Tool budget hard limit reached after (\d+) tool calls? \(hard (\d+)\)\. The '([^']+)' tool is blocked so you can finalize from the context you already have\.$/;
69
+
70
+ /**
71
+ * Recognizes a hard-block reason generated by toolBudgetBlockedMessage for this exact budget
72
+ * and tool. A tool result only counts as a budget block when the entire message matches the
73
+ * runtime format and the embedded hard limit and tool name belong to this run; incidental
74
+ * occurrences of the phrase inside ordinary tool output are rejected.
75
+ */
76
+ export function isToolBudgetBlockedMessage(
77
+ budget: ResolvedToolBudget,
78
+ resultText: string,
79
+ blockedTool: string | undefined,
80
+ ): boolean {
81
+ const tool = blockedTool?.trim();
82
+ if (!tool) return false;
83
+ const match = TOOL_BUDGET_BLOCKED_MESSAGE.exec(resultText.trim());
84
+ if (!match) return false;
85
+ const [, blockedToolCount, hard, namedTool] = match;
86
+ return Number(hard) === budget.hard && Number(blockedToolCount) > budget.hard && namedTool === tool;
87
+ }
@@ -0,0 +1,73 @@
1
+ import type { Usage } from "../../shared/types.ts";
2
+
3
+ type UsageMessage = { role?: unknown; timestamp?: unknown; usage?: object };
4
+
5
+ const usageFields = ["input", "output", "cacheRead", "cacheWrite", "cost"] as const;
6
+ type UsageField = typeof usageFields[number];
7
+
8
+ const aliases: Record<Exclude<UsageField, "cost">, readonly string[]> = {
9
+ input: ["input", "inputTokens"],
10
+ output: ["output", "outputTokens"],
11
+ cacheRead: ["cacheRead", "cacheReadTokens"],
12
+ cacheWrite: ["cacheWrite", "cacheWriteTokens"],
13
+ };
14
+
15
+ function validNumber(value: unknown): number | undefined {
16
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
17
+ }
18
+
19
+ function fieldValue(usage: object | undefined, field: UsageField): number | undefined {
20
+ if (!usage) return undefined;
21
+ const values = usage as Record<string, unknown>;
22
+ if (field === "cost") {
23
+ const direct = validNumber(values.cost);
24
+ if (direct !== undefined) return direct;
25
+ const cost = values.cost;
26
+ return cost && typeof cost === "object" && !Array.isArray(cost)
27
+ ? validNumber((cost as { total?: unknown }).total)
28
+ : undefined;
29
+ }
30
+ for (const name of aliases[field]) {
31
+ const value = validNumber(values[name]);
32
+ if (value !== undefined) return value;
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ function validTimestamp(message: UsageMessage): string | number | undefined {
38
+ const value = message.timestamp;
39
+ if (typeof value === "number" && Number.isFinite(value)) return value;
40
+ if (typeof value === "string" && value.length > 0) return value;
41
+ return undefined;
42
+ }
43
+
44
+ export function reconcileAttemptUsage(live: Usage, messages: readonly UsageMessage[], baseline: number): Usage {
45
+ if (!Number.isInteger(baseline) || baseline < 0 || messages.length < baseline) return { ...live };
46
+
47
+ const persisted: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
48
+ const complete: Record<UsageField, boolean> = { input: true, output: true, cacheRead: true, cacheWrite: true, cost: true };
49
+ let previous: UsageMessage | undefined;
50
+ for (let index = baseline; index < messages.length; index++) {
51
+ const message = messages[index]!;
52
+ if (message.role === "assistant") {
53
+ const timestamp = validTimestamp(message);
54
+ const duplicate = previous?.role === "assistant" && timestamp !== undefined && validTimestamp(previous) === timestamp;
55
+ if (!duplicate) {
56
+ persisted.turns++;
57
+ for (const field of usageFields) {
58
+ const value = fieldValue(message.usage, field);
59
+ if (value === undefined) complete[field] = false;
60
+ else persisted[field] += value;
61
+ }
62
+ }
63
+ }
64
+ previous = message;
65
+ }
66
+ if (persisted.turns === 0) return { ...live };
67
+
68
+ const reconciled = { ...live, turns: persisted.turns };
69
+ for (const field of usageFields) {
70
+ if (complete[field] && Number.isFinite(persisted[field])) reconciled[field] = persisted[field];
71
+ }
72
+ return reconciled;
73
+ }
@@ -20,7 +20,7 @@ const WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
20
20
  const WORKTREE_COMMAND_OUTPUT_MAX_BYTES = 128 * 1024;
21
21
  const WORKTRUNK_COMMAND = process.platform === "win32" ? "git" : "wt";
22
22
  const WORKTRUNK_ARG_PREFIX = process.platform === "win32" ? ["wt"] : [];
23
- export const MACHINE_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--default-prefix", "--line-prefix=", "--no-relative"] as const;
23
+ export const MACHINE_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", "--line-prefix=", "--no-relative"] as const;
24
24
  const MACHINE_PATCH_OPTIONS = [...MACHINE_DIFF_OPTIONS, "--binary"] as const;
25
25
  const PATCH_VALIDATION_OPTIONS = ["apply", "--check", "--cached", "--reverse", "--binary", "--whitespace=nowarn"] as const;
26
26
 
@@ -439,9 +439,14 @@ function shortWorktreeHash(value: string): string {
439
439
  }
440
440
 
441
441
  function truncateUtf8(value: string, maxBytes: number): string {
442
- if (Buffer.byteLength(value, "utf-8") <= maxBytes) return value;
443
- const truncated = Buffer.from(value, "utf-8").subarray(0, maxBytes).toString("utf-8");
444
- return /[\uD800-\uDFFF]$/u.test(truncated) ? truncated.slice(0, -1) : truncated;
442
+ const bytes = Buffer.from(value, "utf-8");
443
+ if (bytes.length <= maxBytes) return value;
444
+ // Back off to a code-point boundary before decoding: cutting mid-sequence
445
+ // emits U+FFFD (3 bytes per dangling byte), which can push the re-encoded
446
+ // result beyond maxBytes (e.g. a 256-byte cap yields a 258-byte string).
447
+ let end = maxBytes;
448
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1;
449
+ return bytes.subarray(0, end).toString("utf-8");
445
450
  }
446
451
 
447
452
  /** Convert an arbitrary label to a single safe filesystem/branch component. */
@@ -743,13 +748,35 @@ export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, inde
743
748
  function linkNodeModulesIfPresent(toplevel: string, worktreePath: string): boolean {
744
749
  const nodeModulesPath = path.join(toplevel, "node_modules");
745
750
  const nodeModulesLinkPath = path.join(worktreePath, "node_modules");
746
- if (!fs.existsSync(nodeModulesPath) || fs.existsSync(nodeModulesLinkPath)) return false;
751
+ const hasDirectoryEntry = (candidate: string): boolean => {
752
+ try { fs.lstatSync(candidate); return true; }
753
+ catch (error) {
754
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
755
+ throw error;
756
+ }
757
+ };
747
758
  try {
748
- fs.symlinkSync(nodeModulesPath, nodeModulesLinkPath);
759
+ if (hasDirectoryEntry(nodeModulesLinkPath)) return false;
760
+ let sourceRealPath: string;
761
+ try {
762
+ if (!fs.statSync(nodeModulesPath).isDirectory()) throw new Error("source node_modules is not a directory");
763
+ sourceRealPath = fs.realpathSync.native(nodeModulesPath);
764
+ } catch (error) {
765
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
766
+ throw error;
767
+ }
768
+ fs.symlinkSync(nodeModulesPath, nodeModulesLinkPath, process.platform === "win32" ? "junction" : "dir");
769
+ if (!fs.lstatSync(nodeModulesLinkPath).isSymbolicLink()
770
+ || fs.realpathSync.native(nodeModulesLinkPath) !== sourceRealPath) {
771
+ throw new Error("created link does not resolve to the source node_modules");
772
+ }
749
773
  return true;
750
- } catch {
751
- // Symlink creation is optional (e.g., unsupported filesystems on CI runners).
752
- return false;
774
+ } catch (error) {
775
+ const code = error instanceof Error && "code" in error && typeof error.code === "string" ? `${error.code}: ` : "";
776
+ throw new Error(
777
+ `failed to link node_modules from ${nodeModulesPath} to ${nodeModulesLinkPath}: ${code}${error instanceof Error ? error.message : String(error)}`,
778
+ { cause: error },
779
+ );
753
780
  }
754
781
  }
755
782
 
@@ -13,8 +13,10 @@ import { PROMPT_REDACTED } from "./utils.ts";
13
13
  * rendering the parent stream can label each child row.
14
14
  *
15
15
  * The name is display-only metadata. When the intercom bridge is active the
16
- * child keeps its machine intercom target as the session name instead — that
17
- * name is a routing address and must win (see subagent-prompt-runtime).
16
+ * child claims its machine intercom target as its pi-intercom session ID and
17
+ * keeps this readable name. With a pi-intercom that does not support the claim,
18
+ * the target stays the session name because it routes by name
19
+ * (see subagent-prompt-runtime).
18
20
  */
19
21
 
20
22
  /** Longest task excerpt kept in the name; the full string is capped below. */
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Opt-in feature groups an operator can remove from the parent-facing `subagent` tool.
3
+ * Groups own parameters and actions that enabled features do not need, so hiding them
4
+ * cannot remove a field that enabled behavior still needs. `preflight` is the one shared
5
+ * parameter: it is script-only, so `workflow-scripts` removes it too. Per-call options
6
+ * disable only the per-call override; configured defaults keep applying.
7
+ */
8
+ export const SUBAGENT_FEATURES = {
9
+ "agent-management": {
10
+ actions: ["create", "update", "delete", "eject", "disable", "enable", "reset", "refine", "refine.show", "refine.rollback"],
11
+ params: ["config"],
12
+ },
13
+ watchdog: {
14
+ actions: ["watchdog.status", "watchdog.check", "watchdog.configure", "watchdog.recommend-model"],
15
+ params: ["scope", "target", "thinking"],
16
+ },
17
+ panes: {
18
+ actions: ["inspector.open", "inspector.command", "inspector.status", "inspector.close", "project.open", "project.status", "project.close"],
19
+ params: ["focus"],
20
+ },
21
+ missions: {
22
+ actions: ["mission.create", "mission.list", "mission.show", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close"],
23
+ params: ["mission", "missionUpdate", "missionStatus", "missionScope", "missionId", "runMode", "runStatus", "summary"],
24
+ },
25
+ "lane-management": {
26
+ actions: ["lane.status", "lane.recordMerge", "lane.recordSupersession", "worktree.discard", "worktree.cleanup"],
27
+ params: ["handoffPath", "laneId", "merge", "supersession", "repo", "planId"],
28
+ },
29
+ "spawn-budget-grants": { actions: ["grant-spawn-budget"], params: ["additional"] },
30
+ preflight: { actions: [], params: ["preflight"] },
31
+ "lane-metadata": { actions: [], params: ["lane"] },
32
+ gates: { actions: [], params: ["gate"] },
33
+ "usage-budgets": { actions: [], params: ["usageBudget"] },
34
+ "tool-budgets": { actions: [], params: ["toolBudget"] },
35
+ "control-overrides": { actions: [], params: ["control"] },
36
+ "extension-bindings": { actions: [], params: ["extensionBindings"] },
37
+ "external-machines": { actions: [], params: ["machine"] },
38
+ "workflow-scripts": { actions: ["validate"], params: ["workflow", "args", "preflight", "globalConcurrencyLimit", "maxSubagentSpawnsPerRun"] },
39
+ } as const satisfies Record<string, { actions: readonly string[]; params: readonly string[] }>;
40
+
41
+ export type SubagentFeature = keyof typeof SUBAGENT_FEATURES;
42
+
43
+ /** Schedules are turned off by `scheduledRuns.enabled: false`, not by `disabledFeatures`. */
44
+ export type SubagentSurfaceFeature = SubagentFeature | "schedules";
45
+
46
+ const SCHEDULE_SURFACE = {
47
+ actions: ["schedule.create", "schedule.list", "schedule.show", "schedule.history", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"],
48
+ params: ["name", "at", "every", "sessionOnly", "quiet", "on", "timezone", "overlap", "catchUp"],
49
+ } as const;
50
+
51
+ export function validateDisabledFeatures(value: unknown): void {
52
+ if (value === undefined) return;
53
+ if (!Array.isArray(value)) throw new Error("config.disabledFeatures must be an array of feature names");
54
+ const seen = new Set<string>();
55
+ for (const entry of value) {
56
+ if (entry === "schedules") throw new Error(`config.disabledFeatures does not accept "schedules"; set config.scheduledRuns.enabled to false instead`);
57
+ if (typeof entry !== "string" || !Object.hasOwn(SUBAGENT_FEATURES, entry)) {
58
+ throw new Error(`config.disabledFeatures entry ${JSON.stringify(entry)} is not one of: ${Object.keys(SUBAGENT_FEATURES).join(", ")}`);
59
+ }
60
+ if (seen.has(entry)) throw new Error(`config.disabledFeatures lists "${entry}" more than once`);
61
+ seen.add(entry);
62
+ }
63
+ }
64
+
65
+ /** Disabled features, and each disabled parameter and action mapped to the setting that disabled it. */
66
+ export interface DisabledFeatureSurface {
67
+ features: ReadonlySet<SubagentSurfaceFeature>;
68
+ params: ReadonlyMap<string, string>;
69
+ actions: ReadonlyMap<string, string>;
70
+ }
71
+
72
+ interface FeatureConfig {
73
+ disabledFeatures?: readonly SubagentFeature[];
74
+ scheduledRuns?: { enabled?: boolean };
75
+ }
76
+
77
+ function featureSurface(feature: SubagentSurfaceFeature): { actions: readonly string[]; params: readonly string[]; disabledBy: string } {
78
+ if (feature === "schedules") return { ...SCHEDULE_SURFACE, disabledBy: "scheduledRuns.enabled=false" };
79
+ return { ...SUBAGENT_FEATURES[feature], disabledBy: `disabledFeatures "${feature}"` };
80
+ }
81
+
82
+ export function resolveDisabledFeatureSurface(config: FeatureConfig): DisabledFeatureSurface {
83
+ const features = new Set<SubagentSurfaceFeature>(config.disabledFeatures);
84
+ if (config.scheduledRuns?.enabled === false) features.add("schedules");
85
+ const params = new Map<string, string>();
86
+ const actions = new Map<string, string>();
87
+ for (const feature of features) {
88
+ const surface = featureSurface(feature);
89
+ // A parameter shared with workflow-scripts is always attributed to workflow-scripts,
90
+ // whatever order the config lists the features in.
91
+ for (const param of surface.params) if (feature === "workflow-scripts" || !params.has(param)) params.set(param, surface.disabledBy);
92
+ for (const action of surface.actions) actions.set(action, surface.disabledBy);
93
+ }
94
+ return { features, params, actions };
95
+ }
96
+
97
+ /** Returns why a request uses a disabled feature, or undefined when every requested field is enabled. */
98
+ export function disabledFeatureUseError(request: object, surface: DisabledFeatureSurface, label = "subagent"): string | undefined {
99
+ const params = request as Record<string, unknown>;
100
+ const action = typeof params.action === "string" ? params.action.trim() : undefined;
101
+ const disabledAction = action === undefined ? undefined : surface.actions.get(action);
102
+ if (disabledAction) return `${label} action '${action}' is disabled by config ${disabledAction}.`;
103
+ for (const [param, disabledBy] of surface.params) {
104
+ if (params[param] !== undefined) return `${label} option '${param}' is disabled by config ${disabledBy}.`;
105
+ }
106
+ // workflowScript is the internal carrier for slash, prompt-workflow, RPC, and scheduled scripts.
107
+ // Callers check the original request, before the package lowers chain/tasks into its own script.
108
+ if (params.workflowScript !== undefined && surface.features.has("workflow-scripts")) {
109
+ return `${label} workflow scripts are disabled by config ${featureSurface("workflow-scripts").disabledBy}.`;
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ /** Lists what config disabled, for prepending to static reference docs that describe the full tool. */
115
+ export function disabledFeatureNotice(surface: DisabledFeatureSurface): string | undefined {
116
+ if (surface.features.size === 0) return undefined;
117
+ const lines = [...surface.features].map((feature) => {
118
+ const { actions, params, disabledBy } = featureSurface(feature);
119
+ const parts = [`options ${params.join(", ")}`, ...(actions.length > 0 ? [`actions ${actions.join(", ")}`] : [])];
120
+ return `- ${disabledBy}: ${parts.join("; ")}`;
121
+ });
122
+ return `Disabled by config in this session. The reference below still lists these, but calls that use them are rejected:\n${lines.join("\n")}`;
123
+ }
@@ -1,11 +1,24 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
+ /**
4
+ * Declares a tool to the model but keeps it out of codemode scripts and other `ctx.executeTool()`
5
+ * callers. These tools need model-issued calls: nested calls hide their progress, block the script
6
+ * on supervisor replies, and drop `terminate`. Pi 0.99 reads `exposure`; the pinned SDK types
7
+ * predate it and older hosts ignore it.
8
+ */
9
+ export const MODEL_ONLY_TOOL = { exposure: "model-only" } as const;
10
+
3
11
  /** Pi exposes replaced extension contexts as ordinary Errors without a stable code. */
4
12
  export function isStaleExtensionContextError(error: unknown): boolean {
5
13
  return error instanceof Error
6
14
  && /extension ctx is stale|extension context no longer active|stale after session replacement or reload/i.test(error.message);
7
15
  }
8
16
 
17
+ /** Pi throws this from action methods while extensions are still loading, before it binds the runtime. */
18
+ export function isUnboundExtensionRuntimeError(error: unknown): boolean {
19
+ return error instanceof Error && /extension runtime not initialized/i.test(error.message);
20
+ }
21
+
9
22
  /** Run a synchronous operation against a cached UI context without leaking replacement errors. */
10
23
  export function withCachedUiContext<T>(
11
24
  ctx: ExtensionContext | null | undefined,
@@ -16,6 +16,8 @@ interface BranchSessionEntry {
16
16
  cwd?: string;
17
17
  parentId?: string | null;
18
18
  timestamp?: string;
19
+ targetId?: string;
20
+ replacement?: { content?: unknown } | null;
19
21
  message?: {
20
22
  role?: string;
21
23
  content?: unknown;
@@ -110,11 +112,16 @@ function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"],
110
112
 
111
113
  function sanitizeUnsafeThinkingBlocks(entries: BranchSessionEntry[]): boolean {
112
114
  let sanitized = false;
115
+ const entriesById = new Map(entries.flatMap((entry) => entry.id ? [[entry.id, entry] as const] : []));
113
116
  for (const entry of entries) {
114
- if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
115
- const filtered = entry.message.content.filter((block) => !isUnsafeAnthropicThinkingBlock(entry.message, block));
116
- if (filtered.length === entry.message.content.length) continue;
117
- entry.message.content = filtered;
117
+ const targetMessage = entry.type === "context_edit" && entry.targetId
118
+ ? entriesById.get(entry.targetId)?.message
119
+ : entry.message;
120
+ const contentOwner = entry.type === "context_edit" ? entry.replacement : targetMessage;
121
+ if (targetMessage?.role !== "assistant" || !contentOwner || !Array.isArray(contentOwner.content)) continue;
122
+ const filtered = contentOwner.content.filter((block) => !isUnsafeAnthropicThinkingBlock(targetMessage, block));
123
+ if (filtered.length === contentOwner.content.length) continue;
124
+ contentOwner.content = filtered;
118
125
  sanitized = true;
119
126
  }
120
127
  return sanitized;
@@ -55,6 +55,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
55
55
  tools: agent.tools,
56
56
  excludeTools: agent.excludeTools,
57
57
  allowNestedSubagents: agent.allowNestedSubagents,
58
+ allowedAgents: agent.allowedAgents,
58
59
  mcpDirectTools: agent.mcpDirectTools,
59
60
  extensions: agent.extensions,
60
61
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
@@ -72,7 +73,6 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
72
73
  acceptanceRole: agent.acceptanceRole,
73
74
  interactive: agent.interactive,
74
75
  maxSubagentDepth: agent.maxSubagentDepth,
75
- completionGuard: agent.completionGuard,
76
76
  toolBudget: agent.toolBudget,
77
77
  sandbox: agent.sandbox,
78
78
  permissionProfile: agent.permissionProfile,
@@ -60,6 +60,15 @@ export function resolveEffectiveThinking(model: string | undefined, configThinki
60
60
  return THINKING_LEVELS.find((level) => level === configThinking);
61
61
  }
62
62
 
63
+ /** The recorded thinking level of one child: the first known level among the places it is recorded. */
64
+ export function childThinkingLevel(...sources: Array<{ thinking?: string } | undefined>): ThinkingLevel | undefined {
65
+ for (const source of sources) {
66
+ const level = THINKING_LEVELS.find((candidate) => candidate === source?.thinking);
67
+ if (level) return level;
68
+ }
69
+ return undefined;
70
+ }
71
+
63
72
  export function splitKnownThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
64
73
  const colonIdx = model.lastIndexOf(":");
65
74
  if (colonIdx === -1) return { baseModel: model, thinkingSuffix: "" };