@xzzpig/pi-subagents 0.12.0 → 0.13.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.13.0] - 2026-09-11
4
+
5
+ ### Changed
6
+
7
+ - **Sandbox profile env is pinned per child launch.** Every child launch now writes `PI_SUBAGENT_PERMISSION_PROFILE` explicitly (cleared when the child declares no profile) and drops launcher-owned `PI_SUBAGENT_*PROFILE*` keys from the runner's inherited environment, so a spawned child can neither inherit a host-session role selection nor override its own. The launch also sets `PI_SUBAGENT_PERMISSION_PROFILE_PINNED=1` to tell the permission system that this process owns a launched selection.
8
+
9
+ ### Added
10
+
11
+ - **Public agent discovery API.** `pi-subagents/agents` now exports `discoverAgentsWithRuntime(pi, cwd, scope, preferredModelProvider?)` alongside the existing registration surface, plus the `AgentConfig`, `AgentDiscoveryDiagnostic`, `AgentDiscoveryResult`, and `AgentScope` types. It returns the same merged view the subagent executor uses — builtin, package, user, and project agent files combined with agents registered at runtime — so an independent extension can offer the launcher's agent list instead of re-implementing discovery. The extension's own runtime discovery now calls the same function.
12
+
3
13
  ## [0.12.0] - 2026-09-11
4
14
 
5
15
  ### Added
@@ -687,6 +697,7 @@
687
697
  - Keep `worktree: true` workflow children on the single-child path while preserving managed patch handoffs.
688
698
 
689
699
  ### Removed
700
+
690
701
  - Remove unused foreground chain and parallel execution and durable chain management surfaces.
691
702
  - Remove legacy subagent tool compatibility fields for append-step control, schedule aliases, async recovery metadata, and string mission goals.
692
703
  - Remove chain approval checkpoint steps and the `approve-checkpoint` / `reject-checkpoint` controls.
@@ -101,6 +101,41 @@ The installed owner applies the existing runtime-agent validation, collision che
101
101
 
102
102
  This contract is process-local. It does not register agents in child sessions or other Pi processes, and it does not change package discovery or package resolution.
103
103
 
104
+ ## Agent discovery from independent extensions
105
+
106
+ An extension that wants to offer the same agent list the subagent launcher uses
107
+ — a session role picker, for example — can call the exported discovery helper
108
+ instead of re-implementing agent loading:
109
+
110
+ ```typescript
111
+ import { discoverAgentsWithRuntime } from "pi-subagents/agents";
112
+
113
+ const result = discoverAgentsWithRuntime(pi, cwd, "both");
114
+ for (const agent of result.agents) {
115
+ // agent.name, agent.description, agent.aliases, agent.source,
116
+ // agent.sandbox, agent.permissionProfile, agent.override?.scope, agent.disabled
117
+ }
118
+ result.agentDiagnostics; // loader problems, per source
119
+ result.projectAgentsDir; // where project agents came from
120
+ ```
121
+
122
+ The result is the merged view: builtin, package, user, and project agent files
123
+ plus anything registered at runtime through the contract above. With nothing
124
+ registered, it is exactly `discoverAgents(cwd, scope)`.
125
+
126
+ `scope` is `"user" | "project" | "both"`. Pass the caller's `cwd` so project
127
+ layering resolves against the right tree, and pass the caller's `ExtensionAPI`
128
+ because the runtime registry is keyed on it.
129
+
130
+ Two notes for consumers of an optional dependency:
131
+
132
+ - Treat the module as optional. A package that is not installed cannot be
133
+ imported, so load it dynamically and report the failure rather than failing
134
+ extension load.
135
+ - `agent.source === "project"` (or `agent.override?.scope === "project"`) means
136
+ the definition comes from the current project. Gate such an agent behind the
137
+ host's project-trust decision before adopting it for anything.
138
+
104
139
  ## External jobs in FleetView
105
140
 
