@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -18,25 +18,27 @@ import {
18
18
  SessionManager,
19
19
  SettingsManager,
20
20
  } from "@earendil-works/pi-coding-agent";
21
- import { type AdvisorStatus, attachAdvisorStatusCleanup, subscribeAdvisorStatus } from "./advisor-status.js";
22
- import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
23
- import { runAsSubagentProcess, runInChildSessionContext, runWithAdvisorBind } from "./child-context.js";
24
- import { shutdownChildSession } from "./child-session-shutdown.js";
25
- import { buildParentContext, extractText } from "./context.js";
26
- import { DEFAULT_AGENTS } from "./default-agents.js";
27
- import { detectEnv } from "./env.js";
28
- import { isPinFallback, resolvePinnedModel } from "./invocation-config.js";
29
- import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
30
- import { createNestedSubagentTools, getMaxSubagentDepth, type NestedAgentManager } from "./nested-tools.js";
31
- import { buildAgentPrompt, type PromptExtras } from "./prompts.js";
32
- import { abortChildSession, beginChildRequest, ChildRecovery, promptWithRecovery } from "./recovery.js";
33
- import { preloadSkills } from "./skill-loader.js";
34
- import { inventoryRecoveryOwner, resolveStandaloneModel } from "./standalone-fallback.js";
35
- import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from "./structured-output.js";
36
- import type { SubagentType, ThinkingLevel } from "./types.js";
37
- import { attachToolProgress, releaseToolProgress } from "./ui/tool-progress.js";
38
- import type { LifetimeUsage } from "./usage.js";
39
- import type { CompiledSchema } from "./workflow/json-schema.js";
21
+ import { type AdvisorStatus, attachAdvisorStatusCleanup, subscribeAdvisorStatus } from "./advisor-status.ts";
22
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType, KNOWN_BUILTIN_TOOL_NAMES } from "./agent-types.ts";
23
+ import { runAsSubagentProcess, runInChildSessionContext, runWithAdvisorBind } from "./child-context.ts";
24
+ import { type ChildShutdownOutcome, shutdownChildSession } from "./child-session-shutdown.ts";
25
+ import { buildParentContext, extractText } from "./context.ts";
26
+ import { DEFAULT_AGENTS } from "./default-agents.ts";
27
+ import { detectEnv } from "./env.ts";
28
+ import { isForceMainModel } from "./force-main-model.ts";
29
+ import { isPinFallback, resolvePinnedModel } from "./invocation-config.ts";
30
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.ts";
31
+ import { type ArchivedReportReader, createNestedSubagentTools, getMaxSubagentDepth, type NestedAgentManager } from "./nested-tools.ts";
32
+ import { buildAgentPrompt, type PromptExtras } from "./prompts.ts";
33
+ import { abortChildSession, beginChildRequest, ChildRecovery, promptWithRecovery } from "./recovery.ts";
34
+ import { SESSION_OWNERSHIP_ENTRY_TYPE, type SessionOwnershipData } from "./report-store.ts";
35
+ import { preloadSkills } from "./skill-loader.ts";
36
+ import { inventoryRecoveryOwner, resolveStandaloneModel } from "./standalone-fallback.ts";
37
+ import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from "./structured-output.ts";
38
+ import type { AgentConfig, SubagentType, ThinkingLevel } from "./types.ts";
39
+ import { attachToolProgress, releaseToolProgress } from "./ui/tool-progress.ts";
40
+ import type { LifetimeUsage } from "./usage.ts";
41
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
40
42
 
