@xzzpig/pi-subagents 0.19.0 → 0.20.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 (53) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/docs/agents.md +15 -5
  3. package/docs/configuration.md +10 -0
  4. package/docs/extension-api.md +1 -1
  5. package/docs/missions.md +15 -1
  6. package/docs/models.md +6 -2
  7. package/docs/observability.md +8 -3
  8. package/docs/tool-reference.md +28 -3
  9. package/docs/workflows.md +2 -2
  10. package/package.json +1 -1
  11. package/src/agents/agents.ts +59 -3
  12. package/src/api/preflight.ts +42 -1
  13. package/src/extension/config.ts +4 -1
  14. package/src/extension/index.ts +23 -16
  15. package/src/extension/public-execution.ts +3 -0
  16. package/src/extension/reply-workflow-script.ts +1 -1
  17. package/src/extension/rpc.ts +1 -1
  18. package/src/extension/schemas.ts +5 -3
  19. package/src/extension/tool-description.ts +1 -1
  20. package/src/missions/goal-driver.ts +44 -31
  21. package/src/missions/store.ts +10 -1
  22. package/src/profiles/profiles.ts +5 -2
  23. package/src/runs/background/async-execution.ts +88 -6
  24. package/src/runs/background/async-job-tracker.ts +3 -2
  25. package/src/runs/background/await-async-run.ts +4 -2
  26. package/src/runs/background/control-channel.ts +43 -0
  27. package/src/runs/background/run-child-session.ts +13 -6
  28. package/src/runs/background/runner-aliases.ts +7 -4
  29. package/src/runs/background/scheduled-runs.ts +28 -13
  30. package/src/runs/background/stale-run-reconciler.ts +13 -2
  31. package/src/runs/background/subagent-runner.ts +43 -4
  32. package/src/runs/foreground/command-action.ts +41 -0
  33. package/src/runs/foreground/execution.ts +16 -7
  34. package/src/runs/foreground/subagent-executor.ts +63 -12
  35. package/src/runs/shared/child-commands.ts +228 -0
  36. package/src/runs/shared/child-session.ts +93 -19
  37. package/src/runs/shared/child-tool-plan.ts +1 -1
  38. package/src/runs/shared/claude-code-adapter.ts +157 -2
  39. package/src/runs/shared/dynamic-fanout.ts +1 -1
  40. package/src/runs/shared/external-cli-preflight.ts +54 -6
  41. package/src/runs/shared/external-cli-runner.ts +5 -1
  42. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -4
  43. package/src/runs/shared/model-resolution.ts +9 -1
  44. package/src/runs/shared/parallel-utils.ts +2 -0
  45. package/src/runs/shared/run-history.ts +87 -0
  46. package/src/runs/shared/subagent-control.ts +32 -17
  47. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  48. package/src/shared/required-child-extensions.ts +39 -5
  49. package/src/shared/types.ts +6 -1
  50. package/src/slash/subagent-cost.ts +9 -5
  51. package/src/tui/render.ts +4 -4
  52. package/src/workflows/workflow-receipt.ts +2 -2
  53. package/src/workflows/workflow-resources.ts +7 -4
@@ -27,6 +27,7 @@ import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflo
27
27
  import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.ts";
28
28
  import { disabledFeatureNotice, disabledFeatureUseError, resolveDisabledFeatureSurface, type DisabledFeatureSurface } from "../../shared/disabled-features.ts";
29
29
  import { runSync } from "./execution.ts";
30
+ import { commandAction } from "./command-action.ts";
30
31
  import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
31
32
  import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
32
33
  import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
@@ -75,7 +76,7 @@ import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig
75
76
  import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
76
77
  import { isAgentContract } from "../shared/agent-contract.ts";
77
78
  import { normalizeExtensionBindings, type ExtensionBindings } from "../shared/extension-bindings.ts";