106
141
  Use `pi-subagents/external-runs` to publish display-only current-session jobs owned by another extension:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -0,0 +1,39 @@
1
+ import {
2
+ discoverAgentSnapshot,
3
+ discoverAgents,
4
+ type AgentConfig,
5
+ type AgentDiscoveryResult,
6
+ type AgentScope,
7
+ } from "./agents.ts";
8
+ import { listRuntimeAgentConfigs, mergeRuntimeAgents, type RuntimeAgentOwner } from "./runtime-agent-registry.ts";
9
+
10
+ /**
11
+ * Discover agents exactly as the runtime sees them: file-based discovery
12
+ * (builtin, package, user, project) merged with agents registered in-process
13
+ * through the runtime agent registry.
14
+ *
15
+ * Callers outside this extension — for example an extension that lets the user
16
+ * pick a role for the interactive session — need the same merged view the
17
+ * subagent executor uses. When nothing is registered at runtime this is a thin
18
+ * wrapper around `discoverAgents`, so the registry stays a pure addition.
19
+ */
20
+ export function discoverAgentsWithRuntime(
21
+ pi: RuntimeAgentOwner,
22
+ cwd: string,
23
+ scope: AgentScope,
24
+ preferredModelProvider?: string,
25
+ ): AgentDiscoveryResult {
26
+ if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider);
27
+ const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false });
28
+ const discovered = snapshot.effective;
29
+ const all = snapshot.all;
30
+ const configuredAgents: AgentConfig[] = [...all.builtin, ...all.package, ...all.user, ...all.project];
31
+ const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
32
+ if (discovered.maxThinking === undefined) return merged;
33
+ return {
34
+ ...merged,
35
+ agents: merged.agents.map((agent) =>
36
+ agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking },
37
+ ),
38
+ };
39
+ }
package/src/api/agents.ts CHANGED
@@ -8,5 +8,12 @@ export {
8
8
  type RuntimeAgentRegistrationRequest,
9
9
  type RuntimeAgentRegistrationResult,
10
10
  } from "../agents/runtime-agent-events.ts";