41
43
  /**
42
44
  * Tool names registered by THIS extension. Single source of truth so the
@@ -333,6 +335,23 @@ export function getDefaultMaxTurns(): number | undefined { return defaultMaxTurn
333
335
  /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
334
336
  export function setDefaultMaxTurns(n: number | undefined): void { defaultMaxTurns = normalizeMaxTurns(n); }
335
337
 
338
+ /**
339
+ * Whether tool/RPC callers may impose their own per-call turn limit.
340
+ *
341
+ * Off by default: a configured agent-file or project budget is authoritative,
342
+ * and a caller's `max_turns` is ignored. Turn it on to restore the historical
343
+ * caller-cap behaviour. This governs only the model-facing/tool and RPC
344
+ * surfaces — `RunOptions.maxTurns` stays an internal API for in-tree callers
345
+ * (the manager, scheduler, nested delegation) with an explicitly configured
346
+ * budget, and `resolveEffectiveMaxTurns` keeps honoring it.
347
+ */
348
+ let allowPerCallTurnLimits = false;
349
+
350
+ /** Whether callers may impose per-call turn limits. Default false. */
351
+ export function getAllowPerCallTurnLimits(): boolean { return allowPerCallTurnLimits; }
352
+ /** Set whether callers may impose per-call turn limits. */
353
+ export function setAllowPerCallTurnLimits(b: boolean): void { allowPerCallTurnLimits = b; }
354
+
336
355
  /**
337
356
  * The turn limit a run of `type` will actually enforce: an explicit value if the
338
357
  * caller supplied one, else the agent's own `max_turns`, else the project
@@ -360,8 +379,8 @@ export function getRememberAgents(): boolean { return rememberAgents; }
360
379
  /** Set whether subagent sessions are persisted by default. */
361
380
  export function setRememberAgents(b: boolean): void { rememberAgents = b; }
362
381
 
363
- /** Additional turns allowed after the soft limit steer message. */
364
- let graceTurns = 5;
382
+ /** Additional turns allowed after the soft limit steer message. Default 10. */
383
+ let graceTurns = 10;
365
384
 
366
385
  /** Get the grace turns value. */
367
386
  export function getGraceTurns(): number { return graceTurns; }
