@timmyjl12/pi-subagents 0.20.0 → 0.21.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 (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 +3612 -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 +4130 -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
@@ -4,12 +4,13 @@
4
4
  import type { Model } from "@earendil-works/pi-ai";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
6
  import { type AgentSession, DefaultResourceLoader, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
- import { type AdvisorStatus } from "./advisor-status.js";
8
- import { resolvePinnedModel } from "./invocation-config.js";
9
- import { type NestedAgentManager } from "./nested-tools.js";
10
- import type { SubagentType, ThinkingLevel } from "./types.js";
11
- import type { LifetimeUsage } from "./usage.js";
12
- import type { CompiledSchema } from "./workflow/json-schema.js";
7
+ import { type AdvisorStatus } from "./advisor-status.ts";
8
+ import { type ChildShutdownOutcome } from "./child-session-shutdown.ts";
9
+ import { resolvePinnedModel } from "./invocation-config.ts";
10
+ import { type ArchivedReportReader, type NestedAgentManager } from "./nested-tools.ts";
11
+ import type { AgentConfig, SubagentType, ThinkingLevel } from "./types.ts";
12
+ import type { LifetimeUsage } from "./usage.ts";
13
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
13
14
  /**
14
15
  * Tool names registered by THIS extension. Single source of truth so the
15
16
  * registration sites (index.ts) and the subagent exclusion list below can't
@@ -119,6 +120,10 @@ export declare function normalizeMaxTurns(n: number | undefined): number | undef
119
120
  export declare function getDefaultMaxTurns(): number | undefined;
120
121
  /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
121
122
  export declare function setDefaultMaxTurns(n: number | undefined): void;
123
+ /** Whether callers may impose per-call turn limits. Default false. */
124
+ export declare function getAllowPerCallTurnLimits(): boolean;
125
+ /** Set whether callers may impose per-call turn limits. */
126
+ export declare function setAllowPerCallTurnLimits(b: boolean): void;
122
127
  /**
123
128
  * The turn limit a run of `type` will actually enforce: an explicit value if the
124
129
  * caller supplied one, else the agent's own `max_turns`, else the project
@@ -161,6 +166,19 @@ export interface ToolActivity {
161
166
  export interface RunOptions {
162
167
  /** ExtensionAPI instance — used for pi.exec() instead of execSync. */
163
168
  pi: ExtensionAPI;
169
+ /**
170
+ * Internal, manager-only: the agent definition admitted with this run.
171
+ *
172
+ * The manager snapshots this from its registry BEFORE a spawn is queued or
173
+ * starts awaiting work, and callers that resolve a definition against a
174
+ * scoped registry pass their own snapshot. The runner reads prompt, tools,
175
+ * model, memory, session and nesting policy from THIS object, never from
176
+ * `getAgentConfig`/`getToolNamesForType` once the run has suspended: a
177
+ * reload during a queued wait or a worktree copy must not change the agent
178
+ * that was admitted. Undefined keeps the historical direct-call behaviour
179
+ * (including the unknown-type general-purpose fallback).
180
+ */
181
+ agentDefinition?: AgentConfig;
164
182
  /** Manager-assigned id; suffixes session name to disambiguate parallel spawns (e.g. `Explore#a1b2c3d4`). */
165
183
  agentId?: string;
166
184
  model?: Model<any>;
@@ -221,6 +239,19 @@ export interface RunOptions {
221
239
  /** Called on streaming text deltas from the assistant response. */
222
240
  onTextDelta?: (delta: string, fullText: string) => void;
223
241
  onSessionCreated?: (session: AgentSession) => void;
242
+ /**
243
+ * Internal, manager-only: fires synchronously as soon as `createAgentSession`
244
+ * returns, BEFORE extension binding. The manager registers the allocated SDK
245
+ * instance and its plain provenance so a bind failure or a hang during
246
+ * `session_start` cannot make teardown look complete. It must not steer or
247
+ * announce a ready session here — `onSessionCreated` remains that boundary.
248
+ */
249
+ onSessionAllocated?: (session: AgentSession) => void;
250
+ /**
251
+ * Internal, manager-only: reports the explicit outcome of a partial-startup
252
+ * teardown (currently a bind failure) without rejecting the run's error path.
253
+ */
254
+ onSessionTeardown?: (session: AgentSession, outcome: ChildShutdownOutcome) => void;
224
255
  /** Child-local advisor runtime telemetry; independent of the child UI. */
225
256
  onAdvisorStatus?: (status: AdvisorStatus) => void;
226
257
  /** Refresh effective model metadata after recovery switches, including on resume. */
@@ -260,7 +291,15 @@ export interface RunOptions {
260
291
  parentAgentId: string;
261
292
  depth: number;
262
293
  maxSubagentDepth?: number;
294
+ /** Async parent-scoped durable-report reader for evicted children. */
295
+ archive?: ArchivedReportReader;
263
296
  };
297
+ /** Stable root session id, pinned by the manager for ownership provenance. */
298
+ rootSessionId?: string;
299
+ /** Stable root project cwd — never the worktree copy. */
300
+ rootCwd?: string;
301
+ /** Root session's pi JSONL file, when it exists. */
302
+ rootSessionFile?: string;
264
303
  }
265
304
  export interface RunResult {
266
305
  responseText: string;
@@ -6,17 +6,19 @@ import { homedir } from "node:os";
6
6
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
7
  import { createAgentSession, createEventBus, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import { attachAdvisorStatusCleanup, subscribeAdvisorStatus } from "./advisor-status.js";
9
- import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType } from "./agent-types.js";
9
+ import { BUILTIN_TOOL_NAMES, getAgentConfig, getConfig, getMemoryToolNames, getReadOnlyMemoryToolNames, getToolNamesForType, KNOWN_BUILTIN_TOOL_NAMES } from "./agent-types.js";
10
10
  import { runAsSubagentProcess, runInChildSessionContext, runWithAdvisorBind } from "./child-context.js";
11
11
  import { shutdownChildSession } from "./child-session-shutdown.js";
12
12
  import { buildParentContext, extractText } from "./context.js";
13
13
  import { DEFAULT_AGENTS } from "./default-agents.js";
14
14
  import { detectEnv } from "./env.js";
15
+ import { isForceMainModel } from "./force-main-model.js";
15
16
  import { isPinFallback, resolvePinnedModel } from "./invocation-config.js";
16
17
  import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
17
18
  import { createNestedSubagentTools, getMaxSubagentDepth } from "./nested-tools.js";
18
19
  import { buildAgentPrompt } from "./prompts.js";
19
20
  import { abortChildSession, beginChildRequest, ChildRecovery, promptWithRecovery } from "./recovery.js";
21
+ import { SESSION_OWNERSHIP_ENTRY_TYPE } from "./report-store.js";
20
22
  import { preloadSkills } from "./skill-loader.js";
21
23
  import { inventoryRecoveryOwner, resolveStandaloneModel } from "./standalone-fallback.js";
22
24
  import { createStructuredCapture, createStructuredOutputTool, structuredRetryPrompt } from "./structured-output.js";
@@ -288,6 +290,21 @@ export function normalizeMaxTurns(n) {
288
290
  export function getDefaultMaxTurns() { return defaultMaxTurns; }
289
291
  /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
290
292
  export function setDefaultMaxTurns(n) { defaultMaxTurns = normalizeMaxTurns(n); }
293
+ /**
294
+ * Whether tool/RPC callers may impose their own per-call turn limit.
295
+ *
296
+ * Off by default: a configured agent-file or project budget is authoritative,
297
+ * and a caller's `max_turns` is ignored. Turn it on to restore the historical
298
+ * caller-cap behaviour. This governs only the model-facing/tool and RPC
299
+ * surfaces — `RunOptions.maxTurns` stays an internal API for in-tree callers
300
+ * (the manager, scheduler, nested delegation) with an explicitly configured
301
+ * budget, and `resolveEffectiveMaxTurns` keeps honoring it.
302
+ */
303
+ let allowPerCallTurnLimits = false;
304
+ /** Whether callers may impose per-call turn limits. Default false. */
305
+ export function getAllowPerCallTurnLimits() { return allowPerCallTurnLimits; }
306
+ /** Set whether callers may impose per-call turn limits. */
307
+ export function setAllowPerCallTurnLimits(b) { allowPerCallTurnLimits = b; }
291
308
  /**
292
309
  * The turn limit a run of `type` will actually enforce: an explicit value if the
293
310
  * caller supplied one, else the agent's own `max_turns`, else the project
@@ -312,8 +329,8 @@ let rememberAgents = true;
312
329
  export function getRememberAgents() { return rememberAgents; }
313
330
  /** Set whether subagent sessions are persisted by default. */
314
331
  export function setRememberAgents(b) { rememberAgents = b; }
315
- /** Additional turns allowed after the soft limit steer message. */
316
- let graceTurns = 5;
332
+ /** Additional turns allowed after the soft limit steer message. Default 10. */
333
+ let graceTurns = 10;
317
334
  /** Get the grace turns value. */
318
335
  export function getGraceTurns() { return graceTurns; }
319
336
  /** Set the grace turns value (minimum 1). */
@@ -421,7 +438,7 @@ function finalTurnError(session, startIndex = 0, finalMessage) {
421
438
  function forwardAbortSignal(session, signal) {
422
439
  if (!signal)
423
440
  return () => { };
424
- const onAbort = () => { void abortChildSession(session); };
441
+ const onAbort = () => { void abortChildSession(session).catch(() => { }); /* teardown errors surface through the run */ };
425
442
  if (signal.aborted)
426
443
  onAbort();
427
444
  else
@@ -457,25 +474,48 @@ export async function runAgent(ctx, type, prompt, options) {
457
474
  }
458
475
  }
459
476
  async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, retainAdvisorStatus) {
460
- const config = getConfig(type);
461
- const agentConfig = getAgentConfig(type);
477
+ // Admitted definition is the run's sole policy source. Direct runAgent
478
+ // callers without one keep the historical registry reads — captured before
479
+ // the first await below, so nothing is re-read after a suspension.
480
+ const admittedDefinition = options.agentDefinition;
481
+ const agentConfig = admittedDefinition ?? getAgentConfig(type);
482
+ const config = admittedDefinition === undefined
483
+ ? getConfig(type)
484
+ : {
485
+ displayName: admittedDefinition.displayName ?? admittedDefinition.name,
486
+ color: admittedDefinition.color,
487
+ description: admittedDefinition.description,
488
+ builtinToolNames: admittedDefinition.builtinToolNames ?? BUILTIN_TOOL_NAMES,
489
+ extensions: admittedDefinition.extensions,
490
+ excludeExtensions: admittedDefinition.excludeExtensions,
491
+ skills: admittedDefinition.skills,
492
+ promptMode: admittedDefinition.promptMode,
493
+ };
462
494
  if (agentConfig?.advisor === false) {
463
495
  options.onAdvisorStatus?.({ state: "off", models: [], reviews: 0 });
464
496
  }
465
497
  // Capture the standalone default before any await; resume keeps this identity
466
498
  // even if the parent context or its model object later changes.
467
499
  const standaloneParentModel = ctx.model;
468
- const fallbackModel = agentConfig?.fallbackModel
500
+ // Under `/subagents off` an agent file's `fallback_model` is one more model
501
+ // choice that gives way: standalone recovery still happens, onto the main model.
502
+ const configuredFallback = isForceMainModel() ? undefined : agentConfig?.fallbackModel;
503
+ const fallbackModel = configuredFallback
469
504
  ?? (standaloneParentModel ? `${standaloneParentModel.provider}/${standaloneParentModel.id}` : undefined);
470
505
  // Every entry path reaches this gate, including RPC, nested, mention and
471
- // scheduled spawns. A pre-resolved caller model cannot bypass an agent pin.
506
+ // scheduled spawns. A pre-resolved caller model cannot bypass an agent pin —
507
+ // except under `/subagents off`, where pins and overrides alike give way to
508
+ // the parent's model. A nested child's parent is itself twinned, so the main
509
+ // model propagates down the whole tree.
472
510
  // Built-in defaults (Explore/Plan) fall back to the parent model with a
473
511
  // notice when their pin names an unavailable provider; user-authored pins
474
512
  // stay strict. The notice is folded into the prompt extras below so it is
475
513
  // visible in the child's context rather than silently dropped.
476
- const { model, notice: pinFallbackNotice } = resolveDefaultModel(options.model ?? ctx.model, ctx.modelRegistry, agentConfig?.model, {
477
- isBuiltInDefault: agentConfig?.isDefault === true,
478
- });
514
+ const { model, notice: pinFallbackNotice } = isForceMainModel()
515
+ ? { model: ctx.model, notice: undefined }
516
+ : resolveDefaultModel(options.model ?? ctx.model, ctx.modelRegistry, agentConfig?.model, {
517
+ isBuiltInDefault: agentConfig?.isDefault === true,
518
+ });
479
519
  // Resolve working directory: worktree override > parent cwd
480
520
  const effectiveCwd = options.cwd ?? ctx.cwd;
481
521
  // Filesystem work happens in effectiveCwd; config discovery in configCwd.
@@ -505,7 +545,11 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
505
545
  extras.skillBlocks = loaded;
506
546
  }
507
547
  }
508
- let toolNames = getToolNamesForType(type);
548
+ let toolNames = admittedDefinition === undefined
549
+ ? getToolNamesForType(type)
550
+ : admittedDefinition.builtinToolNames === undefined
551
+ ? [...BUILTIN_TOOL_NAMES]
552
+ : [...admittedDefinition.builtinToolNames];
509
553
  // Persistent memory: detect write capability and branch accordingly.
510
554
  // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
511
555
  if (agentConfig?.memory) {
@@ -650,7 +694,7 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
650
694
  // this produced a silently broken agent (#75) — pi-mono accepted the bogus name
651
695
  // into the allowlist, then dropped it at registration with no signal back.
652
696
  if (agentConfig?.builtinToolNames?.length) {
653
- const knownBuiltins = new Set(BUILTIN_TOOL_NAMES);
697
+ const knownBuiltins = new Set(KNOWN_BUILTIN_TOOL_NAMES);
654
698
  for (const name of agentConfig.builtinToolNames) {
655
699
  if (!knownBuiltins.has(name)) {
656
700
  options.onToolActivity?.({
@@ -737,6 +781,7 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
737
781
  maxSubagentDepth: effectiveMaxDepth,
738
782
  allowedSubagents: agentConfig.allowedSubagents,
739
783
  configCwd,
784
+ ...(nestedRuntime.archive === undefined ? {} : { archive: nestedRuntime.archive }),
740
785
  })
741
786
  : [];
742
787
  const nestedToolNames = new Set(nestedTools.map(tool => tool.name));
@@ -794,8 +839,11 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
794
839
  if (noExtensions) {
795
840
  // Strict allowlist: built-ins the agent asked for, plus any opt-in nested
796
841
  // tools (whose names would otherwise be dropped as EXCLUDED_TOOL_NAMES).
842
+ // Pi 1.1 reads `+x`/`-x` entries as edits to the user's defaultTools (and
843
+ // throws when they are mixed with names) and `*` as a pattern; none is a
844
+ // tool name, and the unknown-name warning above already reported them.
797
845
  sessionTools = [
798
- ...toolNames.filter((t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t)),
846
+ ...toolNames.filter((t) => !EXCLUDED_TOOL_NAMES.includes(t) && !disallowedSet?.has(t) && !/^[+-]|\*/.test(t)),
799
847
  ...[...nestedToolNames].filter((t) => !disallowedSet?.has(t)),
800
848
  // Not filtered through `disallowedSet`, unlike the nested tools above:
801
849
  // the caller asked for a schema, and removing the only tool that can
@@ -844,6 +892,37 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
844
892
  parentSession: ctx.sessionManager?.getSessionFile?.(),
845
893
  })
846
894
  : SessionManager.inMemory(effectiveCwd);
895
+ // Ownership tag, written before the session binds extensions or runs its
896
+ // first prompt. A cleanup can therefore prove a child pi history is ours
897
+ // from the file itself, and record the root provenance once — never the
898
+ // parent's main conversation file. Custom entries are excluded from model
899
+ // context by the SDK; the in-memory variant leaves nothing on disk, which
900
+ // preserves the explicit no-session intent.
901
+ const ownershipRootSessionId = options.rootSessionId ?? ctx.sessionManager?.getSessionId?.();
902
+ const ownershipRootCwd = options.rootCwd ?? ctx.cwd;
903
+ const ownershipRootSessionFile = options.rootSessionFile ?? ctx.sessionManager?.getSessionFile?.();
904
+ const ownershipChildFile = sessionManager.getSessionFile?.();
905
+ if (options.agentId !== undefined
906
+ && ownershipRootSessionId !== undefined
907
+ && ownershipRootCwd !== undefined
908
+ && ownershipChildFile !== ownershipRootSessionFile) {
909
+ const ownership = {
910
+ version: 1,
911
+ agentId: options.agentId,
912
+ rootSessionId: ownershipRootSessionId,
913
+ rootCwd: ownershipRootCwd,
914
+ ...(ownershipRootSessionFile === undefined ? {} : { rootSessionFile: ownershipRootSessionFile }),
915
+ childSessionId: sessionManager.getSessionId(),
916
+ };
917
+ try {
918
+ sessionManager.appendCustomEntry(SESSION_OWNERSHIP_ENTRY_TYPE, ownership);
919
+ }
920
+ catch (error) {
921
+ // A read-only or already-closed history must not take the spawn down;
922
+ // cleanup will simply treat the file as unowned.
923
+ console.warn("[pi-subagents] could not record child-session ownership:", error);
924
+ }
925
+ }
847
926
  // Pi 0.80.8 replaced createAgentSession's modelRegistry option with
848
927
  // modelRuntime, but ExtensionContext still exposes only the registry facade.
849
928
  // Pass both so the full supported Pi range retains the parent's providers.
@@ -879,6 +958,10 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
879
958
  sessionOpts.thinkingLevel = thinkingLevel;
880
959
  }
881
960
  const { session } = await runInChildSessionContext(() => createAgentSession(sessionOpts));
961
+ // Before any binding or ready announcement: the manager now owns the plain
962
+ // identity of this allocated instance, so its teardown outcome cannot be
963
+ // lost if `session_start` fails or hangs.
964
+ options.onSessionAllocated?.(session);
882
965
  attachToolProgress(session);
883
966
  const dispose = session.dispose?.bind(session);
884
967
  if (dispose)
@@ -913,8 +996,16 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
913
996
  }
914
997
  catch (error) {
915
998
  // Bind may have run some session_start handlers already. Emit shutdown
916
- // before disposal so their timers/watchers cannot outlive this child.
917
- await shutdownChildSession(session);
999
+ // before disposal so their timers/watchers cannot outlive this child. The
1000
+ // outcome is forwarded to the manager: this runs before onSessionCreated,
1001
+ // so without the handoff the allocated instance would simply disappear.
1002
+ const outcome = await shutdownChildSession(session);
1003
+ try {
1004
+ options.onSessionTeardown?.(session, outcome);
1005
+ }
1006
+ catch (notifyError) {
1007
+ console.warn("[pi-subagents] partial-startup teardown handoff failed:", notifyError);
1008
+ }
918
1009
  throw error;
919
1010
  }
920
1011
  // With `allowedToolNames` unset, the registry is scoped by `excludeTools` but
@@ -936,7 +1027,7 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
936
1027
  options.onSessionCreated?.(session);
937
1028
  // Track turns for graceful max_turns enforcement
938
1029
  let turnCount = 0;
939
- const maxTurns = resolveEffectiveMaxTurns(type, options.maxTurns);
1030
+ const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
940
1031
  let softLimitReached = false;
941
1032
  let aborted = false;
942
1033
  let currentMessageText = "";
@@ -951,7 +1042,7 @@ async function runAgentSession(ctx, type, prompt, options, eventBus, recovery, r
951
1042
  }
952
1043
  else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
953
1044
  aborted = true;
954
- void abortChildSession(session, "turn_limit");
1045
+ void abortChildSession(session, "turn_limit").catch(() => { }); // the run reports the abort itself
955
1046
  }
956
1047
  }
957
1048
  }
@@ -4,14 +4,26 @@
4
4
  * Merges embedded default agents with user-defined agents from .pi/agents/*.md, .agents/agents/*.md, and global agents.
5
5
  * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
6
  */
7
- import type { AgentConfig } from "./types.js";
7
+ import type { AgentConfig } from "./types.ts";
8
8
  /**
9
- * All known built-in tool names, derived from pi's own tool factories rather
10
- * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
11
- * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
12
- * read/grep/find/ls; their de-duplicated union is the 7 built-ins
13
- * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
14
- * operations we never invoke here — we read each tool's `.name` and discard it.
9
+ * Every built-in tool name pi's registry knows, on every platform — the set
10
+ * `tools:` frontmatter is validated against. Derived from pi's own tool
11
+ * factories rather than hardcoded so the set tracks pi-mono if it
12
+ * adds/renames a built-in: `createCodingTools` → read/bash/edit/write;
13
+ * `createReadOnlyTools` → read/grep/find/ls; `powershell` from its own
14
+ * factory (pi 0.84.3 added it — inside the ≥0.86.1 peer floor — and pi's
15
+ * `allToolNames` registry lists it unconditionally). The `cwd` only binds
16
+ * tool operations we never invoke here — we read each tool's `.name` and
17
+ * discard it. Construction is safe everywhere: pi builds these definitions
18
+ * in every session on every platform.
19
+ */
20
+ export declare const KNOWN_BUILTIN_TOOL_NAMES: string[];
21
+ /**
22
+ * The built-ins `tools: *`/`all` and an omitted `tools:` expand to on THIS
23
+ * platform. `powershell` validates as known everywhere (explicit
24
+ * `tools: powershell` never warns, and pi registers it in every session), but
25
+ * its exec throws off-Windows (pi's `getPowerShellConfig`), so wildcard and
26
+ * full-set agents only advertise it where it can actually run.
15
27
  */
16
28
  export declare const BUILTIN_TOOL_NAMES: string[];
17
29
  /** Check whether default agents are disabled. */
@@ -37,6 +49,17 @@ export declare function buildAgentRegistry(userAgents: Map<string, AgentConfig>)
37
49
  * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
38
50
  */
39
51
  export declare function registerAgents(userAgents: Map<string, AgentConfig>): void;
52
+ /**
53
+ * Detach an agent definition from the process-global registry for admission.
54
+ *
55
+ * A spawn can be queued, or paused on an async acquire-side guard, long enough
56
+ * for a settings reload or a mention-driven reload to re-register the same type
57
+ * name. The run must use the definition that identified it when it was admitted,
58
+ * not whatever the registry says minutes later. Strings (including `systemPrompt`)
59
+ * are immutable and shared by reference; only the mutable arrays are copied.
60
+ */
61
+ export declare function cloneAgentDefinition(config: AgentConfig): AgentConfig;
62
+ export declare function cloneAgentDefinition(config: AgentConfig | undefined): AgentConfig | undefined;
40
63
  /** Resolve a type name case-insensitively in a registry. Returns the canonical key or undefined. */
41
64
  export declare function resolveTypeIn(registry: Map<string, AgentConfig>, name: string): string | undefined;
42
65
  /** Get the agent config for a type (case-insensitive) from a registry. */
@@ -4,19 +4,31 @@
4
4
  * Merges embedded default agents with user-defined agents from .pi/agents/*.md, .agents/agents/*.md, and global agents.
5
5
  * User agents override defaults with the same name. Disabled agents are kept but excluded from spawning.
6
6
  */
7
- import { createCodingTools, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
7
+ import { createCodingTools, createPowerShellTool, createReadOnlyTools } from "@earendil-works/pi-coding-agent";
8
8
  import { DEFAULT_AGENTS } from "./default-agents.js";
9
9
  /**
10
- * All known built-in tool names, derived from pi's own tool factories rather
11
- * than hardcoded so the set tracks pi-mono if it adds/renames a built-in.
12
- * `createCodingTools` → read/bash/edit/write; `createReadOnlyTools` →
13
- * read/grep/find/ls; their de-duplicated union is the 7 built-ins
14
- * (read, bash, edit, write, grep, find, ls). The `cwd` only binds tool
15
- * operations we never invoke here — we read each tool's `.name` and discard it.
10
+ * Every built-in tool name pi's registry knows, on every platform — the set
11
+ * `tools:` frontmatter is validated against. Derived from pi's own tool
12
+ * factories rather than hardcoded so the set tracks pi-mono if it
13
+ * adds/renames a built-in: `createCodingTools` → read/bash/edit/write;
14
+ * `createReadOnlyTools` → read/grep/find/ls; `powershell` from its own
15
+ * factory (pi 0.84.3 added it — inside the ≥0.86.1 peer floor — and pi's
16
+ * `allToolNames` registry lists it unconditionally). The `cwd` only binds
17
+ * tool operations we never invoke here — we read each tool's `.name` and
18
+ * discard it. Construction is safe everywhere: pi builds these definitions
19
+ * in every session on every platform.
16
20
  */
17
- export const BUILTIN_TOOL_NAMES = [
18
- ...new Set([...createCodingTools("."), ...createReadOnlyTools(".")].map((t) => t.name)),
21
+ export const KNOWN_BUILTIN_TOOL_NAMES = [
22
+ ...new Set([...createCodingTools("."), ...createReadOnlyTools("."), createPowerShellTool(".")].map((t) => t.name)),
19
23
  ];
24
+ /**
25
+ * The built-ins `tools: *`/`all` and an omitted `tools:` expand to on THIS
26
+ * platform. `powershell` validates as known everywhere (explicit
27
+ * `tools: powershell` never warns, and pi registers it in every session), but
28
+ * its exec throws off-Windows (pi's `getPowerShellConfig`), so wildcard and
29
+ * full-set agents only advertise it where it can actually run.
30
+ */
31
+ export const BUILTIN_TOOL_NAMES = KNOWN_BUILTIN_TOOL_NAMES.filter((name) => name !== "powershell" || process.platform === "win32");
20
32
  /** Unified runtime registry of all agents (defaults + user-defined). */
21
33
  const agents = new Map();
22
34
  /** When true, DEFAULT_AGENTS are skipped during registration. */
@@ -77,6 +89,23 @@ export function registerAgents(userAgents) {
77
89
  agents.set(name, config);
78
90
  }
79
91
  }
92
+ export function cloneAgentDefinition(config) {
93
+ if (config === undefined)
94
+ return undefined;
95
+ const allowedSubagents = config.allowedSubagents;
96
+ return {
97
+ ...config,
98
+ ...(config.builtinToolNames === undefined ? {} : { builtinToolNames: [...config.builtinToolNames] }),
99
+ ...(config.extSelectors === undefined ? {} : { extSelectors: [...config.extSelectors] }),
100
+ ...(config.disallowedTools === undefined ? {} : { disallowedTools: [...config.disallowedTools] }),
101
+ extensions: Array.isArray(config.extensions) ? [...config.extensions] : config.extensions,
102
+ ...(config.excludeExtensions === undefined ? {} : { excludeExtensions: [...config.excludeExtensions] }),
103
+ skills: Array.isArray(config.skills) ? [...config.skills] : config.skills,
104
+ ...(allowedSubagents === undefined
105
+ ? {}
106
+ : { allowedSubagents: Array.isArray(allowedSubagents) ? [...allowedSubagents] : allowedSubagents }),
107
+ };
108
+ }
80
109
  /** Case-insensitive key resolution within a registry. */
81
110
  function resolveKeyIn(registry, name) {
82
111
  if (registry.has(name))
@@ -0,0 +1,37 @@
1
+ import type { ReportLookup } from "./report-store.ts";
2
+ import type { AgentRecord } from "./types.ts";
3
+ /** Bound on the opt-in conversation excerpt appended after the report. */
4
+ export declare const TRANSCRIPT_EXCERPT_MAX_CHARS = 16000;
5
+ export interface FinalReportRequest {
6
+ /** Append the raw conversation. Opt-in per wait; never implied. */
7
+ verbose: boolean;
8
+ }
9
+ /**
10
+ * The worker's final answer, framed honestly: a failure keeps its error and the
11
+ * partial output that preceded it, a non-normal terminal status keeps its note,
12
+ * and discarded steering messages are disclosed. This text is the report — it is
13
+ * never truncated, and only `verbose` adds anything after it.
14
+ */
15
+ export declare function formatFinalReport(record: AgentRecord, request: FinalReportRequest): string;
16
+ /**
17
+ * Format a durable-report lookup for the root `get_subagent_result` surface.
18
+ *
19
+ * This is the post-eviction/reload twin of the live output above, so it keeps
20
+ * the same facts and the same honesty rules:
21
+ *
22
+ * - the stored report is returned in full, never previewed or capped;
23
+ * - absent legacy metadata reads `unknown`, never a fabricated `0`;
24
+ * - provenance names where the report came from;
25
+ * - expiry, deliberate deletion, ambiguity and absence each say what actually
26
+ * happened instead of promoting an older value as current.
27
+ *
28
+ * The caller passes `conversation` only for an opt-in verbose read; this
29
+ * function never reads a session, never notifies, and never bills usage.
30
+ */
31
+ export interface ArchivedReportFormatOptions {
32
+ /** Show cost in the stats line, matching the live path's setting. */
33
+ showCost?: boolean;
34
+ /** Opt-in raw conversation, already read from verified existing files. */
35
+ conversation?: string;
36
+ }
37
+ export declare function formatArchivedReportLookup(lookup: ReportLookup, options?: ArchivedReportFormatOptions): string;
@@ -0,0 +1,150 @@
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.js";
17
+ import { getStatusNote, partialOutputSuffix } from "./status-note.js";
18
+ import { getLifetimeCost, getLifetimeTotal } from "./usage.js";
19
+ /** Bound on the opt-in conversation excerpt appended after the report. */
20
+ export const TRANSCRIPT_EXCERPT_MAX_CHARS = 16_000;
21
+ /** Bound the opt-in transcript excerpt and say where the full one lives. */
22
+ function transcriptExcerpt(conversation, agentId) {
23
+ if (conversation.length <= TRANSCRIPT_EXCERPT_MAX_CHARS)
24
+ return conversation;
25
+ const pointer = `\n\n...(transcript excerpt truncated at ${TRANSCRIPT_EXCERPT_MAX_CHARS} characters — ` +
26
+ `get_subagent_result with agent_id "${agentId}" and verbose: true returns the full conversation. ` +
27
+ `The final report above is complete.)`;
28
+ return conversation.slice(0, TRANSCRIPT_EXCERPT_MAX_CHARS).trimEnd() + pointer;
29
+ }
30
+ /**
31
+ * The worker's final answer, framed honestly: a failure keeps its error and the
32
+ * partial output that preceded it, a non-normal terminal status keeps its note,
33
+ * and discarded steering messages are disclosed. This text is the report — it is
34
+ * never truncated, and only `verbose` adds anything after it.
35
+ */
36
+ export function formatFinalReport(record, request) {
37
+ let text = record.status === "error"
38
+ ? `Error: ${record.error ?? "unknown"}${partialOutputSuffix(record)}`
39
+ : (record.result?.trim() || "No output.");
40
+ const statusNote = getStatusNote(record.status);
41
+ if (statusNote)
42
+ text += `\n${statusNote.trim()}`;
43
+ if (record.droppedSteers) {
44
+ const n = record.droppedSteers;
45
+ text +=
46
+ `\n\nNote: ${n} steering message${n === 1 ? "" : "s"} arrived after the agent finished and ` +
47
+ `${n === 1 ? "was" : "were"} discarded.`;
48
+ }
49
+ if (request.verbose && record.session) {
50
+ const conversation = getAgentConversation(record.session);
51
+ if (conversation) {
52
+ text += `\n\n--- Agent Conversation ---\n${transcriptExcerpt(conversation, record.id)}`;
53
+ }
54
+ }
55
+ return text;
56
+ }
57
+ function archivedTokens(count) {
58
+ if (count >= 1_000_000)
59
+ return `${(count / 1_000_000).toFixed(1)}M token`;
60
+ if (count >= 1_000)
61
+ return `${(count / 1_000).toFixed(1)}k token`;
62
+ return `${count} token`;
63
+ }
64
+ function archivedCost(cost) {
65
+ if (!(cost > 0))
66
+ return "";
67
+ if (cost < 0.0001)
68
+ return "<$0.0001";
69
+ if (cost >= 1)
70
+ return `~$${cost.toFixed(2)}`;
71
+ return `~$${cost.toFixed(4).replace(/0+$/, "").replace(/\.$/, "")}`;
72
+ }
73
+ export function formatArchivedReportLookup(lookup, options = {}) {
74
+ switch (lookup.status) {
75
+ case "found": {
76
+ const report = lookup.report;
77
+ const stats = [
78
+ `Tool uses: ${report.toolUses === undefined ? "unknown" : report.toolUses}`,
79
+ ];
80
+ if (report.startedAt !== undefined && report.completedAt !== undefined) {
81
+ stats.push(`Duration: ${((report.completedAt - report.startedAt) / 1000).toFixed(1)}s`);
82
+ }
83
+ else {
84
+ stats.push("Duration: unknown");
85
+ }
86
+ if (report.lifetimeUsage === undefined) {
87
+ stats.push("Tokens: unknown");
88
+ }
89
+ else {
90
+ const total = getLifetimeTotal(report.lifetimeUsage);
91
+ if (total > 0)
92
+ stats.push(archivedTokens(total));
93
+ if (options.showCost) {
94
+ const cost = getLifetimeCost(report.lifetimeUsage);
95
+ const text = archivedCost(cost);
96
+ if (text)
97
+ stats.push(`Cost: ${text}`);
98
+ }
99
+ }
100
+ if (report.compactionCount)
101
+ stats.push(`Compactions: ${report.compactionCount}`);
102
+ const provenance = lookup.provenance === "archive"
103
+ ? "saved report"
104
+ : lookup.provenance === "parent-record"
105
+ ? "parent-session record (pre-archive)"
106
+ : "validated legacy transcript metadata";
107
+ let body;
108
+ if (report.status === "error") {
109
+ const partial = report.result?.trim();
110
+ body = `Error: ${report.error ?? "unknown"}${partial ? `\n\nPartial output before the failure:\n${partial}` : ""}`;
111
+ }
112
+ else {
113
+ body = report.result?.trim() || report.error?.trim() || "No output.";
114
+ const note = getStatusNote(report.status);
115
+ if (note)
116
+ body += `\n${note.trim()}`;
117
+ }
118
+ if (report.droppedSteers) {
119
+ const n = report.droppedSteers;
120
+ body +=
121
+ `\n\nNote: ${n} steering message${n === 1 ? "" : "s"} arrived after the agent finished and ` +
122
+ `${n === 1 ? "was" : "were"} discarded.`;
123
+ }
124
+ let output = `Agent: ${report.id}\n` +
125
+ `Type: ${report.type} | Status: ${report.status}${getStatusNote(report.status)} | ${stats.join(" | ")}\n` +
126
+ `Description: ${report.description}\n` +
127
+ `Recovered from: ${provenance} (root session ${lookup.rootSessionId})\n\n` +
128
+ body;
129
+ if (options.conversation !== undefined) {
130
+ output += `\n\n--- Agent Conversation ---\n${options.conversation}`;
131
+ }
132
+ return output;
133
+ }
134
+ case "expired":
135
+ return (`Agent ${lookup.entry.id} is no longer available: its saved report expired at ` +
136
+ `${new Date(lookup.expiredAt).toISOString()} (30-day retention). ` +
137
+ `The complete result was removed; no older value is being presented as current.`);
138
+ case "deleted":
139
+ return (`Agent ${lookup.entry.id}'s saved report was deliberately deleted${lookup.reason === undefined ? "" : ` (${lookup.reason})`} at ${new Date(lookup.deletedAt).toISOString()}. ` +
140
+ `Deliberate removal is final: the report will not be resurrected from history or a transcript.`);
141
+ case "ambiguous":
142
+ return (`Agent reference "${lookup.ref}" is ambiguous in the saved archive: ` +
143
+ `${lookup.candidates.map(candidate => candidate.id).join(", ")}. ` +
144
+ `No result was chosen — use the exact 17-character agent id.`);
145
+ case "missing": {
146
+ const reason = lookup.reason.replace(/[.]+$/, "");
147
+ return `Agent not found: "${lookup.ref}". ${reason}. It may have been cleaned up.`;
148
+ }
149
+ }
150
+ }