11
+ export { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
11
12
 
12
13
  export type { RegisterRuntimeAgentInput, RuntimeAgentDefinition, RuntimeAgentRegistration };
14
+ export type {
15
+ AgentConfig,
16
+ AgentDiscoveryDiagnostic,
17
+ AgentDiscoveryResult,
18
+ AgentScope,
19
+ } from "../agents/agents.ts";
@@ -19,9 +19,10 @@ import * as path from "node:path";
19
19
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
20
20
  import { keyText, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
21
21
  import { Box, Container, Spacer, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
22
- import { discoverAgentSnapshot, discoverAgents, discoverAgentsAll, type AgentConfig, type AgentScope } from "../agents/agents.ts";
22
+ import { discoverAgentsAll, type AgentScope } from "../agents/agents.ts";
23
23
  import { mergeAgentsForScope } from "../agents/agent-selection.ts";
24
- import { clearRuntimeAgentsForPi, listRuntimeAgentConfigs, mergeRuntimeAgents } from "../agents/runtime-agent-registry.ts";
24
+ import { clearRuntimeAgentsForPi } from "../agents/runtime-agent-registry.ts";
25
+ import { discoverAgentsWithRuntime } from "../agents/runtime-discovery.ts";
25
26
  import { registerRuntimeAgentEventListener } from "../agents/runtime-agent-events.ts";
26
27
  import { ensureAccessibleDir } from "../shared/accessible-dir.ts";
27
28
  import { cleanupAllArtifactDirs, cleanupOldArtifacts, getArtifactsDir } from "../shared/artifacts.ts";
@@ -535,24 +536,8 @@ export default function registerSubagentExtension(pi: ExtensionAPI): void {
535
536
  if (scheduledRunManager.observedCompletionRunIds().size > 0) return true;
536
537
  return missionObserverResultCandidateFiles(DIRS.results).length > 0;
537
538
  };
538
- const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) => {
539
- if (listRuntimeAgentConfigs(pi).length === 0) return discoverAgents(cwd, scope, preferredModelProvider);
540
- const snapshot = discoverAgentSnapshot(cwd, scope, preferredModelProvider, { includeChains: false });
541
- const discovered = snapshot.effective;
542
- const all = snapshot.all;
543
- const configuredAgents: AgentConfig[] = [
544
- ...all.builtin,
545
- ...all.package,
546
- ...all.user,
547
- ...all.project,
548
- ];
549
- const merged = mergeRuntimeAgents(pi, discovered, configuredAgents);
550
- if (discovered.maxThinking === undefined) return merged;
551
- return {
552
- ...merged,
553
- agents: merged.agents.map((agent) => agent.maxThinking === discovered.maxThinking ? agent : { ...agent, maxThinking: discovered.maxThinking }),
554
- };
555
- };
539
+ const discoverAgentsForRuntime = (cwd: string, scope: AgentScope, preferredModelProvider?: string) =>
540
+ discoverAgentsWithRuntime(pi, cwd, scope, preferredModelProvider);
556
541
  const { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs, dispose: disposeAsyncJobTracker } = createAsyncJobTracker(pi, state, DIRS.async, {
557
542
  widgetEnabled: asyncWidgetEnabled,
558
543
  onJobTerminal: () => refreshResultDelivery(),
@@ -28,7 +28,7 @@ import { backgroundProcessOptions } from "../shared/background-process-options.t
28
28
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.ts";
29
29
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
30
30
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, PROMPT_REDACTED, resolveChildCwd } from "../../shared/utils.ts";
31
- import { buildModelCandidates, inheritsParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
31
+ import { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelOrigin, resolveSubagentModelOverride, type AvailableModelInfo, type ModelOrigin, type ParentModel } from "../shared/model-fallback.ts";
32
32
  import { resolveToolTimeoutMs, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
33
33
  import { resolveModelScopesForAgent, type ModelScopeConfig } from "../shared/model-scope.ts";
34
34
  import { findModelInfo, resolveEffectiveThinking } from "../../shared/model-info.ts";
@@ -82,7 +82,7 @@ import { SUBAGENT_PROCESS_TERMINAL_EVENT } from "../../shared/types.ts";
82
82
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
83
83
  import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
84
84
  import { resolvePermissionRules, type PermissionConfig } from "../shared/permissions.ts";
85
- import { normalizeExtensionBindings, omitExtensionBindingsEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
85
+ import { normalizeExtensionBindings, omitExtensionBindingsEnv, omitInheritedProfileEnv, type ExtensionBindings } from "../shared/extension-bindings.ts";
86
86
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
87
87
 
88
88
  const require = createRequire(import.meta.url);
@@ -602,7 +602,7 @@ function spawnRunner(cfg: Record<string, unknown>, suffix: string, cwd: string,
602
602
  ...backgroundProcessOptions(),
603
603
  stdio: ["ignore", stdoutFd ?? "ignore", stderrFd ?? "ignore"],
604
604
  env: {
605
- ...omitExtensionBindingsEnv(process.env),
605
+ ...omitInheritedProfileEnv(omitExtensionBindingsEnv(process.env)),
606
606
  [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot,
607
607
  [JITI_ALIAS_ENV]: JSON.stringify(hostPeerAliases.aliases),
608
608
  },
@@ -770,7 +770,7 @@ function profileProjectTrustedForCwd(ctx: AsyncExecutionContext, cwd: string): b
770
770
  && path.resolve(ctx.trustedProjectCwd) === path.resolve(cwd);
771
771
  }
772
772
 
773
- function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext, cwd: string): string {
773
+ function profileProjectTrustError(agent: AgentConfig, ctx: AsyncExecutionContext): string {
774
774
  if (ctx.projectTrusted !== true) {
775
775
  return `Agent '${agent.name}' selects sandbox profile '${agent.sandbox}' from project scope, but the project is not trusted. Trust the project and retry.`;
776
776
  }
@@ -788,7 +788,6 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
788
788
  maxSubagentDepth,
789
789
  worktreeBaseDir,
790
790
  worktreeProvider,
791
- worktreeBranchPrefix,
792
791
  asyncDir,
793
792
  } = params;
794
793
  const outputBaseDir = params.outputBaseDir;
@@ -905,7 +904,7 @@ export function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildPa
905
904
  const { stepCwd, instructionCwd, readExistenceCwd, behavior, namespaceOutputPath, outputPath, skillNames } = launchPlan;
906
905
  const profileChildCwd = behaviorCwd ?? stepCwd;
907
906
  if (a.sandbox && (a.source === "project" || a.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, profileChildCwd)) {
908
- throw new AsyncStartValidationError(profileProjectTrustError(a, ctx, profileChildCwd));
907
+ throw new AsyncStartValidationError(profileProjectTrustError(a, ctx));
909
908
  }
910
909
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
911
910
  skillNames,
@@ -1656,7 +1655,7 @@ export function executeAsyncSingle(
1656
1655
  ? resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s0`, 0, worktreeBaseDir)
1657
1656
  : runnerCwd;
1658
1657
  if (sandbox && (agentConfig.source === "project" || agentConfig.override?.scope === "project") && !profileProjectTrustedForCwd(ctx, instructionCwd)) {
1659
- return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx, instructionCwd));
1658
+ return formatAsyncStartError("single", profileProjectTrustError(agentConfig, ctx));
1660
1659
  }
1661
1660
  const readExistenceCwd = params.worktree === true ? runnerCwd : instructionCwd;
1662
1661
  const skillNames = params.skills ?? agentConfig.skills ?? [];
@@ -18,7 +18,7 @@ import {
18
18
  type RunFanoutBudgetDescriptor,
19
19
  } from "../../shared/types.ts";
20
20
  import { SUBAGENT_SANDBOX_PROFILE_ENV, SUBAGENT_SANDBOX_PROJECT_TRUST_ENV } from "../../shared/sandbox-profile.ts";
21
- import { SUBAGENT_PERMISSION_PROFILE_ENV } from "../../shared/permission-profile.ts";
21
+ import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
22
22
  import type { NestedPathEntry } from "./nested-path.ts";
23
23
  import type { McpRuntimeSnapshotHost } from "./mcp-direct-tool-allowlist.ts";
24
24
  import type { PermissionRules } from "./permissions.ts";
@@ -251,7 +251,24 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
251
251
  sandboxEnv !== undefined || permissionProfileEnv !== undefined
252
252
  ? { ...(sandboxEnv ?? {}), ...(permissionProfileEnv ?? {}) }
253
253
  : undefined;
254
- const transientProcessEnv = childEnv ? Object.keys(childEnv) : undefined;
254
+ // The profile key is pinned for every launch, `undefined` included: a child
255
+ // that declares no profile must not inherit the host session's role
256
+ // selection, and one that declares a profile must not be overridden by it
257
+ // (the launcher env wins inside pi-permission-system). It is kept out of
258
+ // `childEnv` so a plain in-process child does not also start receiving the
259
+ // binding and MCP values that only a runner-hosted child used to get.
260
+ const profilePin: Record<string, string | undefined> = {
261
+ [SUBAGENT_PERMISSION_PROFILE_ENV]: input.permissionProfile,
262
+ // Present for every child launch: it is what tells pi-permission-system
263
+ // this selection is authoritative for the child (see the constant).
264
+ [SUBAGENT_PERMISSION_PROFILE_PINNED_ENV]: "1",
265
+ };
266
+ const transientProcessEnv = [
267
+ ...new Set([
268
+ ...(childEnv ? Object.keys(childEnv) : []),
269
+ ...Object.keys(profilePin),
270
+ ]),
271
+ ];
255
272
 
256
273
  const inherited = input.inherited;
257
274
  const fanout = toolPlan.fanoutAuthorized;
@@ -355,8 +372,10 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
355
372
  extensionPaths,
356
373
  ambientExtensions,
357
374
  hooks: createChildHooks(config),
358
- ...(input.host === "runner" || childEnv ? { processEnv: childProcessEnv(input, toolPlan, childEnv) } : {}),
359
- ...(transientProcessEnv ? { transientProcessEnv } : {}),
375
+ ...(input.host === "runner" || childEnv
376
+ ? { processEnv: { ...childProcessEnv(input, toolPlan, childEnv), ...profilePin } }
377
+ : { processEnv: profilePin }),
378
+ transientProcessEnv,
360
379
  runtime: config,
361
380
  noSkills: !input.inheritSkills,
362
381
  noContextFiles: !input.inheritProjectContext,
@@ -1,3 +1,9 @@
1
+ import { SUBAGENT_PERMISSION_PROFILE_ENV, SUBAGENT_PERMISSION_PROFILE_PINNED_ENV } from "../../shared/permission-profile.ts";
2
+ import {
3
+ SUBAGENT_SANDBOX_PROFILE_ENV,
4
+ SUBAGENT_SANDBOX_PROJECT_TRUST_ENV,
5
+ } from "../../shared/sandbox-profile.ts";
6
+
1
7
  export const PI_SUBAGENT_EXTENSION_BINDINGS_ENV = "PI_SUBAGENT_EXTENSION_BINDINGS";
2
8
  export const MAX_EXTENSION_BINDING_NAMESPACES = 16;
3
9
  export const MAX_EXTENSION_BINDINGS_BYTES = 16 * 1024;
@@ -76,3 +82,22 @@ export function omitExtensionBindingsEnv(env: NodeJS.ProcessEnv): NodeJS.Process
76
82
  const { [PI_SUBAGENT_EXTENSION_BINDINGS_ENV]: _extensionBindings, ...sanitized } = env;
77
83
  return sanitized;
78
84
  }
85
+
86
+ /**
87
+ * Drop launcher-owned profile selections from an inherited environment.
88
+ *
89
+ * A runner process must not carry the host session's role selection into the
90
+ * children it launches: each child's own selection is pinned by the child
91
+ * launch, so anything inherited here would silently apply to every step that
92
+ * does not declare one.
93
+ */
94
+ export function omitInheritedProfileEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
95
+ const {
96
+ [SUBAGENT_PERMISSION_PROFILE_ENV]: _permissionProfile,
97
+ [SUBAGENT_PERMISSION_PROFILE_PINNED_ENV]: _permissionProfilePinned,
98
+ [SUBAGENT_SANDBOX_PROFILE_ENV]: _sandboxProfile,
99
+ [SUBAGENT_SANDBOX_PROJECT_TRUST_ENV]: _sandboxTrust,
100
+ ...sanitized
101
+ } = env;
102
+ return sanitized;
103
+ }
@@ -1,6 +1,18 @@
1
1
  /** Shared wire contract for selecting a pi-permission-system profile in a child Pi process. */
2
2
  export const SUBAGENT_PERMISSION_PROFILE_ENV = "PI_SUBAGENT_PERMISSION_PROFILE";
3
3
 
4
+ /**
5
+ * Marks a child process whose profile selection was pinned by its launcher.
6
+ *
7
+ * The selection key alone cannot express "this child was launched with no
8
+ * profile": clearing it looks exactly like a host session that never selected
9
+ * one. pi-permission-system therefore freezes the launcher's selection only when
10
+ * this marker is present, which keeps a host session reading the value live so a
11
+ * mid-session role change still applies.
12
+ */
13
+ export const SUBAGENT_PERMISSION_PROFILE_PINNED_ENV =
14
+ "PI_SUBAGENT_PERMISSION_PROFILE_PINNED";
15
+
4
16
  const MAX_PERMISSION_PROFILE_NAME_LENGTH = 128;
5
17
  const PERMISSION_PROFILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
6
18