@@ -403,6 +422,19 @@ export interface ToolActivity {
403
422
  export interface RunOptions {
404
423
  /** ExtensionAPI instance — used for pi.exec() instead of execSync. */
405
424
  pi: ExtensionAPI;
425
+ /**
426
+ * Internal, manager-only: the agent definition admitted with this run.
427
+ *
428
+ * The manager snapshots this from its registry BEFORE a spawn is queued or
429
+ * starts awaiting work, and callers that resolve a definition against a
430
+ * scoped registry pass their own snapshot. The runner reads prompt, tools,
431
+ * model, memory, session and nesting policy from THIS object, never from
432
+ * `getAgentConfig`/`getToolNamesForType` once the run has suspended: a
433
+ * reload during a queued wait or a worktree copy must not change the agent
434
+ * that was admitted. Undefined keeps the historical direct-call behaviour
435
+ * (including the unknown-type general-purpose fallback).
436
+ */
437
+ agentDefinition?: AgentConfig;
406
438
  /** Manager-assigned id; suffixes session name to disambiguate parallel spawns (e.g. `Explore#a1b2c3d4`). */
407
439
  agentId?: string;
408
440
  model?: Model<any>;
@@ -463,6 +495,19 @@ export interface RunOptions {
463
495
  /** Called on streaming text deltas from the assistant response. */
464
496
  onTextDelta?: (delta: string, fullText: string) => void;
465
497
  onSessionCreated?: (session: AgentSession) => void;
498
+ /**
499
+ * Internal, manager-only: fires synchronously as soon as `createAgentSession`
500
+ * returns, BEFORE extension binding. The manager registers the allocated SDK
501
+ * instance and its plain provenance so a bind failure or a hang during
502
+ * `session_start` cannot make teardown look complete. It must not steer or
503
+ * announce a ready session here — `onSessionCreated` remains that boundary.
504
+ */
505
+ onSessionAllocated?: (session: AgentSession) => void;
506
+ /**
507
+ * Internal, manager-only: reports the explicit outcome of a partial-startup
508
+ * teardown (currently a bind failure) without rejecting the run's error path.
509
+ */
510
+ onSessionTeardown?: (session: AgentSession, outcome: ChildShutdownOutcome) => void;
466
511
  /** Child-local advisor runtime telemetry; independent of the child UI. */
467
512
  onAdvisorStatus?: (status: AdvisorStatus) => void;
468
513
  /** Refresh effective model metadata after recovery switches, including on resume. */
@@ -499,7 +544,15 @@ export interface RunOptions {
499
544
  parentAgentId: string;
500
545
  depth: number;
501
546
  maxSubagentDepth?: number;
547
+ /** Async parent-scoped durable-report reader for evicted children. */
548
+ archive?: ArchivedReportReader;
502
549
  };
550
+ /** Stable root session id, pinned by the manager for ownership provenance. */
551
+ rootSessionId?: string;
552
+ /** Stable root project cwd — never the worktree copy. */
553
+ rootCwd?: string;
554
+ /** Root session's pi JSONL file, when it exists. */
555
+ rootSessionFile?: string;
503
556
  }
504
557
 
505
558
  export interface RunResult {
@@ -612,7 +665,7 @@ function finalTurnError(session: AgentSession, startIndex = 0, finalMessage?: As
612
665
  */
613
666
  function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () => void {
614
667
  if (!signal) return () => {};
615
- const onAbort = () => { void abortChildSession(session); };
668
+ const onAbort = () => { void abortChildSession(session).catch(() => {}); /* teardown errors surface through the run */ };
616
669
  if (signal.aborted) onAbort();
617
670
  else signal.addEventListener("abort", onAbort, { once: true });
618
671
  return () => signal.removeEventListener("abort", onAbort);
@@ -657,25 +710,48 @@ async function runAgentSession(
657
710
  recovery: ChildRecovery,
658
711
  retainAdvisorStatus: (session: AgentSession) => void,
659
712
  ): Promise<RunResult> {
660
- const config = getConfig(type);
661
- const agentConfig = getAgentConfig(type);
713
+ // Admitted definition is the run's sole policy source. Direct runAgent
714
+ // callers without one keep the historical registry reads — captured before
715
+ // the first await below, so nothing is re-read after a suspension.
716
+ const admittedDefinition = options.agentDefinition;
717
+ const agentConfig = admittedDefinition ?? getAgentConfig(type);
718
+ const config = admittedDefinition === undefined
719
+ ? getConfig(type)
720
+ : {
721
+ displayName: admittedDefinition.displayName ?? admittedDefinition.name,
722
+ color: admittedDefinition.color,
723
+ description: admittedDefinition.description,
724
+ builtinToolNames: admittedDefinition.builtinToolNames ?? BUILTIN_TOOL_NAMES,
725
+ extensions: admittedDefinition.extensions,
726
+ excludeExtensions: admittedDefinition.excludeExtensions,
727
+ skills: admittedDefinition.skills,
728
+ promptMode: admittedDefinition.promptMode,
729
+ };
662
730
  if (agentConfig?.advisor === false) {
663
731
  options.onAdvisorStatus?.({ state: "off", models: [], reviews: 0 });
664
732
  }
665
733
  // Capture the standalone default before any await; resume keeps this identity
666
734
  // even if the parent context or its model object later changes.
667
735
  const standaloneParentModel = ctx.model;
668
- const fallbackModel = agentConfig?.fallbackModel
736
+ // Under `/subagents off` an agent file's `fallback_model` is one more model
737
+ // choice that gives way: standalone recovery still happens, onto the main model.
738
+ const configuredFallback = isForceMainModel() ? undefined : agentConfig?.fallbackModel;
739
+ const fallbackModel = configuredFallback
669
740
  ?? (standaloneParentModel ? `${standaloneParentModel.provider}/${standaloneParentModel.id}` : undefined);
670
741
  // Every entry path reaches this gate, including RPC, nested, mention and
671
- // scheduled spawns. A pre-resolved caller model cannot bypass an agent pin.
742
+ // scheduled spawns. A pre-resolved caller model cannot bypass an agent pin —
743
+ // except under `/subagents off`, where pins and overrides alike give way to
744
+ // the parent's model. A nested child's parent is itself twinned, so the main
745
+ // model propagates down the whole tree.
672
746
  // Built-in defaults (Explore/Plan) fall back to the parent model with a
673
747
  // notice when their pin names an unavailable provider; user-authored pins
674
748
  // stay strict. The notice is folded into the prompt extras below so it is
675
749
  // visible in the child's context rather than silently dropped.
676
- const { model, notice: pinFallbackNotice } = resolveDefaultModel(options.model ?? ctx.model, ctx.modelRegistry, agentConfig?.model, {
677
- isBuiltInDefault: agentConfig?.isDefault === true,
678
- });
750
+ const { model, notice: pinFallbackNotice } = isForceMainModel()
751
+ ? { model: ctx.model, notice: undefined }
752
+ : resolveDefaultModel(options.model ?? ctx.model, ctx.modelRegistry, agentConfig?.model, {
753
+ isBuiltInDefault: agentConfig?.isDefault === true,
754
+ });
679
755
 
680
756
  // Resolve working directory: worktree override > parent cwd
681
757
  const effectiveCwd = options.cwd ?? ctx.cwd;
@@ -709,7 +785,11 @@ async function runAgentSession(
709
785
  }
710
786
  }
711
787
 
712
- let toolNames = getToolNamesForType(type);
788
+ let toolNames = admittedDefinition === undefined
789
+ ? getToolNamesForType(type)
790
+ : admittedDefinition.builtinToolNames === undefined
791
+ ? [...BUILTIN_TOOL_NAMES]
792
+ : [...admittedDefinition.builtinToolNames];
713
793
 
714
794
  // Persistent memory: detect write capability and branch accordingly.
715
795
  // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
@@ -860,7 +940,7 @@ async function runAgentSession(
860
940
  // this produced a silently broken agent (#75) — pi-mono accepted the bogus name
861
941
  // into the allowlist, then dropped it at registration with no signal back.
862
942
  if (agentConfig?.builtinToolNames?.length) {
863
- const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
943
+ const knownBuiltins = new Set(KNOWN_BUILTIN_TOOL_NAMES);
864
944
  for (const name of agentConfig.builtinToolNames) {
865
945
  if (!knownBuiltins.has(name)) {
866
946
  options.onToolActivity?.({
@@ -953,6 +1033,7 @@ async function runAgentSession(
953
1033
  maxSubagentDepth: effectiveMaxDepth,
954
1034
  allowedSubagents: agentConfig.allowedSubagents,
955
1035
  configCwd,
1036
+ ...(nestedRuntime.archive === undefined ? {} : { archive: nestedRuntime.archive }),
956
1037
  })
957
1038
  : [];
958
1039
  const nestedToolNames = new Set(nestedTools.map(tool => tool.name));
@@ -1013,9 +1094,12 @@ async function runAgentSession(
1013
1094
  if (noExtensions) {
1014
1095
  // Strict allowlist: built-ins the agent asked for, plus any opt-in nested
1015
1096
  // tools (whose names would otherwise be dropped as EXCLUDED_TOOL_NAMES).
1097
+ // Pi 1.1 reads `+x`/`-x` entries as edits to the user's defaultTools (and
1098
+ // throws when they are mixed with names) and `*` as a pattern; none is a
1099
+ // tool name, and the unknown-name warning above already reported them.
1016
1100
  sessionTools = [
1017
1101
  ...toolNames.filter(
1018
- (t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t),
1102
+ (t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t) && !/^[+-]|\*/.test(t),
1019
1103
  ),
1020
1104
  ...[...nestedToolNames].filter((t) => !disallowedSet?.has(t)),
1021
1105
  // Not filtered through `disallowedSet`, unlike the nested tools above:
@@ -1066,6 +1150,39 @@ async function runAgentSession(
1066
1150
  })
1067
1151
  : SessionManager.inMemory(effectiveCwd);
1068
1152
 
1153
+ // Ownership tag, written before the session binds extensions or runs its
1154
+ // first prompt. A cleanup can therefore prove a child pi history is ours
1155
+ // from the file itself, and record the root provenance once — never the
1156
+ // parent's main conversation file. Custom entries are excluded from model
1157
+ // context by the SDK; the in-memory variant leaves nothing on disk, which
1158
+ // preserves the explicit no-session intent.
1159
+ const ownershipRootSessionId = options.rootSessionId ?? ctx.sessionManager?.getSessionId?.();
1160
+ const ownershipRootCwd = options.rootCwd ?? ctx.cwd;
1161
+ const ownershipRootSessionFile = options.rootSessionFile ?? ctx.sessionManager?.getSessionFile?.();
1162
+ const ownershipChildFile = sessionManager.getSessionFile?.();
1163
+ if (
1164
+ options.agentId !== undefined
1165
+ && ownershipRootSessionId !== undefined
1166
+ && ownershipRootCwd !== undefined
1167
+ && ownershipChildFile !== ownershipRootSessionFile
1168
+ ) {
1169
+ const ownership: SessionOwnershipData = {
1170
+ version: 1,
1171
+ agentId: options.agentId,
1172
+ rootSessionId: ownershipRootSessionId,
1173
+ rootCwd: ownershipRootCwd,
1174
+ ...(ownershipRootSessionFile === undefined ? {} : { rootSessionFile: ownershipRootSessionFile }),
1175
+ childSessionId: sessionManager.getSessionId(),
1176
+ };
1177
+ try {
1178
+ sessionManager.appendCustomEntry(SESSION_OWNERSHIP_ENTRY_TYPE, ownership);
1179
+ } catch (error) {
1180
+ // A read-only or already-closed history must not take the spawn down;
1181
+ // cleanup will simply treat the file as unowned.
1182
+ console.warn("[pi-subagents] could not record child-session ownership:", error);
1183
+ }
1184
+ }
1185
+
1069
1186
  // Pi 0.80.8 replaced createAgentSession's modelRegistry option with
1070
1187
  // modelRuntime, but ExtensionContext still exposes only the registry facade.
1071
1188
  // Pass both so the full supported Pi range retains the parent's providers.
@@ -1105,6 +1222,10 @@ async function runAgentSession(
1105
1222
  }
1106
1223
 
1107
1224
  const { session } = await runInChildSessionContext(() => createAgentSession(sessionOpts));
1225
+ // Before any binding or ready announcement: the manager now owns the plain
1226
+ // identity of this allocated instance, so its teardown outcome cannot be
1227
+ // lost if `session_start` fails or hangs.
1228
+ options.onSessionAllocated?.(session);
1108
1229
  attachToolProgress(session);
1109
1230
  const dispose = session.dispose?.bind(session);
1110
1231
  if (dispose) session.dispose = () => { releaseToolProgress(session); dispose(); };
@@ -1142,8 +1263,15 @@ async function runAgentSession(
1142
1263
  })), bindSignal);
1143
1264
  } catch (error) {
1144
1265
  // Bind may have run some session_start handlers already. Emit shutdown
1145
- // before disposal so their timers/watchers cannot outlive this child.
1146
- await shutdownChildSession(session);
1266
+ // before disposal so their timers/watchers cannot outlive this child. The
1267
+ // outcome is forwarded to the manager: this runs before onSessionCreated,
1268
+ // so without the handoff the allocated instance would simply disappear.
1269
+ const outcome = await shutdownChildSession(session);
1270
+ try {
1271
+ options.onSessionTeardown?.(session, outcome);
1272
+ } catch (notifyError) {
1273
+ console.warn("[pi-subagents] partial-startup teardown handoff failed:", notifyError);
1274
+ }
1147
1275
  throw error;
1148
1276
  }
1149
1277
 
@@ -1168,7 +1296,7 @@ async function runAgentSession(
1168
1296
 
1169
1297
  // Track turns for graceful max_turns enforcement
1170
1298
  let turnCount = 0;
1171
- const maxTurns = resolveEffectiveMaxTurns(type, options.maxTurns);
1299
+ const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
1172
1300
  let softLimitReached = false;
1173
1301
  let aborted = false;
1174
1302
 
@@ -1183,7 +1311,7 @@ async function runAgentSession(
1183
1311
  session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
1184
1312
  } else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
1185
1313
  aborted = true;
1186
- void abortChildSession(session, "turn_limit");
1314
+ void abortChildSession(session, "turn_limit").catch(() => {}); // the run reports the abort itself
1187
1315
  }
1188
1316
  }
1189
1317
  }
@@ -5,22 +5,39 @@
5
5
  * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
6
  */
7
7
 
8
- import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
9
- import { DEFAULT_AGENTS } from "./default-agents.js";
10
- import type { AgentConfig } from "./types.js";
8
+ import { createCodingTools, createPowerShellTool, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
9
+ import { DEFAULT_AGENTS } from "./default-agents.ts";
10
+ import type { AgentConfig } from "./types.ts";
11
11
 
12
12
  /**
13
- * All known built-in tool names, derived from pi's own tool factories rather
14
- * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
15
- * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
16
- * read/grep/find/ls; their de-duplicated union is the 7 built-ins
17
- * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
18
- * operations we never invoke here — we read each tool's `.name` and discard it.
13
+ * Every built-in tool name pi's registry knows, on every platform — the set
14
+ * `tools:` frontmatter is validated against. Derived from pi's own tool
15
+ * factories rather than hardcoded so the set tracks pi-mono if it
16
+ * adds/renames a built-in: `createCodingTools` → read/bash/edit/write;
17
+ * `createReadOnlyTools` → read/grep/find/ls; `powershell` from its own
18
+ * factory (pi 0.84.3 added it — inside the ≥0.86.1 peer floor — and pi's
19
+ * `allToolNames` registry lists it unconditionally). The `cwd` only binds
20
+ * tool operations we never invoke here — we read each tool's `.name` and
21
+ * discard it. Construction is safe everywhere: pi builds these definitions
22
+ * in every session on every platform.
19
23
  */
20
- export const BUILTIN_TOOL_NAMES: string[] = [
21
- ...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
24
+ export const KNOWN_BUILTIN_TOOL_NAMES: string[] = [
25
+ ...new Set(
26
+ [...createCodingTools("."), ...createReadOnlyTools("."), createPowerShellTool(".")].map((t) => t.name),
27
+ ),
22
28
  ];
23
29
 
30
+ /**
31
+ * The built-ins `tools: *`/`all` and an omitted `tools:` expand to on THIS
32
+ * platform. `powershell` validates as known everywhere (explicit
33
+ * `tools: powershell` never warns, and pi registers it in every session), but
34
+ * its exec throws off-Windows (pi's `getPowerShellConfig`), so wildcard and
35
+ * full-set agents only advertise it where it can actually run.
36
+ */
37
+ export const BUILTIN_TOOL_NAMES: string[] = KNOWN_BUILTIN_TOOL_NAMES.filter(
38
+ (name) => name !== "powershell" || process.platform === "win32",
39
+ );
40
+
24
41
  /** Unified runtime registry of all agents (defaults + user-defined). */
25
42
  const agents = new Map<string, AgentConfig>();
26
43
 
@@ -89,6 +106,34 @@ export function registerAgents(userAgents: Map<string, AgentConfig>): void {
89
106
  }
90
107
  }
91
108
 
109
+ /**
110
+ * Detach an agent definition from the process-global registry for admission.
111
+ *
112
+ * A spawn can be queued, or paused on an async acquire-side guard, long enough
113
+ * for a settings reload or a mention-driven reload to re-register the same type
114
+ * name. The run must use the definition that identified it when it was admitted,
115
+ * not whatever the registry says minutes later. Strings (including `systemPrompt`)
116
+ * are immutable and shared by reference; only the mutable arrays are copied.
117
+ */
118
+ export function cloneAgentDefinition(config: AgentConfig): AgentConfig;
119
+ export function cloneAgentDefinition(config: AgentConfig | undefined): AgentConfig | undefined;
120
+ export function cloneAgentDefinition(config: AgentConfig | undefined): AgentConfig | undefined {
121
+ if (config === undefined) return undefined;
122
+ const allowedSubagents = config.allowedSubagents;
123
+ return {
124
+ ...config,
125
+ ...(config.builtinToolNames === undefined ? {} : { builtinToolNames: [...config.builtinToolNames] }),
126
+ ...(config.extSelectors === undefined ? {} : { extSelectors: [...config.extSelectors] }),
127
+ ...(config.disallowedTools === undefined ? {} : { disallowedTools: [...config.disallowedTools] }),
128
+ extensions: Array.isArray(config.extensions) ? [...config.extensions] : config.extensions,
129
+ ...(config.excludeExtensions === undefined ? {} : { excludeExtensions: [...config.excludeExtensions] }),
130
+ skills: Array.isArray(config.skills) ? [...config.skills] : config.skills,
131
+ ...(allowedSubagents === undefined
132
+ ? {}
133
+ : { allowedSubagents: Array.isArray(allowedSubagents) ? [...allowedSubagents] : allowedSubagents }),
134
+ };
135
+ }
136
+
92
137
  /** Case-insensitive key resolution within a registry. */
93
138
  function resolveKeyIn(registry: Map<string, AgentConfig>, name: string): string | undefined {
94
139
  if (registry.has(name)) return name;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * The complete final report carried by an agent's ordinary completion wakeup.
3
+ *
4
+ * There is deliberately NO report-character cap. The parent needs the worker's
5
+ * whole technical conclusion — finding, evidence, changes, tests, blockers — and
6
+ * a silent truncation hides exactly the part that decides what to do next. The
7
+ * compact 500/300-character previews in `buildNotificationDetails` are a
8
+ * separate thing: they are what a HUMAN sees in the rendered notification, not
9
+ * what the model reads.
10
+ *
11
+ * Only the OPT-IN raw transcript is bounded. It grows with tool output rather
12
+ * than with the answer, so a very long conversation stays a bounded excerpt and
13
+ * points at the settled `get_subagent_result(verbose: true)` call for the rest.
14
+ * The report above it is never cut to fit that excerpt.
15
+ */
16
+ import { getAgentConversation } from "./agent-runner.ts";
17
+ import type { ReportLookup } from "./report-store.ts";
18
+ import { getStatusNote, partialOutputSuffix } from "./status-note.ts";
19
+ import type { AgentRecord } from "./types.ts";
20
+ import { getLifetimeCost, getLifetimeTotal } from "./usage.ts";
21
+
22
+ /** Bound on the opt-in conversation excerpt appended after the report. */
23
+ export const TRANSCRIPT_EXCERPT_MAX_CHARS = 16_000;
24
+
25
+ export interface FinalReportRequest {
26
+ /** Append the raw conversation. Opt-in per wait; never implied. */
27
+ verbose: boolean;
28
+ }
29
+
30
+ /** Bound the opt-in transcript excerpt and say where the full one lives. */
31
+ function transcriptExcerpt(conversation: string, agentId: string): string {
32
+ if (conversation.length <= TRANSCRIPT_EXCERPT_MAX_CHARS) return conversation;
33
+ const pointer =
34
+ `\n\n...(transcript excerpt truncated at ${TRANSCRIPT_EXCERPT_MAX_CHARS} characters — ` +
35
+ `get_subagent_result with agent_id "${agentId}" and verbose: true returns the full conversation. ` +
36
+ `The final report above is complete.)`;
37
+ return conversation.slice(0, TRANSCRIPT_EXCERPT_MAX_CHARS).trimEnd() + pointer;
38
+ }
39
+
40
+ /**
41
+ * The worker's final answer, framed honestly: a failure keeps its error and the
42
+ * partial output that preceded it, a non-normal terminal status keeps its note,
43
+ * and discarded steering messages are disclosed. This text is the report — it is
44
+ * never truncated, and only `verbose` adds anything after it.
45
+ */
46
+ export function formatFinalReport(record: AgentRecord, request: FinalReportRequest): string {
47
+ let text = record.status === "error"
48
+ ? `Error: ${record.error ?? "unknown"}${partialOutputSuffix(record)}`
49
+ : (record.result?.trim() || "No output.");
50
+ const statusNote = getStatusNote(record.status);
51
+ if (statusNote) text += `\n${statusNote.trim()}`;
52
+ if (record.droppedSteers) {
53
+ const n = record.droppedSteers;
54
+ text +=
55
+ `\n\nNote: ${n} steering message${n === 1 ? "" : "s"} arrived after the agent finished and ` +
56
+ `${n === 1 ? "was" : "were"} discarded.`;
57
+ }
58
+ if (request.verbose && record.session) {
59
+ const conversation = getAgentConversation(record.session);
60
+ if (conversation) {
61
+ text += `\n\n--- Agent Conversation ---\n${transcriptExcerpt(conversation, record.id)}`;
62
+ }
63
+ }
64
+ return text;
65
+ }
66
+
67
+ /**
68
+ * Format a durable-report lookup for the root `get_subagent_result` surface.
69
+ *
70
+ * This is the post-eviction/reload twin of the live output above, so it keeps
71
+ * the same facts and the same honesty rules:
72
+ *
73
+ * - the stored report is returned in full, never previewed or capped;
74
+ * - absent legacy metadata reads `unknown`, never a fabricated `0`;
75
+ * - provenance names where the report came from;
76
+ * - expiry, deliberate deletion, ambiguity and absence each say what actually
77
+ * happened instead of promoting an older value as current.
78
+ *
79
+ * The caller passes `conversation` only for an opt-in verbose read; this
80
+ * function never reads a session, never notifies, and never bills usage.
81
+ */
82
+ export interface ArchivedReportFormatOptions {
83
+ /** Show cost in the stats line, matching the live path's setting. */
84
+ showCost?: boolean;
85
+ /** Opt-in raw conversation, already read from verified existing files. */
86
+ conversation?: string;
87
+ }
88
+
89
+ function archivedTokens(count: number): string {
90
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M token`;
91
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k token`;
92
+ return `${count} token`;
93
+ }
94
+
95
+ function archivedCost(cost: number): string {
96
+ if (!(cost > 0)) return "";
97
+ if (cost < 0.0001) return "<$0.0001";
98
+ if (cost >= 1) return `~$${cost.toFixed(2)}`;
99
+ return `~$${cost.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}`;
100
+ }
101
+
102
+ export function formatArchivedReportLookup(
103
+ lookup: ReportLookup,
104
+ options: ArchivedReportFormatOptions = {},
105
+ ): string {
106
+ switch (lookup.status) {
107
+ case "found": {
108
+ const report = lookup.report;
109
+ const stats: string[] = [
110
+ `Tool uses: ${report.toolUses === undefined ? "unknown" : report.toolUses}`,
111
+ ];
112
+ if (report.startedAt !== undefined && report.completedAt !== undefined) {
113
+ stats.push(`Duration: ${((report.completedAt - report.startedAt) / 1000).toFixed(1)}s`);
114
+ } else {
115
+ stats.push("Duration: unknown");
116
+ }
117
+ if (report.lifetimeUsage === undefined) {
118
+ stats.push("Tokens: unknown");
119
+ } else {
120
+ const total = getLifetimeTotal(report.lifetimeUsage);
121
+ if (total > 0) stats.push(archivedTokens(total));
122
+ if (options.showCost) {
123
+ const cost = getLifetimeCost(report.lifetimeUsage);
124
+ const text = archivedCost(cost);
125
+ if (text) stats.push(`Cost: ${text}`);
126
+ }
127
+ }
128
+ if (report.compactionCount) stats.push(`Compactions: ${report.compactionCount}`);
129
+ const provenance =
130
+ lookup.provenance === "archive"
131
+ ? "saved report"
132
+ : lookup.provenance === "parent-record"
133
+ ? "parent-session record (pre-archive)"
134
+ : "validated legacy transcript metadata";
135
+ let body: string;
136
+ if (report.status === "error") {
137
+ const partial = report.result?.trim();
138
+ body = `Error: ${report.error ?? "unknown"}${
139
+ partial ? `\n\nPartial output before the failure:\n${partial}` : ""
140
+ }`;
141
+ } else {
142
+ body = report.result?.trim() || report.error?.trim() || "No output.";
143
+ const note = getStatusNote(report.status);
144
+ if (note) body += `\n${note.trim()}`;
145
+ }
146
+ if (report.droppedSteers) {
147
+ const n = report.droppedSteers;
148
+ body +=
149
+ `\n\nNote: ${n} steering message${n === 1 ? "" : "s"} arrived after the agent finished and ` +
150
+ `${n === 1 ? "was" : "were"} discarded.`;
151
+ }
152
+ let output =
153
+ `Agent: ${report.id}\n` +
154
+ `Type: ${report.type} | Status: ${report.status}${getStatusNote(report.status)} | ${stats.join(" | ")}\n` +
155
+ `Description: ${report.description}\n` +
156
+ `Recovered from: ${provenance} (root session ${lookup.rootSessionId})\n\n` +
157
+ body;
158
+ if (options.conversation !== undefined) {
159
+ output += `\n\n--- Agent Conversation ---\n${options.conversation}`;
160
+ }
161
+ return output;
162
+ }
163
+ case "expired":
164
+ return (
165
+ `Agent ${lookup.entry.id} is no longer available: its saved report expired at ` +
166
+ `${new Date(lookup.expiredAt).toISOString()} (30-day retention). ` +
167
+ `The complete result was removed; no older value is being presented as current.`
168
+ );
169
+ case "deleted":
170
+ return (
171
+ `Agent ${lookup.entry.id}'s saved report was deliberately deleted${
172
+ lookup.reason === undefined ? "" : ` (${lookup.reason})`
173
+ } at ${new Date(lookup.deletedAt).toISOString()}. ` +
174
+ `Deliberate removal is final: the report will not be resurrected from history or a transcript.`
175
+ );
176
+ case "ambiguous":
177
+ return (
178
+ `Agent reference "${lookup.ref}" is ambiguous in the saved archive: ` +
179
+ `${lookup.candidates.map(candidate => candidate.id).join(", ")}. ` +
180
+ `No result was chosen — use the exact 17-character agent id.`
181
+ );
182
+ case "missing": {
183
+ const reason = lookup.reason.replace(/[.]+$/, "");
184
+ return `Agent not found: "${lookup.ref}". ${reason}. It may have been cleaned up.`;
185
+ }
186
+ }
187
+ }