pi-subagents 0.85.0 → 0.87.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 (97) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-O7CPL6H4.js → chunk-2D2DQGC2.js} +9 -9
  5. package/bundle/{chunk-KZ34KQQH.js → chunk-2NY5PCKQ.js} +11 -5
  6. package/bundle/{chunk-PVIVCDG2.js → chunk-3CVOAS77.js} +2 -2
  7. package/bundle/{chunk-N7B2KD74.js → chunk-6O7YH2QV.js} +1 -1
  8. package/bundle/{chunk-IQIWF2VX.js → chunk-AIL46SZU.js} +8 -6
  9. package/bundle/{chunk-H2NLFTC5.js → chunk-BFF6YDK6.js} +1 -1
  10. package/bundle/{chunk-UX4SCV5N.js → chunk-C3KWLXDH.js} +159 -98
  11. package/bundle/{chunk-GCSLVFCX.js → chunk-C5QWQSSM.js} +1 -1
  12. package/bundle/{chunk-3UZ5FVVJ.js → chunk-DGTZKYIE.js} +39 -34
  13. package/bundle/{chunk-KDMFBYFM.js → chunk-ESWW6XSX.js} +1 -1
  14. package/bundle/{chunk-WOVMHDES.js → chunk-EYGBK6CE.js} +194 -94
  15. package/bundle/{chunk-CS4O36CZ.js → chunk-HDICKROY.js} +5 -5
  16. package/bundle/{chunk-DV2NCNPR.js → chunk-JLDQ6YUR.js} +12 -12
  17. package/bundle/{chunk-RQAUNAWG.js → chunk-LFKMM3UH.js} +2 -2
  18. package/bundle/{chunk-L2ENOFVZ.js → chunk-LZKVUWIY.js} +66 -26
  19. package/bundle/{chunk-RV5OGHLO.js → chunk-M2VBGET6.js} +2 -2
  20. package/bundle/{chunk-HFTBF7SG.js → chunk-OOE3R7IQ.js} +1 -1
  21. package/bundle/{chunk-JNXT3MPI.js → chunk-OTLDAYEQ.js} +5 -5
  22. package/bundle/{chunk-JWYG26RE.js → chunk-OZCPYJEY.js} +80 -37
  23. package/bundle/{chunk-LGMILZNE.js → chunk-PGU4TZV3.js} +79 -32
  24. package/bundle/{chunk-KEY3UQMQ.js → chunk-SIAQXPJ4.js} +6 -8
  25. package/bundle/{chunk-QO75KJBT.js → chunk-USRX7QXD.js} +2 -2
  26. package/bundle/{chunk-7MAE3DJV.js → chunk-VFUFOZBU.js} +1 -1
  27. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  28. package/bundle/{chunk-T5V5BRCL.js → chunk-W52LJANO.js} +1 -1
  29. package/bundle/{chunk-PHZP3KHB.js → chunk-XSDYTXHF.js} +18 -11
  30. package/bundle/{chunk-LTPH2DXH.js → chunk-XV7RTWTS.js} +3 -3
  31. package/bundle/{chunk-JO67XSKD.js → chunk-YEXKJJVS.js} +12 -7
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/workflow-resources.js +1 -1
  38. package/docs/agents.md +9 -3
  39. package/docs/configuration.md +14 -6
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/tool-reference.md +3 -0
  43. package/package.json +1 -1
  44. package/skills/pi-subagents/SKILL.md +7 -4
  45. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  46. package/src/agents/agent-management.js +10 -6
  47. package/src/agents/agent-serializer.d.ts +2 -0
  48. package/src/agents/agent-serializer.js +1 -1
  49. package/src/agents/agents.js +37 -12
  50. package/src/api/preflight.d.ts +3 -1
  51. package/src/api/preflight.js +2 -0
  52. package/src/extension/index.js +4 -2
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/tool-activation.js +10 -1
  56. package/src/extension/tool-description.d.ts +1 -1
  57. package/src/extension/tool-description.js +8 -8
  58. package/src/runs/background/async-execution.d.ts +2 -1
  59. package/src/runs/background/async-execution.js +4 -2
  60. package/src/runs/background/run-status.js +5 -4
  61. package/src/runs/background/runner-aliases.js +15 -0
  62. package/src/runs/background/subagent-runner.js +6 -6
  63. package/src/runs/background/wait-subscriptions.js +124 -12
  64. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  65. package/src/runs/foreground/async-stop-action.js +9 -1
  66. package/src/runs/foreground/execution.js +1 -0
  67. package/src/runs/foreground/subagent-executor.d.ts +1 -0
  68. package/src/runs/foreground/subagent-executor.js +51 -8
  69. package/src/runs/shared/acceptance.js +69 -26
  70. package/src/runs/shared/child-session.d.ts +5 -4
  71. package/src/runs/shared/child-session.js +43 -33
  72. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  73. package/src/runs/shared/external-cli-contract.js +18 -13
  74. package/src/runs/shared/herdr-placed-run.js +3 -2
  75. package/src/runs/shared/mcp-config-sources.d.ts +2 -1
  76. package/src/runs/shared/mcp-config-sources.js +1 -1
  77. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -1
  78. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -6
  79. package/src/runs/shared/model-resolution.d.ts +19 -4
  80. package/src/runs/shared/model-resolution.js +50 -51
  81. package/src/runs/shared/structured-output.js +10 -3
  82. package/src/shared/artifacts.js +25 -13
  83. package/src/shared/pruned-fork.js +2 -2
  84. package/src/shared/types.d.ts +71 -48
  85. package/src/tui/render.js +83 -22
  86. package/src/watchdog/model-selection.js +2 -2
  87. package/src/watchdog/review.js +2 -2
  88. package/src/workflows/scripted-workflow.d.ts +2 -0
  89. package/src/workflows/scripted-workflow.js +103 -39
  90. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  91. package/src/workflows/structured-workflow-scripts.js +32 -11
  92. package/src/workflows/workflow-receipt.js +36 -53
  93. package/src/workflows/workflow-resources.js +4 -4
  94. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  95. package/src/workflows/workflow-resume-claim.js +1 -1
  96. package/src/workflows/workflow-resume.d.ts +1 -1
  97. package/src/workflows/workflow-resume.js +3 -1