78
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
79
+ import { assertRequiredChildExtensionsAdmitted, hasMandatoryRequiredChildExtensions, readRetainedRequiredChildExtensions, resolveRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
79
80
  import { finalizeSingleOutput, injectSingleOutputInstruction, normalizeSingleOutputOverride, outputPathMappingFromTask, resolveSingleOutputPath, validateFileOnlyOutputMode } from "../shared/single-output.ts";
80
81
  import { assertJsonSchemaObject, cleanupStructuredOutputRuntime, createStructuredOutputRuntime } from "../shared/structured-output.ts";
81
82
  import { compactForegroundDetails, getSingleResultOutput, PROMPT_REDACTED, readStatus, resolveChildCwd, sumResultsCost, sumResultsUsage, toAgentToolUsage } from "../../shared/utils.ts";
@@ -222,8 +223,8 @@ import {
222
223
  } from "../../shared/types.ts";
223
224
  import { deriveChildSessionName } from "../../shared/child-session-name.ts";
224
225
 
225
- const MUTATING_MANAGEMENT_ACTIONS = new Set(["create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
226
- const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
226
+ const MUTATING_MANAGEMENT_ACTIONS = new Set(["command.yield", "command.cancel", "create", "update", "delete", "eject", "disable", "enable", "reset", "grant-spawn-budget", "watchdog.configure", "mission.create", "mission.update", "mission.resolve-decision", "mission.attach-run", "mission.close", "inspector.open", "inspector.close", "project.open", "project.close", "worktree.discard", "worktree.cleanup", "lane.recordMerge", "lane.recordSupersession", "refine", "refine.rollback", "dismiss", "schedule.create", "schedule.pause", "schedule.resume", "schedule.run", "schedule.run-due", "schedule.delete"]);
227
+ const DESTRUCTIVE_MANAGEMENT_ACTIONS = new Set(["command.cancel", "delete", "eject", "disable", "reset", "mission.close", "worktree.discard", "refine.rollback", "inspector.close", "project.close", "stop", "interrupt", "schedule.delete"]);
227
228
 
228
229
  function resolveSteerDeliveryMode(mode: SubagentParamsLike["mode"]): SteerDeliveryMode | undefined {
229
230
  return mode === "steer" || mode === "follow_up" || mode === "auto" ? mode : undefined;
@@ -330,6 +331,7 @@ export interface SubagentParamsLike {
330
331
  merge?: unknown;
331
332
  supersession?: unknown;
332
333
  index?: number;
334
+ toolCallId?: string;
333
335
  childId?: string;
334
336
  view?: "fleet" | "transcript";
335
337
  lines?: number;
@@ -535,6 +537,8 @@ interface ExecutionContextData {
535
537
  usageBudget?: UsageBudgetConfig;
536
538
  /** Parent workflow owns this allowance; presence vetoes unverifiable child continuation. */
537
539
  inheritedUsageBudget?: UsageBudgetConfig;
540
+ /** Mandatory host extensions retained by a parent workflow; they outlive a later registration disposal. */
541
+ requiredExtensions?: RequiredChildExtensionSnapshot;
538
542
  allowZeroToolBudget?: boolean;
539
543
  configToolBudget?: ResolvedToolBudget;
540
544
  contextPolicy: AgentDefaultContextPolicy;
@@ -1378,6 +1382,16 @@ function appendStepToAsyncChain(input: {
1378
1382
  };
1379
1383
  }
1380
1384
 
1385
+ let retainedRequiredExtensions: RequiredChildExtensionSnapshot | undefined;
1386
+ try {
1387
+ retainedRequiredExtensions = readRetainedRequiredChildExtensions(resolved.location.asyncDir);
1388
+ } catch (error) {
1389
+ return {
1390
+ content: [{ type: "text", text: `Cannot append step to run '${resolved.id}': ${error instanceof Error ? error.message : String(error)}` }],
1391
+ isError: true,
1392
+ details: { mode: "management", results: [] },
1393
+ };
1394
+ }
1381
1395
  const pendingAppendRequests = readPendingChainAppendRequests(resolved.location.asyncDir);
1382
1396
  const reservedOutputNames = new Set<string>([
1383
1397
  ...Object.keys(status.outputs ?? {}),
@@ -1450,6 +1464,7 @@ function appendStepToAsyncChain(input: {
1450
1464
  asyncDir: resolved.location.asyncDir,
1451
1465
  validateOutputBindings: false,
1452
1466
  capabilityCeiling: intersectSubagentCapabilityCeilings(status.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(asyncCtx.currentSessionId)),
1467
+ requiredExtensions: retainedRequiredExtensions,
1453
1468
  }));
1454
1469
  if ("error" in built) {
1455
1470
  return {
@@ -3608,6 +3623,7 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
3608
3623
  goal: params.task ?? "",
3609
3624
  agentConfig: a,
3610
3625
  recoveryAgentConfig: data.recoveryAgents.find((agent) => agent.name === params.agent),
3626
+ requiredExtensions: data.requiredExtensions,
3611
3627
  ctx: asyncCtx,
3612
3628
  availableModels,
3613
3629
  cwd: effectiveCwd,
@@ -4094,8 +4110,12 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4094
4110
  }
4095
4111
  let foregroundMachine: import("../../shared/types.ts").HerdrMachineReference | undefined;
4096
4112
  const requestedMachine = params.machine ?? agentConfig.machine;
4113
+ const requiredExtensions = data.requiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4097
4114
  if (requestedMachine) {
4098
- try { foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine; }
4115
+ try {
4116
+ assertRequiredChildExtensionsAdmitted([requiredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
4117
+ foregroundMachine = resolveHerdrMachinePlacement({ machine: requestedMachine, cwd: ctx.cwd, stepCwd: params.machineCwd }).machine;
4118
+ }
4099
4119
  catch (error) { return toExecutionErrorResult(params, error instanceof Error ? error : new Error(String(error)), data.contextPolicy.contextSummary); }
4100
4120
  }
4101
4121
  const effectiveToolBudget = resolveEffectiveToolBudget(omitUndefinedProperties({ runBudget: data.toolBudget, agentBudget: agentConfig.toolBudget, configBudget: data.configToolBudget }));
@@ -4300,7 +4320,6 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
4300
4320
  : undefined;
4301
4321
 
4302
4322
  const deadlineAt = data.deadlineAt ?? (data.timeoutMs !== undefined ? Date.now() + data.timeoutMs : undefined);
4303
- const requiredExtensions = deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(data.parentPiSessionId);
4304
4323
  let r: Awaited<ReturnType<typeof runSync>> | undefined;
4305
4324
  let resolveDetachedWorkflowChild: ((result: Awaited<ReturnType<typeof runSync>>) => void) | undefined;
4306
4325
  const detachedWorkflowChild = params.workflowAwaitDetached === true
@@ -4554,6 +4573,7 @@ function duplicateSubagentCallResult(params: SubagentParamsLike): AgentToolResul
4554
4573
 
4555
4574
  const workflowLaunchObservers = new WeakMap<object, (launch: { agent: string; sessionName?: string; sessionFile?: string; async: boolean; runId?: string }) => void>();
4556
4575
  const workflowOwnedUsageBudgets = new WeakMap<object, UsageBudgetConfig>();
4576
+ const workflowRetainedRequiredExtensions = new WeakMap<object, RequiredChildExtensionSnapshot>();
4557
4577
 
4558
4578
  /**
4559
4579
  * Terminal-mission retention can remove a mission while its children still
@@ -4758,7 +4778,11 @@ function workflowOutputPathMappingSummary(children: WorkflowScriptChildResult[])
4758
4778
  }
4759
4779
 
4760
4780
  function workflowDetailsResults(children: WorkflowScriptChildResult[]): SingleResult[] {
4761
- return children.flatMap((child) => (child.results ?? []).map((result) => result.workflowKey ? result : { ...result, workflowKey: child.key }));
4781
+ return children.flatMap((child) => (child.results ?? []).map((result) => ({
4782
+ ...result,
4783
+ workflowKey: result.workflowKey ?? child.key,
4784
+ ...(child.runId && !result.runId ? { runId: child.runId } : {}),
4785
+ })));
4762
4786
  }
4763
4787
 
4764
4788
  function workflowSteerReceipt(key: string, result: AgentToolResult<Details>): WorkflowSteerResult {
@@ -5354,6 +5378,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5354
5378
  ): Promise<AgentToolResult<Details>> => {
5355
5379
  const workflowLaunchObserver = workflowLaunchObservers.get(params);
5356
5380
  const inheritedUsageBudget = workflowOwnedUsageBudgets.get(params);
5381
+ const retainedRequiredExtensions = workflowRetainedRequiredExtensions.get(params);
5357
5382
  const delegatedThinkingOverride = delegatedThinkingOverrides.get(params);
5358
5383
  const allowZeroToolBudget = delegatedZeroToolBudgets.has(params);
5359
5384
  const delegatedExecution = delegatedExecutions.has(params);
@@ -5381,6 +5406,12 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5381
5406
  ? currentParentModel
5382
5407
  : rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
5383
5408
  })();
5409
+ // validate checks args with the same normalization launch uses, reported beside script errors.
5410
+ const validateWorkflowRequest = () => {
5411
+ const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5412
+ const normalizedArgs = normalizeWorkflowArgs(requestParams.args);
5413
+ return "error" in normalizedArgs ? { ...validation, ok: false, errors: [...validation.errors, { message: normalizedArgs.error }] } : validation;
5414
+ };
5384
5415
  try {
5385
5416
  if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined) {
5386
5417
  throw new Error("preflight requires workflow: true or a workflow script path.");
@@ -5390,7 +5421,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5390
5421
  } catch (error) {
5391
5422
  const message = error instanceof Error ? error.message : String(error);
5392
5423
  if (requestParams.action?.trim() === "validate") {
5393
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5424
+ const validation = validateWorkflowRequest();
5394
5425
  const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
5395
5426
  return {
5396
5427
  content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
@@ -5401,8 +5432,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5401
5432
  return buildRequestedModeError(requestParams, message);
5402
5433
  }
5403
5434
  if (requestParams.action?.trim() === "validate") {
5404
- const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
5405
- return buildWorkflowValidationResult(validation, "management", workflowPreflight);
5435
+ return buildWorkflowValidationResult(validateWorkflowRequest(), "management", workflowPreflight);
5406
5436
  }
5407
5437
  const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
5408
5438
  if (normalizedAction === "resume" && requestParams.extensionBindings !== undefined) return buildRequestedModeError(requestParams, "extensionBindings is not supported with action='resume'; resume uses the original retained child binding.");
@@ -5431,6 +5461,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
5431
5461
  }
5432
5462
  const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
5433
5463
  if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
5464
+ // Capture mandatory host extensions at admission: script children may launch after the host disposes its registration.
5465
+ const admittedRequiredExtensions = retainedRequiredExtensions ?? deps.childRuntime?.requiredExtensions ?? resolveRequiredChildExtensions(ctx.sessionManager.getSessionId() ?? undefined);
5466
+ const workflowRequiredExtensions = hasMandatoryRequiredChildExtensions(admittedRequiredExtensions) ? admittedRequiredExtensions : undefined;
5434
5467
  const foregroundWorkflowRunId = encodeIndexSegment(_id);
5435
5468
  if (delegatedWorkflowPermit) {
5436
5469
  const permitError = validateWorkflowChildPermitRoot(delegatedWorkflowPermit, foregroundWorkflowRunId);
@@ -6231,6 +6264,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6231
6264
  );
6232
6265
  preparedChildParams = childRequest;
6233
6266
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6267
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6234
6268
  workflowLaunchObservers.set(childRequest, (launch) => {
6235
6269
  if (launch.runId) appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: launch.runId });
6236
6270
  const step = status.steps?.find((candidate) => candidate.workflowKey === key);
@@ -6516,6 +6550,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6516
6550
  );
6517
6551
  preparedChildParams = childRequest;
6518
6552
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6553
+ if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
6519
6554
  if (delegatedWorkflowPermit) {
6520
6555
  if (childRequest.async !== false) throw new Error("Workflow child permit supports one foreground child only.");
6521
6556
  const childCwd = resolveRequestedCwd(workflowCwd, childRequest.cwd);
@@ -6755,7 +6790,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6755
6790
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
6756
6791
  }
6757
6792
  }
6758
- const policyAction = action === "stop" ? "stopRun" : action === "steer" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6793
+ const policyAction = action === "stop" || action === "command.cancel" ? "stopRun" : action === "steer" || action === "command.yield" ? "steerRun" : action === "schedule.create" ? "scheduleCreate" : action === "inspector.open" ? "inspectorOpen" : action === "project.open" ? "projectOpen" : undefined;
6759
6794
  if (policyAction) {
6760
6795
  // Child-safe mode is a hard capability boundary; the policy is an operator
6761
6796
  // preference. Refuse first, so the gate never prompts for an action that is
@@ -6978,6 +7013,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
6978
7013
  details: { mode: "management", results: [], spawnBudget, activeAsyncCapacity },
6979
7014
  };
6980
7015
  }
7016
+ if (["command.status", "command.yield", "command.cancel"].includes(action)) {
7017
+ try {
7018
+ if (deps.allowMutatingManagementActions === false && action !== "command.status") throw new Error(`Action '${action}' is not available from child-safe subagent fanout mode.`);
7019
+ const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
7020
+ if (!targetRunId || paramsWithResolvedCwd.dir) throw new Error(`${action} requires id or runId; directory targets are not supported.`);
7021
+ deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
7022
+ const target = resolveSubagentRunId(targetRunId, { state: deps.state, nested: nestedResolutionScopeForExecutor(deps) });
7023
+ if (!target) throw new Error(`No run found for '${targetRunId}'.`);
7024
+ return await commandAction({ state: deps.state, target, operation: action.slice("command.".length) as "status" | "yield" | "cancel", index: paramsWithResolvedCwd.index, toolCallId: paramsWithResolvedCwd.toolCallId, signal });
7025
+ } catch (error) {
7026
+ return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true, details: { mode: "management", results: [] } };
7027
+ }
7028
+ }
6981
7029
  if (action === "status" || action === "debug.run") {
6982
7030
  if (!preserveActiveSession) deps.state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
6983
7031
  const targetRunId = paramsWithResolvedCwd.id ?? paramsWithResolvedCwd.runId;
@@ -7685,6 +7733,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7685
7733
  toolBudget: runToolBudget.toolBudget,
7686
7734
  usageBudget: usageBudget.budget,
7687
7735
  inheritedUsageBudget,
7736
+ requiredExtensions: retainedRequiredExtensions,
7688
7737
  allowZeroToolBudget,
7689
7738
  configToolBudget: configToolBudget.toolBudget,
7690
7739
  configToolTimeoutMs: deps.config.toolTimeoutMs,
@@ -7971,7 +8020,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7971
8020
  workflowResourcePermits.set(publicParams, resolved.resource.permit);
7972
8021
  } else if (workflow !== undefined || publicParams.workflowScript !== undefined) {
7973
8022
  const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
7974
- if ("error" in normalizedArgs) return errorResult(normalizedArgs.error);
8023
+ // validate reports args errors with its script errors; launch rejects them here.
8024
+ const validateOnly = publicParams.action === "validate";
8025
+ if ("error" in normalizedArgs && !validateOnly) return errorResult(normalizedArgs.error);
7975
8026
  let workflowScript = publicParams.workflowScript;
7976
8027
  if (workflow !== undefined) {
7977
8028
  const source = workflow === true ? readReplyWorkflowScript(ctx.sessionManager, id) : readWorkflowScriptFile(workflow, publicParams.cwd, ctx.cwd);
@@ -7979,7 +8030,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
7979
8030
  workflowScript = source.script;
7980
8031
  }
7981
8032
  const { workflow: _workflow, ...withoutWorkflowSource } = publicParams;
7982
- publicParams = { ...withoutWorkflowSource, workflowScript, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
8033
+ publicParams = { ...withoutWorkflowSource, workflowScript, args: "error" in normalizedArgs ? publicParams.args : deepFreezeWorkflowArgs(normalizedArgs.args) };
7983
8034
  }
7984
8035
  publicExecutions.add(publicParams);
7985
8036
  return executeWithSingleDispatchGuard(id, publicParams, signal, onUpdate, ctx);
@@ -0,0 +1,228 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { Type } from "typebox";
5
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
6
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ import { createAtomicJsonWriter } from "../../shared/atomic-json.ts";
8
+ import { watchAsyncControlInbox, requestAsyncCommand, type CommandRequest } from "../background/control-channel.ts";
9
+
10
+ export const CHILD_COMMAND_TOOL = "subagent_command";
11
+ export type CommandOperation = "status" | "yield" | "cancel";
12
+ export interface ChildCommandSnapshot {
13
+ toolCallId: string;
14
+ state: "running" | "yielded" | "cancel_requested" | "completed" | "failed" | "cancelled";
15
+ startedAt: number;
16
+ endedAt?: number;
17
+ output: string;
18
+ fullOutputPath?: string;
19
+ }
20
+ interface CommandJob {
21
+ snapshot: ChildCommandSnapshot;
22
+ controller: AbortController;
23
+ yieldResult: () => void;
24
+ settled: Promise<void>;
25
+ yielded?: boolean;
26
+ }
27
+ export interface ChildCommandState {
28
+ ownerId: string;
29
+ closed: boolean;
30
+ commands: ChildCommandSnapshot[];
31
+ }
32
+ const writeAtomicJson = createAtomicJsonWriter({ mode: 0o600 });
33
+ const MAX_OUTPUT_BYTES = 8 * 1024;
34
+ const RECENT_COMMANDS = 20;
35
+
36
+ function childCommandStatePath(channelDir: string): string {
37
+ return path.join(channelDir, "commands.json");
38
+ }
39
+ export function readChildCommandState(channelDir: string): ChildCommandState | undefined {
40
+ try { return JSON.parse(fs.readFileSync(childCommandStatePath(channelDir), "utf8")) as ChildCommandState; }
41
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
42
+ }
43
+ function active(job: CommandJob): boolean { return job.snapshot.endedAt === undefined; }
44
+ function text(result: AgentToolResult<unknown>): string {
45
+ return Buffer.from(result.content.filter((part) => part.type === "text").map((part) => part.text).join("\n")).subarray(-MAX_OUTPUT_BYTES).toString("utf8");
46
+ }
47
+
48
+ /** Owns command lifetimes, not shell execution. The supplied Pi tool still executes the command. */
49
+ export function createChildCommandRuntime(channelDir: string) {
50
+ const ownerId = randomUUID();
51
+ const jobs = new Map<string, CommandJob>();
52
+ const usedIds = new Set<string>();
53
+ let closed = false;
54
+ let disposeInbox: (() => void) | undefined;
55
+ const state = (): ChildCommandState => ({ ownerId, closed, commands: [...jobs.values()].map((job) => ({ ...job.snapshot })) });
56
+ const persist = () => writeAtomicJson(childCommandStatePath(channelDir), {
57
+ ownerId, closed,
58
+ commands: [...jobs.values()].map((job) => ({ ...job.snapshot, output: job.yielded ? job.snapshot.output : "" })),
59
+ });
60
+ const operate = (operation: CommandOperation, toolCallId?: string): ChildCommandState => {
61
+ if (operation === "status" && toolCallId === undefined) return state();
62
+ const job = toolCallId ? jobs.get(toolCallId) : undefined;
63
+ if (!job) throw new Error(`No retained command '${toolCallId ?? ""}' in this child session.`);
64
+ if (operation !== "status" && closed) throw new Error("Child command controller is closed.");
65
+ const before = job.snapshot.state;
66
+ if (active(job)) {
67
+ if (operation === "yield" && job.snapshot.state === "running") {
68
+ job.yielded = true;
69
+ job.snapshot.state = "yielded";
70
+ job.yieldResult();
71
+ } else if (operation === "cancel") {
72
+ job.snapshot.state = "cancel_requested";
73
+ job.controller.abort();
74
+ }
75
+ }
76
+ if (job.snapshot.state !== before) persist();
77
+ return { ownerId, closed, commands: [{ ...job.snapshot }] };
78
+ };
79
+ const startInbox = () => {
80
+ if (disposeInbox) return;
81
+ disposeInbox = watchAsyncControlInbox(channelDir, {
82
+ onCommand(request) {
83
+ const replyPath = commandReplyPath(channelDir, request.id);
84
+ try {
85
+ if (request.ownerId !== ownerId) throw new Error("Command request belongs to another child session.");
86
+ if (Date.now() > request.deadlineAt) throw new Error("Command request expired before delivery.");
87
+ writeAtomicJson(replyPath, { state: operate(request.operation, request.toolCallId) });
88
+ } catch (error) {
89
+ writeAtomicJson(replyPath, { error: error instanceof Error ? error.message : String(error) });
90
+ }
91
+ },
92
+ });
93
+ };
94
+ const stop = async () => {
95
+ closed = true;
96
+ disposeInbox?.();
97
+ for (const job of jobs.values()) if (active(job)) {
98
+ job.snapshot.state = "cancel_requested";
99
+ job.controller.abort();
100
+ }
101
+ await Promise.all([...jobs.values()].map((job) => job.settled));
102
+ if (jobs.size) persist();
103
+ };
104
+ return {
105
+ state,
106
+ operate,
107
+ shutdown: stop,
108
+ async finish() {
109
+ const pending = [...jobs.values()].filter(active);
110
+ if (!pending.length) return;
111
+ await stop();
112
+ throw new Error(`Child finished with unfinished commands: ${pending.map((job) => job.snapshot.toolCallId).join(", ")}. Commands were cancelled; query or cancel background commands before finishing.`);
113
+ },
114
+ wrap(tool: ToolDefinition): ToolDefinition {
115
+ return {
116
+ ...tool,
117
+ parameters: Type.Unsafe({ ...tool.parameters, properties: {
118
+ ...(tool.parameters as { properties?: object }).properties,
119
+ yieldTimeMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30_000, description: "Return a managed command handle after this wait; does not terminate the command. Omit to wait for completion." })),
120
+ } }),
121
+ description: `${tool.description}\nOptional yieldTimeMs returns a command handle without stopping execution. Use subagent_command to query or cancel it. Finish or cancel every command before completing the task.`,
122
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
123
+ if (closed) throw new Error("Child command controller is closed.");
124
+ if (usedIds.has(toolCallId)) throw new Error(`Command id '${toolCallId}' was already used in this child session.`);
125
+ usedIds.add(toolCallId);
126
+ const { yieldTimeMs, ...args } = params as Record<string, unknown>;
127
+ const controller = new AbortController();
128
+ const commandSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
129
+ let yieldResult!: () => void;
130
+ const yielded = new Promise<void>((resolve) => { yieldResult = resolve; });
131
+ const job: CommandJob = { snapshot: { toolCallId, state: "running", startedAt: Date.now(), output: "" }, controller, yieldResult, settled: Promise.resolve() };
132
+ // Keep active commands and a bounded recent history; never retain full outputs.
133
+ const completed = [...jobs].filter(([, candidate]) => !active(candidate));
134
+ for (const [id] of completed.slice(0, Math.max(0, completed.length - RECENT_COMMANDS + 1))) jobs.delete(id);
135
+ jobs.set(toolCallId, job);
136
+ persist();
137
+ startInbox();
138
+ let timer: ReturnType<typeof setTimeout> | undefined;
139
+ if (typeof yieldTimeMs === "number") timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
140
+ const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
141
+ job.snapshot.output = text(update);
142
+ if (job.snapshot.state === "running") onUpdate?.(update);
143
+ }, ctx)).then((result) => {
144
+ job.snapshot.output = text(result);
145
+ job.snapshot.state = "completed";
146
+ const fullOutputPath = (result.details as { fullOutputPath?: string } | undefined)?.fullOutputPath;
147
+ if (fullOutputPath) job.snapshot.fullOutputPath = fullOutputPath;
148
+ return result;
149
+ }, (error: unknown) => {
150
+ job.snapshot.state = controller.signal.aborted ? "cancelled" : "failed";
151
+ job.snapshot.output = String(error).slice(-MAX_OUTPUT_BYTES);
152
+ throw error;
153
+ }).finally(() => {
154
+ if (timer) clearTimeout(timer);
155
+ job.snapshot.endedAt = Date.now();
156
+ persist();
157
+ });
158
+ job.settled = execution.then(() => {}, () => {});
159
+ const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
160
+ if (result) return result.value;
161
+ return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
162
+ },
163
+ };
164
+ },
165
+ tool(): ToolDefinition {
166
+ return {
167
+ name: CHILD_COMMAND_TOOL, label: "Child command",
168
+ description: "Inspect or cancel bash commands owned by this child. Cancellation stops only the selected command, not the agent. Check terminal state before finishing.",
169
+ parameters: Type.Object({ action: Type.String({ enum: ["status", "cancel"] }), toolCallId: Type.Optional(Type.String()), waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30_000 })) }),
170
+ async execute(_id, params, signal) {
171
+ const { action, toolCallId, waitMs = 0 } = params as { action: "status" | "cancel"; toolCallId?: string; waitMs?: number };
172
+ operate(action, toolCallId);
173
+ const job = toolCallId ? jobs.get(toolCallId) : undefined;
174
+ if (job && active(job) && waitMs > 0) await waitForCommand(job.settled, waitMs, signal);
175
+ const snapshot = operate("status", toolCallId);
176
+ return { content: [{ type: "text", text: JSON.stringify(snapshot) }], details: snapshot };
177
+ },
178
+ };
179
+ },
180
+ };
181
+ }
182
+
183
+ async function waitForCommand(settled: Promise<void>, waitMs: number, signal?: AbortSignal): Promise<void> {
184
+ let timer: ReturnType<typeof setTimeout>;
185
+ let abort!: () => void;
186
+ const wait = new Promise<void>((resolve, reject) => {
187
+ timer = setTimeout(resolve, waitMs);
188
+ abort = () => reject(new Error("Command wait aborted; command remains managed by the child."));
189
+ if (signal?.aborted) abort();
190
+ else signal?.addEventListener("abort", abort, { once: true });
191
+ });
192
+ try { await Promise.race([settled, wait]); }
193
+ finally { clearTimeout(timer!); signal?.removeEventListener("abort", abort); }
194
+ }
195
+ function commandReplyPath(channelDir: string, id: string): string {
196
+ return path.join(channelDir, "command-replies", `${id}.json`);
197
+ }
198
+ export async function controlChildCommand(channelDir: string, operation: CommandOperation, toolCallId?: string, signal?: AbortSignal): Promise<ChildCommandState> {
199
+ const current = readChildCommandState(channelDir);
200
+ if (!current) throw new Error("No command controller is available for this child. Command controls require a local native Pi child with bash.");
201
+ if (current.closed) {
202
+ if (operation === "status") {
203
+ if (toolCallId === undefined) return current;
204
+ const command = current.commands.find((entry) => entry.toolCallId === toolCallId);
205
+ if (!command) throw new Error(`No retained command '${toolCallId}' in this child session.`);
206
+ return { ...current, commands: [command] };
207
+ }
208
+ throw new Error("Child command controller is closed.");
209
+ }
210
+ if (operation !== "status" && !toolCallId) throw new Error("An exact toolCallId is required; command controls never target the next command.");
211
+ const id = randomUUID();
212
+ const deadlineAt = Date.now() + 5_000;
213
+ const request: CommandRequest = { type: "command", id, ownerId: current.ownerId, operation, ...(toolCallId ? { toolCallId } : {}), deadlineAt };
214
+ requestAsyncCommand(channelDir, request);
215
+ const replyPath = commandReplyPath(channelDir, id);
216
+ try {
217
+ while (Date.now() < deadlineAt) {
218
+ if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
219
+ try {
220
+ const reply = JSON.parse(fs.readFileSync(replyPath, "utf8")) as { state?: ChildCommandState; error?: string };
221
+ if (reply.error) throw new Error(reply.error);
222
+ if (reply.state) return reply.state;
223
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
224
+ await new Promise((resolve) => setTimeout(resolve, 20));
225
+ }
226
+ throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
227
+ } finally { fs.rmSync(replyPath, { force: true }); }
228
+ }