@@ -24,7 +24,7 @@ import { commandAction } from "./command-action.js";
24
24
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.js";
25
25
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.js";
26
26
  import { childWatchdogProgressForModel } from "../../watchdog/child-status.js";
27
- import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, scopedModelIdsFromContext } from "../shared/model-resolution.js";
27
+ import { knownModelProviders, normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, scopedModelIdsFromContext } from "../shared/model-resolution.js";
28
28
  import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.js";
29
29
  import { formatRetainedChildren, listRetainedChildren } from "../background/retained-children.js";
30
30
  import { resolveModelScopesForAgent } from "../shared/model-scope.js";
@@ -1063,6 +1063,7 @@ function appendStepToAsyncChain(input) {
1063
1063
  parentProviderRegistry: input.ctx.modelRegistry,
1064
1064
  currentModel: parentModel,
1065
1065
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1066
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1066
1067
  modelScope: discoveredForAppend.modelScope,
1067
1068
  modelResponseAliases: input.deps.config.modelResponseAliases,
1068
1069
  interactive: input.ctx.hasUI,
@@ -1551,6 +1552,7 @@ async function resumeExternalJobFollowUp(input) {
1551
1552
  parentProviderRegistry: input.ctx.modelRegistry,
1552
1553
  currentModel: parentModel,
1553
1554
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1555
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1554
1556
  modelScope: input.modelScope,
1555
1557
  modelResponseAliases: input.deps.config.modelResponseAliases,
1556
1558
  interactive: input.ctx.hasUI,
@@ -1855,6 +1857,7 @@ async function resumeAsyncRun(input) {
1855
1857
  parentProviderRegistry: input.ctx.modelRegistry,
1856
1858
  currentModel: parentModel,
1857
1859
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
1860
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
1858
1861
  modelScope,
1859
1862
  modelResponseAliases: input.deps.config.modelResponseAliases,
1860
1863
  runnerLaunchers: input.deps.config.runnerLaunchers,
@@ -1998,6 +2001,7 @@ async function resumeAsyncRun(input) {
1998
2001
  parentProviderRegistry: input.ctx.modelRegistry,
1999
2002
  currentModel: parentModel,
2000
2003
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
2004
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
2001
2005
  modelScope,
2002
2006
  // Absence in the retained contract is meaningful; never acquire current aliases.
2003
2007
  modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
@@ -2874,7 +2878,7 @@ function resolveStaticLaunchSummary(input) {
2874
2878
  const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel, input.scopedModelIds);
2875
2879
  const model = externalRunner
2876
2880
  ? undefined
2877
- : resolveEffectiveSubagentModel(input.explicitModel, agentConfig?.model, input.parentModel, input.availableModels, agentConfig?.modelProvider ?? input.currentProvider, modelScopes.length === 0 ? {} : { scope: modelScopes });
2881
+ : resolveEffectiveSubagentModel(input.explicitModel, agentConfig?.model, input.parentModel, input.availableModels, agentConfig?.modelProvider ?? input.currentProvider, { scope: modelScopes, knownProviders: input.knownProviders });
2878
2882
  const thinkingOverride = externalRunner ? undefined : input.thinkingOverrideForTask();
2879
2883
  const thinking = externalRunner ? undefined : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
2880
2884
  return {
@@ -2892,6 +2896,7 @@ function collectStaticLaunchSummaries(input) {
2892
2896
  parentModel: input.parentModel,
2893
2897
  scopedModelIds: input.scopedModelIds,
2894
2898
  availableModels: input.availableModels,
2899
+ knownProviders: input.knownProviders,
2895
2900
  currentProvider: input.currentProvider,
2896
2901
  modelScope: input.modelScope,
2897
2902
  thinkingOverrideForTask: input.thinkingOverrideForTask,
@@ -3171,6 +3176,7 @@ async function runAsyncPath(data, deps) {
3171
3176
  parentProviderRegistry: ctx.modelRegistry,
3172
3177
  currentModel: parentModel,
3173
3178
  scopedModelIds: data.scopedModelIds,
3179
+ knownProviders: knownModelProviders(ctx.modelRegistry),
3174
3180
  modelScope: data.modelScope,
3175
3181
  modelResponseAliases: deps.config.modelResponseAliases,
3176
3182
  runnerLaunchers: deps.config.runnerLaunchers,
@@ -3215,8 +3221,9 @@ async function runAsyncPath(data, deps) {
3215
3221
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job"
3216
3222
  ? params.model ?? (externalRunnerWithoutExplicitModel ? undefined : a.model)
3217
3223
  : resolveEffectiveSubagentModel(params.model, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, {
3218
- ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3224
+ scope: modelScopes,
3219
3225
  source: modelOrigin === "explicit" ? "explicit" : "inherited",
3226
+ knownProviders: asyncCtx.knownProviders,
3220
3227
  });
3221
3228
  const modelOverrideFromParent = modelOrigin === "inherited";
3222
3229
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -3644,6 +3651,7 @@ async function runSinglePath(data, deps) {
3644
3651
  const parentModel = data.parentModel;
3645
3652
  const currentProvider = parentModel?.provider;
3646
3653
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
3654
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
3647
3655
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
3648
3656
  let task = typeof params.task === "string" ? params.task : "";
3649
3657
  const modelOrigin = resolveModelOrigin({
@@ -3653,8 +3661,9 @@ async function runSinglePath(data, deps) {
3653
3661
  parentModel,
3654
3662
  });
3655
3663
  let modelOverride = resolveEffectiveSubagentModel(params.model, agentConfig.model, parentModel, availableModels, agentConfig.modelProvider ?? currentProvider, {
3656
- ...(modelScopes.length === 0 ? {} : { scope: modelScopes }),
3664
+ scope: modelScopes,
3657
3665
  source: modelOrigin === "explicit" ? "explicit" : "inherited",
3666
+ knownProviders,
3658
3667
  });
3659
3668
  const modelOverrideFromParent = modelOrigin === "inherited";
3660
3669
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: agentConfig.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -3902,6 +3911,7 @@ async function runSinglePath(data, deps) {
3902
3911
  thinkingCeiling: agentConfig.maxThinking,
3903
3912
  extensionBindings: params.extensionBindings,
3904
3913
  availableModels,
3914
+ knownProviders,
3905
3915
  modelResponseAliases,
3906
3916
  preferredModelProvider: currentProvider,
3907
3917
  modelScope: modelScopes,
@@ -5179,6 +5189,7 @@ export function createSubagentExecutor(deps) {
5179
5189
  const controller = new AbortController();
5180
5190
  deps.state.workflowControllers ??= new Map();
5181
5191
  deps.state.workflowChildStops ??= new Map();
5192
+ deps.state.workflowDrains ??= new Map();
5182
5193
  deps.state.workflowControllers.set(workflowRunId, controller);
5183
5194
  workflowCapacity?.markWorkflowStarted();
5184
5195
  if (workflowCapacity)
@@ -5809,6 +5820,36 @@ export function createSubagentExecutor(deps) {
5809
5820
  else
5810
5821
  deps.state.workflowChildStops?.delete(workflowRunId);
5811
5822
  },
5823
+ registerDrain: (drain) => {
5824
+ if (!drain)
5825
+ deps.state.workflowDrains?.delete(workflowRunId);
5826
+ else
5827
+ deps.state.workflowDrains?.set(workflowRunId, () => {
5828
+ if (workflowRunEvidence.drainRequestedAt === undefined) {
5829
+ // The marker must be on disk before anything is stopped: without it a reload during the drain would resume the run.
5830
+ const previousWorkflow = status.workflow;
5831
+ workflowRunEvidence.drainRequestedAt = Date.now();
5832
+ status.workflow = { ...(previousWorkflow ?? { trace: [], emits: [], console: [] }), drainRequestedAt: workflowRunEvidence.drainRequestedAt };
5833
+ let saved = false;
5834
+ try {
5835
+ persist();
5836
+ saved = runPersistence.pendingCount() === 0;
5837
+ }
5838
+ catch (error) {
5839
+ console.error(`Failed to save the drain request for async workflow '${workflowRunId}':`, error);
5840
+ }
5841
+ if (!saved) {
5842
+ delete workflowRunEvidence.drainRequestedAt;
5843
+ status.workflow = previousWorkflow;
5844
+ // Replaces a queued write that still carries the marker.
5845
+ persist({ tolerateStatusWriteFailure: true });
5846
+ return { ok: false };
5847
+ }
5848
+ }
5849
+ // Deferred so a full stop that stops the last running child aborts with its own reason first.
5850
+ return { ok: true, started: drain(() => queueMicrotask(() => controller.abort(new Error("Workflow drained: started children finished; no new children were started.")))) };
5851
+ });
5852
+ },
5812
5853
  ...(workflowState ? { state: workflowState } : {}),
5813
5854
  onTrace: updateTrace,
5814
5855
  onChildSettled: (notification) => {
@@ -6151,8 +6192,7 @@ export function createSubagentExecutor(deps) {
6151
6192
  const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
6152
6193
  const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
6153
6194
  const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
6154
- // A top-level artifact file: outside outputs/, where children save their reports, and
6155
- // within artifact retention, which only removes top-level files.
6195
+ // Outside outputs/ so it cannot overwrite a child's report.
6156
6196
  const workflowFullResultPath = path.join(workflowArtifactsDir, `${sanitizeRunPathSegment(foregroundWorkflowRunId)}_workflow-result.md`);
6157
6197
  const claimedOutputPaths = new Map();
6158
6198
  const childOutputOverrides = new Map();
@@ -7039,6 +7079,8 @@ export function createSubagentExecutor(deps) {
7039
7079
  }
7040
7080
  if (action === "stop") {
7041
7081
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
7082
+ if (paramsWithResolvedCwd.drain && paramsWithResolvedCwd.childId !== undefined)
7083
+ return { content: [{ type: "text", text: "action='stop' drain applies to a whole workflow; omit childId." }], isError: true, details: { mode: "management", results: [] } };
7042
7084
  // Whole-workflow stops reach stopAsyncRun below, which stops a live workflow in-process.
7043
7085
  const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== undefined ? resolveLiveWorkflowRunId(deps, targetRunId) : undefined;
7044
7086
  if (workflowRunId && paramsWithResolvedCwd.childId !== undefined) {
@@ -7085,7 +7127,7 @@ export function createSubagentExecutor(deps) {
7085
7127
  if (paramsWithResolvedCwd.dir) {
7086
7128
  try {
7087
7129
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
7088
- const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId);
7130
+ const stopResult = stopAsyncRun(deps.state, location.resolvedId ?? targetRunId ?? path.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps.kill, location, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
7089
7131
  return stopResult ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
7090
7132
  }
7091
7133
  catch (error) {
@@ -7106,7 +7148,7 @@ export function createSubagentExecutor(deps) {
7106
7148
  return { content: [{ type: "text", text: "action='stop' supports current-session top-level async runs only." }], isError: true, details: { mode: "management", results: [] } };
7107
7149
  if (resolved?.kind === "foreground")
7108
7150
  return { content: [{ type: "text", text: "action='stop' supports async runs only. Use action='interrupt' for foreground runs." }], isError: true, details: { mode: "management", results: [] } };
7109
- const stopResult = stopAsyncRun(deps.state, resolved?.kind === "async" ? resolved.id : targetRunId, deps.kill, resolved?.kind === "async" ? resolved.location : undefined, paramsWithResolvedCwd.childId);
7151
+ const stopResult = stopAsyncRun(deps.state, resolved?.kind === "async" ? resolved.id : targetRunId, deps.kill, resolved?.kind === "async" ? resolved.location : undefined, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
7110
7152
  if (stopResult)
7111
7153
  return stopResult;
7112
7154
  return {
@@ -7651,6 +7693,7 @@ export function createSubagentExecutor(deps) {
7651
7693
  parentModel: requestParentModel,
7652
7694
  scopedModelIds: scopedModelIdsFromContext(ctx),
7653
7695
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
7696
+ knownProviders: knownModelProviders(ctx.modelRegistry),
7654
7697
  currentProvider: requestParentModel?.provider,
7655
7698
  modelScope,
7656
7699
  thinkingOverrideForTask,
@@ -1149,13 +1149,34 @@ function verifyRedactionEnv(env) {
1149
1149
  return value.length >= 4 && SENSITIVE_ENV_KEY_PATTERN.test(key);
1150
1150
  }));
1151
1151
  }
1152
- function redactVerifyEnv(value, env) {
1152
+ function verifySecrets(env) {
1153
+ return [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1154
+ }
1155
+ function redactSecrets(value, secrets) {
1153
1156
  let redacted = value;
1154
- const secrets = [...new Set(Object.values(verifyRedactionEnv(env)).filter(Boolean))].sort((left, right) => right.length - left.length);
1155
1157
  for (const secret of secrets)
1156
1158
  redacted = redacted.replaceAll(secret, "[REDACTED]");
1157
1159
  return redacted;
1158
1160
  }
1161
+ function redactVerifyEnv(value, env) {
1162
+ return redactSecrets(value, verifySecrets(env));
1163
+ }
1164
+ /** Numbers are matched on their source text: parsing rounds or respells them (12345678901234567890, 1.50), which would hide a secret. */
1165
+ function parseRedactedVerifyValue(text, secrets) {
1166
+ return JSON.parse(text, (_key, value, context) => {
1167
+ if (typeof value === "string")
1168
+ return redactSecrets(value, secrets);
1169
+ if (typeof value === "number" && secrets.length > 0) {
1170
+ // Node 22+ and Bun pass the source text; without it, fail closed.
1171
+ const source = context?.source;
1172
+ return source !== undefined && redactSecrets(source, secrets) === source ? value : "[REDACTED]";
1173
+ }
1174
+ if (value && typeof value === "object" && !Array.isArray(value)) {
1175
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactSecrets(key, secrets), item]));
1176
+ }
1177
+ return value;
1178
+ });
1179
+ }
1159
1180
  function uniqueStrings(items) {
1160
1181
  return unique(items.map((item) => item?.trim()).filter((item) => Boolean(item)));
1161
1182
  }
@@ -1223,34 +1244,49 @@ const TYPED_VERIFY_OUTPUT_MAX_BYTES = 12_000;
1223
1244
  * A passing `output: "json"` command must print one JSON document on stdout.
1224
1245
  * The parsed value becomes the run's structured output; anything else turns
1225
1246
  * the passing run into a failed one so acceptance rejects rather than
1226
- * silently dropping the verdict. Stdout is already bounded by trimOutput, so a
1227
- * truncated document is detected by its marker instead of a parse guess.
1247
+ * silently dropping the verdict. The raw stdout is parsed, because the stored
1248
+ * stdout is redacted and redaction can hit JSON syntax (`true` in KDE_FULL_SESSION).
1249
+ * The schema checks the raw value so a redacted string cannot fail a correct
1250
+ * gate. Error messages quote parts of their input (a parse error quotes ~10
1251
+ * chars, schema paths escape `/` and `~`), so each one is built from the
1252
+ * redacted text or value, never the raw one.
1228
1253
  */
1229
- async function applyTypedVerifyOutput(command, run) {
1254
+ async function applyTypedVerifyOutput(command, run, rawStdout) {
1230
1255
  if (run.status !== "passed")
1231
1256
  return;
1232
- const stdout = run.stdout ?? "";
1257
+ const secrets = verifySecrets(command.env);
1258
+ const stdout = rawStdout.trim();
1233
1259
  const fail = (message) => {
1234
1260
  run.status = "failed";
1235
- run.structuredOutputError = message;
1261
+ run.structuredOutputError = redactSecrets(message, secrets);
1236
1262
  };
1237
- if (!stdout.trim())
1263
+ if (!stdout)
1238
1264
  return fail("output: \"json\" command printed nothing on stdout.");
1239
- if (stdout.endsWith("...[truncated]"))
1265
+ if (stdout.length > TYPED_VERIFY_OUTPUT_MAX_BYTES)
1240
1266
  return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
1241
1267
  let value;
1242
1268
  try {
1243
1269
  value = JSON.parse(stdout);
1244
1270
  }
1245
- catch (error) {
1246
- return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1271
+ catch {
1272
+ let reason = "parse failed";
1273
+ try {
1274
+ JSON.parse(redactSecrets(stdout, secrets));
1275
+ }
1276
+ catch (error) {
1277
+ reason = error instanceof Error ? error.message : String(error);
1278
+ }
1279
+ return fail(`output: "json" stdout is not valid JSON: ${reason}`);
1247
1280
  }
1281
+ const redactedValue = parseRedactedVerifyValue(stdout, secrets);
1248
1282
  if (command.schema) {
1249
1283
  const validation = await validateStructuredOutputValue(command.schema, value);
1250
- if (validation.status === "invalid")
1251
- return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
1284
+ if (validation.status === "invalid") {
1285
+ const redactedValidation = await validateStructuredOutputValue(command.schema, redactedValue);
1286
+ return fail(`output: "json" stdout does not match gate.schema${redactedValidation.status === "invalid" ? `: ${redactedValidation.message}` : "."}`);
1287
+ }
1252
1288
  }
1253
- run.structuredOutput = value;
1289
+ run.structuredOutput = redactedValue;
1254
1290
  }
1255
1291
  /** The first typed verify result on a ledger, if any command produced one. */
1256
1292
  export function typedVerifyOutput(ledger) {
@@ -1258,6 +1294,13 @@ export function typedVerifyOutput(ledger) {
1258
1294
  return run ? { value: run.structuredOutput } : undefined;
1259
1295
  }
1260
1296
  async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1297
+ // Typed gates read inputs (a report file, a log) that can change without
1298
+ // the tracked tree changing, so their verdicts are never reused.
1299
+ if (command.output === "json") {
1300
+ const { run, rawStdout } = await runVerifyCommand(command, defaultCwd, options);
1301
+ await applyTypedVerifyOutput(command, run, rawStdout);
1302
+ return run;
1303
+ }
1261
1304
  const cwd = command.cwd ? path.resolve(defaultCwd, command.cwd) : defaultCwd;
1262
1305
  let workspaceState;
1263
1306
  try {
@@ -1266,10 +1309,8 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1266
1309
  catch {
1267
1310
  workspaceState = undefined;
1268
1311
  }
1269
- // Typed gates read inputs (a report file, a log) that can change without
1270
- // the tracked tree changing, so their verdicts are never reused.
1271
- if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
1272
- return runVerifyCommand(command, defaultCwd, options);
1312
+ if (!workspaceState || !options.artifactsDir || !options.runId) {
1313
+ return (await runVerifyCommand(command, defaultCwd, options)).run;
1273
1314
  }
1274
1315
  const envKeys = Object.keys(command.env ?? {}).sort();
1275
1316
  const envHash = hash(JSON.stringify(Object.fromEntries(Object.entries(effectiveVerifyEnv(command.env)).sort(([left], [right]) => left.localeCompare(right)))));
@@ -1295,7 +1336,7 @@ async function runMemoizedVerifyCommand(command, defaultCwd, options = {}) {
1295
1336
  catch {
1296
1337
  // A cache miss or unreadable artifact must not prevent host verification.
1297
1338
  }
1298
- const result = await runVerifyCommand(command, defaultCwd, options);
1339
+ const { run: result } = await runVerifyCommand(command, defaultCwd, options);
1299
1340
  const evidenced = { ...result, artifactPath, cacheKey, memoized: false, envKeys, envHash, workspaceState };
1300
1341
  try {
1301
1342
  fs.mkdirSync(path.dirname(artifactPath), { recursive: true });
@@ -1363,6 +1404,7 @@ export function quoteExecutableForShell(command, platform = process.platform) {
1363
1404
  }
1364
1405
  return command;
1365
1406
  }
1407
+ /** `rawStdout` is unredacted and never stored; only typed output parsing reads it. */
1366
1408
  function runVerifyCommand(command, defaultCwd, options = {}) {
1367
1409
  return new Promise((resolve) => {
1368
1410
  const startedAt = Date.now();
@@ -1388,11 +1430,14 @@ function runVerifyCommand(command, defaultCwd, options = {}) {
1388
1430
  clearTimeout(hardKill);
1389
1431
  options.signal?.removeEventListener("abort", abortVerification);
1390
1432
  resolve({
1391
- id: command.id,
1392
- command: command.command,
1393
- cwd,
1394
- durationMs: Date.now() - startedAt,
1395
- ...result,
1433
+ run: {
1434
+ id: command.id,
1435
+ command: command.command,
1436
+ cwd,
1437
+ durationMs: Date.now() - startedAt,
1438
+ ...result,
1439
+ },
1440
+ rawStdout: stdout,
1396
1441
  });
1397
1442
  };
1398
1443
  const abortVerification = () => {
@@ -1531,8 +1576,6 @@ export async function evaluateAcceptance(input) {
1531
1576
  artifactsDir: input.artifactsDir,
1532
1577
  runId: input.runId,
1533
1578
  });
1534
- if (command.output === "json")
1535
- await applyTypedVerifyOutput(command, run);
1536
1579
  ledger.verifyRuns.push(run);
1537
1580
  if (input.signal?.aborted)
1538
1581
  break;
@@ -122,9 +122,9 @@ export interface ChildSession {
122
122
  };
123
123
  /** Event-updated pane-native status; reading it performs no network work. */
124
124
  readonly placementSnapshot?: unknown;
125
- /** Set by the foreground host once the run detached; `factory.dispose()` leaves such children running. */
125
+ /** Set by the foreground host once the run detached; factory disposal leaves such children running. */
126
126
  detached?: boolean;
127
- /** Set by `factory.dispose()` before it aborts the child, so the host can report the stop truthfully. */
127
+ /** Set by factory disposal before it aborts the child, so the host can report the stop truthfully. */
128
128
  shutDown?: boolean;
129
129
  }
130
130
  export declare function childSessionHasQueuedMessages(session: ChildSession | undefined): boolean;
@@ -132,6 +132,8 @@ export interface ChildSessionFactory {
132
132
  create(launch: ChildSessionLaunch): Promise<ChildSession>;
133
133
  /** Abort and dispose every live attached child; detached children keep running and hold the shared runtime. */
134
134
  dispose(): Promise<void>;
135
+ /** `dispose()` for only the children `parentSessionFile`'s session launched (undefined: sessions without a file); pi-web shuts sessions down one at a time. */
136
+ disposeForParent(parentSessionFile: string | undefined): Promise<void>;
135
137
  }
136
138
  export type PiCodingAgentModule = typeof import("@earendil-works/pi-coding-agent");
137
139
  export interface DefaultChildSessionFactoryOptions {
@@ -175,6 +177,5 @@ export declare function setChildSessionFactory(factory: ChildSessionFactory | un
175
177
  */
176
178
  export declare function childSessionFactoryModule(): string | undefined;
177
179
  export declare function setChildSessionFactoryModule(modulePath: string | undefined): void;
178
- /** Abort and dispose every live in-process child and release the shared runtime. */
179
- export declare function disposeChildSessions(): Promise<void>;
180
+ export declare function disposeChildSessionsForParent(parentSessionFile: string | undefined): Promise<void>;
180
181
  export {};
@@ -387,12 +387,15 @@ export function createDefaultChildSessionFactory(options = {}) {
387
387
  const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
388
388
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
389
389
  let runtime;
390
- const live = new Set();
390
+ const live = new Map();
391
391
  /** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
392
392
  const shutdowns = new Set();
393
393
  /** Launches still waiting for their MCP tools; `dispose()` ends the wait and waits for their shutdown. */
394
394
  const mcpWaits = new Map();
395
- let disposals = 0;
395
+ let globalDisposals = 0;
396
+ /** Per-parent disposal epochs: a child's launch aborts only when its own parent's scope (or the whole process) was disposed while it started. */
397
+ const parentDisposals = new Map();
398
+ const parentDisposalEpoch = (parent) => parentDisposals.get(parent) ?? 0;
396
399
  const sharedRuntime = async (pi) => {
397
400
  runtime ??= pi.ModelRuntime.create().catch((error) => {
398
401
  runtime = undefined;
@@ -400,9 +403,32 @@ export function createDefaultChildSessionFactory(options = {}) {
400
403
  });
401
404
  return runtime;
402
405
  };
406
+ const disposeMatching = async (matches) => {
407
+ for (const [cancel, wait] of mcpWaits)
408
+ if (matches(wait.parent))
409
+ cancel.abort();
410
+ const children = [...live.keys()].filter((child) => !child.detached && matches(live.get(child)));
411
+ for (const child of children)
412
+ child.shutDown = true;
413
+ await Promise.allSettled(children.map((child) => child.abort()));
414
+ for (const child of children) {
415
+ try {
416
+ void child.dispose();
417
+ }
418
+ catch { /* best effort */ }
419
+ }
420
+ await Promise.allSettled([
421
+ ...shutdowns,
422
+ ...[...mcpWaits.values()].filter((wait) => matches(wait.parent)).map((wait) => wait.ready),
423
+ ]);
424
+ if (live.size === 0)
425
+ runtime = undefined;
426
+ };
403
427
  return {
404
428
  async create(launch) {
405
- const disposalsAtStart = disposals;
429
+ const globalDisposalsAtStart = globalDisposals;
430
+ const parentEpochAtStart = parentDisposalEpoch(launch.parentSessionFile);
431
+ const disposedSinceStart = () => globalDisposals !== globalDisposalsAtStart || parentDisposalEpoch(launch.parentSessionFile) !== parentEpochAtStart;
406
432
  const pi = await loadPiCodingAgent();
407
433
  const builtinMcpTools = launch.builtinMcpTools ?? [];
408
434
  let readinessTool;
@@ -603,12 +629,12 @@ export function createDefaultChildSessionFactory(options = {}) {
603
629
  if (builtinMcp) {
604
630
  const cancel = new AbortController();
605
631
  const signal = launch.signal ? AbortSignal.any([cancel.signal, launch.signal]) : cancel.signal;
606
- if (disposals !== disposalsAtStart)
632
+ if (disposedSinceStart())
607
633
  cancel.abort();
608
634
  const ready = (async () => {
609
635
  try {
610
636
  await builtinMcp.waitForTools(signal, () => loader.getExtensions().errors.find(({ path }) => path === "builtin:mcp")?.error);
611
- if (disposals !== disposalsAtStart)
637
+ if (disposedSinceStart())
612
638
  throw new Error("The child session factory was disposed while the child waited for its MCP tools.");
613
639
  if (signal.aborted)
614
640
  throw new Error("The child launch was cancelled while waiting for its MCP tools.");
@@ -621,7 +647,7 @@ export function createDefaultChildSessionFactory(options = {}) {
621
647
  throw error;
622
648
  }
623
649
  })();
624
- mcpWaits.set(cancel, ready);
650
+ mcpWaits.set(cancel, { ready, parent: launch.parentSessionFile });
625
651
  try {
626
652
  await ready;
627
653
  }
@@ -656,26 +682,16 @@ export function createDefaultChildSessionFactory(options = {}) {
656
682
  get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
657
683
  get contextWindow() { return session.model?.contextWindow; },
658
684
  };
659
- live.add(child);
685
+ live.set(child, launch.parentSessionFile);
660
686
  return child;
661
687
  },
662
688
  async dispose() {
663
- disposals += 1;
664
- for (const cancel of mcpWaits.keys())
665
- cancel.abort();
666
- const children = [...live].filter((child) => !child.detached);
667
- for (const child of children)
668
- child.shutDown = true;
669
- await Promise.allSettled(children.map((child) => child.abort()));
670
- for (const child of children) {
671
- try {
672
- void child.dispose();
673
- }
674
- catch { /* best effort */ }
675
- }
676
- await Promise.allSettled([...shutdowns, ...mcpWaits.values()]);
677
- if (live.size === 0)
678
- runtime = undefined;
689
+ globalDisposals += 1;
690
+ await disposeMatching(() => true);
691
+ },
692
+ async disposeForParent(parentSessionFile) {
693
+ parentDisposals.set(parentSessionFile, parentDisposalEpoch(parentSessionFile) + 1);
694
+ await disposeMatching((parent) => parent === parentSessionFile);
679
695
  },
680
696
  };
681
697
  }
@@ -691,10 +707,8 @@ function createLazyPlacementFactory(local) {
691
707
  const factory = async () => placed ??= (await import("./herdr-placed-run.js")).createPlacementAwareChildSessionFactory(local);
692
708
  return {
693
709
  async create(launch) { return launch.machine ? (await factory()).create(launch) : local.create(launch); },
694
- async dispose() { if (placed)
695
- await placed.dispose();
696
- else
697
- await local.dispose(); },
710
+ async dispose() { await (placed ?? local).dispose(); },
711
+ async disposeForParent(parentSessionFile) { await (placed ?? local).disposeForParent(parentSessionFile); },
698
712
  };
699
713
  }
700
714
  /** Default factory including pane-native placement; detached runners use the same boundary. */
@@ -719,10 +733,6 @@ export function childSessionFactoryModule() {
719
733
  export function setChildSessionFactoryModule(modulePath) {
720
734
  activeFactoryModule = modulePath;
721
735
  }
722
- /** Abort and dispose every live in-process child and release the shared runtime. */
723
- export async function disposeChildSessions() {
724
- const factory = activeFactory;
725
- if (!factory)
726
- return;
727
- await factory.dispose();
736
+ export async function disposeChildSessionsForParent(parentSessionFile) {
737
+ await activeFactory?.disposeForParent(parentSessionFile);
728
738
  }
@@ -12,6 +12,55 @@ export declare function validateCodeOwnedProfileRunner(agent: {
12
12
  adapter?: string;
13
13
  };
14
14
  }): string | undefined;
15
+ export declare const EXTERNAL_CLI_ADAPTER_SAFETY: {
16
+ readonly "codex-exec": {
17
+ readonly sandbox: "read-only";
18
+ readonly approvalPolicy: "never";
19
+ readonly ephemeral: true;
20
+ };
21
+ readonly "codex-exec-writer": {
22
+ readonly access: "workspace-write";
23
+ readonly sandbox: "workspace-write";
24
+ readonly approvalPolicy: "never";
25
+ readonly ephemeral: true;
26
+ };
27
+ readonly "claude-code": {
28
+ readonly access: "read-only";
29
+ readonly authentication: "existing-cli-required";
30
+ readonly permissionMode: "plan";
31
+ readonly tools: "none";
32
+ readonly mcp: "empty-strict";
33
+ readonly settingSources: "user";
34
+ readonly userSettingsTrust: "required";
35
+ readonly sessionPersistence: false;
36
+ };
37
+ readonly "claude-code-writer": {
38
+ readonly access: "workspace-write";
39
+ readonly authentication: "existing-cli-required";
40
+ readonly permissionMode: "acceptEdits";
41
+ readonly tools: "Read,Write,Edit,Glob,Grep";
42
+ readonly mcp: "empty-strict";
43
+ readonly settingSources: "user";
44
+ readonly userSettingsTrust: "required";
45
+ readonly sessionPersistence: false;
46
+ };
47
+ readonly "cursor-agent": {
48
+ readonly access: "read-only";
49
+ readonly authentication: "cursor-api-key-or-existing-login";
50
+ readonly mode: "ask";
51
+ readonly sandbox: "enabled";
52
+ readonly workspaceTrust: "existing-required";
53
+ readonly sessionReuse: false;
54
+ };
55
+ readonly "cursor-agent-writer": {
56
+ readonly access: "workspace-write";
57
+ readonly authentication: "cursor-api-key-or-existing-login";
58
+ readonly mode: "print";
59
+ readonly sandbox: "enabled";
60
+ readonly workspaceTrust: "existing-required";
61
+ readonly sessionReuse: false;
62
+ };
63
+ };
15
64
  export declare function parseExternalCliCapabilityNarrowing(value: unknown, label: string): ExternalCliCapabilityNarrowing | undefined;
16
65
  export declare function resolveExternalCliRunnerStatus(input: {
17
66
  adapter?: CodeOwnedExternalCliAdapterId;
@@ -40,6 +40,16 @@ export function validateCodeOwnedProfileRunner(agent) {
40
40
  }
41
41
  return undefined;
42
42
  }
43
+ // What each adapter's own argv asks the CLI for. It is a profile, not a measurement:
44
+ // a runner command that wraps the CLI can grant something else.
45
+ export const EXTERNAL_CLI_ADAPTER_SAFETY = {
46
+ "codex-exec": { sandbox: "read-only", approvalPolicy: "never", ephemeral: true },
47
+ "codex-exec-writer": { access: "workspace-write", sandbox: "workspace-write", approvalPolicy: "never", ephemeral: true },
48
+ "claude-code": { access: "read-only", authentication: "existing-cli-required", permissionMode: "plan", tools: "none", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false },
49
+ "claude-code-writer": { access: "workspace-write", authentication: "existing-cli-required", permissionMode: "acceptEdits", tools: "Read,Write,Edit,Glob,Grep", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false },
50
+ "cursor-agent": { access: "read-only", authentication: "cursor-api-key-or-existing-login", mode: "ask", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false },
51
+ "cursor-agent-writer": { access: "workspace-write", authentication: "cursor-api-key-or-existing-login", mode: "print", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false },
52
+ };
43
53
  export function parseExternalCliCapabilityNarrowing(value, label) {
44
54
  if (value === undefined)
45
55
  return undefined;
@@ -56,13 +66,8 @@ export function parseExternalCliCapabilityNarrowing(value, label) {
56
66
  return input;
57
67
  }
58
68
  export function resolveExternalCliRunnerStatus(input) {
59
- const codexExec = input.adapter === "codex-exec";
60
- const codexExecWriter = input.adapter === "codex-exec-writer";
61
- const claudeCode = input.adapter === "claude-code";
62
- const claudeCodeWriter = input.adapter === "claude-code-writer";
63
- const cursorAgent = input.adapter === "cursor-agent";
64
- const cursorAgentWriter = input.adapter === "cursor-agent-writer";
65
- const cursor = cursorAgent || cursorAgentWriter;
69
+ const cursor = input.adapter === "cursor-agent" || input.adapter === "cursor-agent-writer";
70
+ const profileSafety = input.adapter ? EXTERNAL_CLI_ADAPTER_SAFETY[input.adapter] : undefined;
66
71
  const unsupported = cursor ? PROMPT_FILE_UNSUPPORTED : UNSUPPORTED;
67
72
  return {
68
73
  type: "external-cli",
@@ -70,12 +75,11 @@ export function resolveExternalCliRunnerStatus(input) {
70
75
  args: input.args ?? [],
71
76
  promptDelivery: cursor ? "prompt-file" : input.promptDelivery ?? "stdin",
72
77
  adapter: { id: input.adapter ?? "external-cli", version: 1, executionMode: cursor ? "one-shot-prompt-file" : "one-shot-stdin" },
73
- ...(codexExec ? { safety: { sandbox: "read-only", approvalPolicy: "never", ephemeral: true } } : {}),
74
- ...(codexExecWriter ? { safety: { access: "workspace-write", sandbox: "workspace-write", approvalPolicy: "never", ephemeral: true } } : {}),
75
- ...(claudeCode ? { safety: { access: "read-only", authentication: "existing-cli-required", permissionMode: "plan", tools: "none", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false } } : {}),
76
- ...(claudeCodeWriter ? { safety: { access: "workspace-write", authentication: "existing-cli-required", permissionMode: "acceptEdits", tools: "Read,Write,Edit,Glob,Grep", mcp: "empty-strict", settingSources: "user", userSettingsTrust: "required", sessionPersistence: false } } : {}),
77
- ...(cursorAgent ? { safety: { access: "read-only", authentication: "cursor-api-key-or-existing-login", mode: "ask", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false } } : {}),
78
- ...(cursorAgentWriter ? { safety: { access: "workspace-write", authentication: "cursor-api-key-or-existing-login", mode: "print", sandbox: "enabled", workspaceTrust: "existing-required", sessionReuse: false } } : {}),
78
+ ...(profileSafety ? {
79
+ safety: { ...profileSafety },
80
+ // A Herdr saved machine launches the remote adapter binary, never runner.command.
81
+ safetySource: { measured: false, ...(input.machine ? {} : { command: input.command }) },
82
+ } : {}),
79
83
  ...(input.machine ? { machine: input.machine } : {}),
80
84
  capabilities: {
81
85
  stop: true,
@@ -131,6 +135,7 @@ export function externalCliReceiptMetadata(input) {
131
135
  capabilities: { ...runner.capabilities },
132
136
  ...(machine ? { machine: { ...machine, ...(machine.remoteGit ? { remoteGit: { ...machine.remoteGit } } : {}) } } : {}),
133
137
  ...(runner.safety ? { safety: { ...runner.safety } } : {}),
138
+ ...(runner.safetySource ? { safetySource: { ...runner.safetySource } } : {}),
134
139
  ...(input.externalProcess ? {
135
140
  outputArtifacts: {
136
141
  stdoutPath: input.externalProcess.stdoutPath,