@xzzpig/pi-subagents 0.18.0 → 0.19.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 +69 -0
- package/README.md +1 -1
- package/docs/agents.md +18 -12
- package/docs/configuration.md +66 -9
- package/docs/extension-api.md +5 -4
- package/docs/missions.md +13 -13
- package/docs/models.md +2 -2
- package/docs/observability.md +2 -2
- package/docs/standalone-background.md +1 -1
- package/docs/tool-reference.md +63 -86
- package/docs/workflows.md +170 -172
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +6 -6
- package/prompts/review-loop.md +1 -1
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +12 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
- package/skills/pi-subagents/references/execution-controls.md +68 -67
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-management.ts +2 -2
- package/src/agents/agents.ts +7 -0
- package/src/api/preflight.ts +67 -62
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +1 -0
- package/src/extension/fanout-child.ts +12 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +68 -159
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +29 -10
- package/src/extension/schemas.ts +36 -133
- package/src/extension/tool-activation.ts +57 -108
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/native-supervisor-channel.ts +4 -1
- package/src/runs/background/async-execution.ts +58 -53
- package/src/runs/background/async-job-tracker.ts +63 -22
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/notify.ts +5 -0
- package/src/runs/background/run-child-session.ts +4 -1
- package/src/runs/background/run-status.ts +6 -0
- package/src/runs/background/runner-aliases.ts +30 -2
- package/src/runs/background/runner-child-launch.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/subagent-runner.ts +15 -1
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +130 -125
- package/src/runs/foreground/subagent-executor.ts +487 -288
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/child-launch.ts +15 -2
- package/src/runs/shared/child-session.ts +92 -6
- package/src/runs/shared/child-tool-plan.ts +15 -3
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/mcp-config-sources.ts +2 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
- package/src/runs/shared/model-resolution.ts +29 -9
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +55 -55
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/pi-spawn.ts +7 -95
- package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
- package/src/runs/shared/worktree.ts +1 -1
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/model-info.ts +9 -0
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +21 -0
- package/src/slash/prompt-template-bridge.ts +2 -2
- package/src/slash/slash-commands.ts +10 -5
- package/src/slash/subagents-admin.ts +24 -24
- package/src/tui/fleet-status.ts +14 -6
- package/src/tui/fleet.ts +14 -2
- package/src/tui/render.ts +113 -52
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +23 -9
- package/src/watchdog/register-child.ts +3 -3
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +2 -2
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +117 -37
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
|
@@ -23,13 +23,15 @@ import { handleManagementAction } from "../../agents/agent-management.ts";
|
|
|
23
23
|
import { handleRefinementAction } from "../../agents/agent-refinements.ts";
|
|
24
24
|
import { buildDoctorReport } from "../../extension/doctor.ts";
|
|
25
25
|
import { readSubagentGuide } from "../../extension/subagent-guide.ts";
|
|
26
|
-
import { normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
|
|
26
|
+
import { isWorkflowScriptPath, normalizePublicSubagentExecution, validateWorkflowCapacityOverrides } from "../../extension/public-execution.ts";
|
|
27
|
+
import { readReplyWorkflowScript } from "../../extension/reply-workflow-script.ts";
|
|
28
|
+
import { disabledFeatureNotice, disabledFeatureUseError, resolveDisabledFeatureSurface, type DisabledFeatureSurface } from "../../shared/disabled-features.ts";
|
|
27
29
|
import { runSync } from "./execution.ts";
|
|
28
30
|
import { handleWatchdogToolAction, WATCHDOG_TOOL_ACTIONS } from "../../watchdog/tool-actions.ts";
|
|
29
31
|
import type { MainWatchdogRuntime } from "../../watchdog/runtime.ts";
|
|
30
32
|
import { applyWatchdogLaunchRules } from "../../watchdog/rules.ts";
|
|
31
33
|
import { childWatchdogProgressForModel } from "../../watchdog/child-status.ts";
|
|
32
|
-
import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
|
|
34
|
+
import { normalizeParentModel, resolveEffectiveSubagentModel, resolveModelOrigin, resolveModelSelection, scopedModelIdsFromContext, type ModelOrigin, type ParentModel } from "../shared/model-resolution.ts";
|
|
33
35
|
import { getHostBuiltinToolNames } from "../shared/child-tool-plan.ts";
|
|
34
36
|
import { projectScopedProfileTrustError } from "../shared/sandbox-profile-guard.ts";
|
|
35
37
|
import { projectChainOutputSchemas, resolveEffectiveOutputSchema } from "../shared/child-launch-plan.ts";
|
|
@@ -67,6 +69,7 @@ import { formatControlIntercomMessage, formatControlNoticeMessage, resolveContro
|
|
|
67
69
|
import { formatSpawnBudget, getSpawnBudgetSnapshot, grantSpawnBudget, preflightSpawnBudget, preflightSpawnBudgetGrant, reserveSpawnBudget } from "../shared/spawn-budget.ts";
|
|
68
70
|
import { claimRunFanoutBatch, claimRunFanoutBatchWithCommit, createRunFanoutBudget, formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor, RunFanoutLimitError, writeRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
|
|
69
71
|
import { retainLiveForegroundNestedRoute } from "../../integrations/pi-web-session-liveness.ts";
|
|
72
|
+
import { HERDR_FOREGROUND_CONTROL_CHANGED_EVENT } from "../../integrations/herdr-status.ts";
|
|
70
73
|
import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
|
|
71
74
|
import { usageBudgetExceededMessage, usageBudgetState, validateUsageBudgetConfig } from "../shared/usage-budget.ts";
|
|
72
75
|
import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, type ResolvedSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
|
|
@@ -100,12 +103,13 @@ import { dismissRecoveredWorkflow } from "./async-dismiss-action.ts";
|
|
|
100
103
|
import { promotePausedWorkflowIfSettled, reconcileDetachedWorkflowChildCompletion } from "./workflow-detach-reconcile.ts";
|
|
101
104
|
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
102
105
|
import { resolveAsyncRootResultPath, waitForImportedAsyncRoot } from "../background/chain-root-attachment.ts";
|
|
106
|
+
import { awaitExistingAsyncRun, claimWorkflowAwaitedResult } from "../background/await-async-run.ts";
|
|
103
107
|
import { fallbackResultPayloadPathForSessionRun, removeResultIndex, resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
|
|
104
108
|
import { attachRootChildrenToSteps, createNestedRoute, findNestedControlResult, inheritedNestedParentAddressOf, inheritedNestedRouteOf, nestedRunScope, resolveNestedAsyncDir, retainNestedLookupRoute, snapshotNestedEventFiles, updateForegroundNestedProjection, writeNestedControlRequest, writeNestedEvent, type NestedParentAddress, type NestedRoute, type NestedRunResolutionScope } from "../shared/nested-events.ts";
|
|
105
109
|
import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
|
|
106
110
|
import { resolveSubagentRunId, type ResolvedSubagentRunId } from "../background/run-id-resolver.ts";
|
|
107
111
|
import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
|
|
108
|
-
import { isStoppableAsyncStatusStep, resolveAsyncStatusChild
|
|
112
|
+
import { isStoppableAsyncStatusStep, resolveAsyncStatusChild } from "../shared/child-identity.ts";
|
|
109
113
|
import { inspectSubagentStatus } from "../background/run-status.ts";
|
|
110
114
|
import { getExternalJobProvider } from "../../api/external-job-provider.ts";
|
|
111
115
|
import { externalJobFollowUpRequestDigest, externalJobFollowUpRequestId, externalJobFollowUpRunId, externalJobPromptDigest, externalJobStableJson } from "../shared/external-job-runner.ts";
|
|
@@ -123,8 +127,10 @@ import { getInspectorPlugins } from "../../inspectors/plugins.ts";
|
|
|
123
127
|
import { handleHerdrProjectPaneAction, HERDR_PROJECT_PANE_ACTIONS } from "../../inspectors/herdr/project-panes.ts";
|
|
124
128
|
import { previewSimpleWorkflowRun, runWorkflowScript, validateWorkflowScript, WorkflowScriptError, type WorkflowChildSettledNotification, type WorkflowLanePlan, type WorkflowReceiptResumeReference, type WorkflowScriptChildResult, type WorkflowScriptTraceEntry, type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
|
|
125
129
|
import { formatIncrementalChildCompletion, incrementalChildCompletionTriggersTurn } from "../background/notify.ts";
|
|
130
|
+
import { appendWorkflowChildJournal, findWorkflowReuseSource, matchWorkflowReuse, workflowChildFingerprint, workflowScriptDigest, workflowStopCause, WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE } from "../../workflows/workflow-reuse.ts";
|
|
126
131
|
import { executeWorkflowHostCommand, resolveWorkflowHostOutputClaimPath, type WorkflowHostCommandParams, type WorkflowHostCommandResult } from "../../workflows/host-command.ts";
|
|
127
132
|
import { buildWorkflowReceipt, readWorkflowReceipt, workflowReceiptPath, resolveWorkflowReceiptResumeEntry, writeWorkflowReceipt, type WorkflowReceipt, type WorkflowReceiptState } from "../../workflows/workflow-receipt.ts";
|
|
133
|
+
import { formatWorkflowKeyRevival, recordWorkflowRevival, withWorkflowRevivals } from "../../workflows/workflow-revival.ts";
|
|
128
134
|
import { upsertHostStep, validHostStepNodes } from "../shared/host-step-status.ts";
|
|
129
135
|
import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../shared/lane-metadata.ts";
|
|
130
136
|
import { parseWorkflowChildSummary, workflowChildProgress, workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
|
|
@@ -140,7 +146,7 @@ import {
|
|
|
140
146
|
type WorkflowResourceAuthority,
|
|
141
147
|
type WorkflowResourcePermit,
|
|
142
148
|
} from "../../shared/workflow-child-permit.ts";
|
|
143
|
-
import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
|
|
149
|
+
import { deepFreezeWorkflowArgs, normalizeWorkflowArgs, resolveStructuredWorkflowResource, resolveWorkflowResource } from "../../workflows/workflow-resources.ts";
|
|
144
150
|
import { stableJsonDigest } from "../../shared/launch-contract.ts";
|
|
145
151
|
import {
|
|
146
152
|
cleanupWorktrees,
|
|
@@ -196,6 +202,7 @@ import {
|
|
|
196
202
|
type SubagentState,
|
|
197
203
|
DIRS,
|
|
198
204
|
DEFAULT_ARTIFACT_CONFIG,
|
|
205
|
+
DEFAULT_MAX_OUTPUT,
|
|
199
206
|
DEFAULT_FORK_PREAMBLE,
|
|
200
207
|
SUBAGENT_ACTIONS,
|
|
201
208
|
SUBAGENT_ASYNC_STARTED_EVENT,
|
|
@@ -208,6 +215,7 @@ import {
|
|
|
208
215
|
resolveChildMaxSubagentDepth,
|
|
209
216
|
resolveCurrentMaxSubagentDepth,
|
|
210
217
|
resolveMaxSubagentSpawnsPerRun,
|
|
218
|
+
truncateOutput,
|
|
211
219
|
wrapForkTask,
|
|
212
220
|
type ScheduleOrigin,
|
|
213
221
|
type SteeringTargetState,
|
|
@@ -246,16 +254,17 @@ function hasSingleAdjacentTransposition(left: string, right: string): boolean {
|
|
|
246
254
|
&& left.slice(mismatch + 2) === right.slice(mismatch + 2);
|
|
247
255
|
}
|
|
248
256
|
|
|
249
|
-
export function unknownSubagentActionMessage(action: string): string {
|
|
257
|
+
export function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string {
|
|
250
258
|
const requested = action.toLowerCase();
|
|
251
|
-
const
|
|
259
|
+
const enabledActions = SUBAGENT_ACTIONS.filter((candidate) => !disabled?.actions.has(candidate));
|
|
260
|
+
const suggestion = enabledActions.find((candidate) => {
|
|
252
261
|
const distance = editDistance(requested, candidate);
|
|
253
262
|
const closeMatch = distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate);
|
|
254
263
|
if (DESTRUCTIVE_MANAGEMENT_ACTIONS.has(candidate)) return distance === 1 && requested.length >= candidate.length - 1;
|
|
255
264
|
return closeMatch;
|
|
256
265
|
});
|
|
257
266
|
const nextStep = 'Use subagent({ action: "status" }) to inspect runs or subagent({ action: "list" }) to inspect agents.';
|
|
258
|
-
const validActions = `Valid: ${
|
|
267
|
+
const validActions = `Valid: ${enabledActions.join(", ")}.`;
|
|
259
268
|
return suggestion
|
|
260
269
|
? `Unknown action: ${action}. Did you mean ${suggestion}? ${nextStep} ${validActions}`
|
|
261
270
|
: `Unknown action: ${action}. ${nextStep} ${validActions}`;
|
|
@@ -340,8 +349,8 @@ export interface SubagentParamsLike {
|
|
|
340
349
|
mode?: SteerDeliveryMode | "plan" | "apply";
|
|
341
350
|
repo?: string;
|
|
342
351
|
planId?: string;
|
|
352
|
+
/** Internal script carrier (slash, prompt-workflow, scheduled, RPC, named resources). The model-facing tool rejects it. */
|
|
343
353
|
workflowScript?: string;
|
|
344
|
-
workflowScriptPath?: string;
|
|
345
354
|
globalConcurrencyLimit?: number;
|
|
346
355
|
maxSubagentSpawnsPerRun?: number;
|
|
347
356
|
preflight?: import("../../shared/types.ts").WorkflowPreflight;
|
|
@@ -367,7 +376,7 @@ export interface SubagentParamsLike {
|
|
|
367
376
|
runFanoutAdmitted?: boolean;
|
|
368
377
|
/** Internal inherited tool/agent ceiling for delegated child launches. */
|
|
369
378
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
370
|
-
/** Internal durable-run compatibility fields. Public callers must use
|
|
379
|
+
/** Internal durable-run compatibility fields. Public callers must use workflow. */
|
|
371
380
|
chain?: ChainStep[];
|
|
372
381
|
tasks?: TaskParam[];
|
|
373
382
|
concurrency?: number;
|
|
@@ -403,8 +412,8 @@ export interface SubagentParamsLike {
|
|
|
403
412
|
modelOrigin?: ModelOrigin;
|
|
404
413
|
fast?: boolean;
|
|
405
414
|
thinking?: string | false;
|
|
406
|
-
/**
|
|
407
|
-
workflow?: string;
|
|
415
|
+
/** true = the ```js workflow block in the calling reply; a string containing "/" or "\" = script path; otherwise a named workflow resource. */
|
|
416
|
+
workflow?: string | true;
|
|
408
417
|
args?: Record<string, unknown>;
|
|
409
418
|
scope?: string;
|
|
410
419
|
target?: string;
|
|
@@ -531,6 +540,7 @@ interface ExecutionContextData {
|
|
|
531
540
|
contextPolicy: AgentDefaultContextPolicy;
|
|
532
541
|
modelScope?: ModelScopeConfig;
|
|
533
542
|
parentModel?: ParentModel;
|
|
543
|
+
scopedModelIds?: string[];
|
|
534
544
|
parentSessionId: string | null;
|
|
535
545
|
parentPiSessionId?: string;
|
|
536
546
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
@@ -544,50 +554,48 @@ function resolveRequestedCwd(runtimeCwd: string, requestedCwd: string | undefine
|
|
|
544
554
|
return requestedCwd ? path.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
|
|
545
555
|
}
|
|
546
556
|
|
|
547
|
-
function
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
let workflowScript: string;
|
|
557
|
+
function readWorkflowScriptFile(requestedPath: string, requestedCwd: string | undefined, runtimeCwd: string): { script: string } | { error: string } {
|
|
558
|
+
const scriptPath = path.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
|
|
559
|
+
let script: string;
|
|
551
560
|
try {
|
|
552
|
-
|
|
561
|
+
script = fs.readFileSync(scriptPath, "utf8");
|
|
553
562
|
} catch (error) {
|
|
554
|
-
return { error: `Failed to read
|
|
563
|
+
return { error: `Failed to read workflow script '${scriptPath}': ${error instanceof Error ? error.message : String(error)}` };
|
|
555
564
|
}
|
|
556
|
-
if (!
|
|
557
|
-
|
|
558
|
-
return { params: { ...rest, workflowScript } };
|
|
565
|
+
if (!script.trim()) return { error: `Workflow script file '${scriptPath}' is empty.` };
|
|
566
|
+
return { script };
|
|
559
567
|
}
|
|
560
568
|
|
|
561
569
|
function currentProjectTrusted(ctx: Pick<ExtensionContext, "isProjectTrusted">): boolean {
|
|
562
|
-
return ctx.isProjectTrusted?.() === true;
|
|
570
|
+
return ctx.isProjectTrusted?.() === true;
|
|
563
571
|
}
|
|
564
572
|
|
|
565
573
|
function trustedProjectCwd(ctx: ExtensionContext): string | undefined {
|
|
566
|
-
return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
|
|
574
|
+
return currentProjectTrusted(ctx) ? path.resolve(ctx.cwd) : undefined;
|
|
567
575
|
}
|
|
568
576
|
|
|
569
577
|
function sandboxProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
|
|
570
|
-
return projectScopedProfileTrustError({
|
|
571
|
-
kind: "sandbox",
|
|
572
|
-
agentName: agent.name,
|
|
573
|
-
profileName: agent.sandbox ?? "",
|
|
574
|
-
projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
|
|
575
|
-
trustedCwd: trustedProjectCwd(ctx),
|
|
576
|
-
effectiveCwd: path.resolve(childCwd),
|
|
577
|
-
messageStyle: "executor",
|
|
578
|
-
});
|
|
578
|
+
return projectScopedProfileTrustError({
|
|
579
|
+
kind: "sandbox",
|
|
580
|
+
agentName: agent.name,
|
|
581
|
+
profileName: agent.sandbox ?? "",
|
|
582
|
+
projectScoped: Boolean(agent.sandbox) && (agent.source === "project" || agent.override?.scope === "project"),
|
|
583
|
+
trustedCwd: trustedProjectCwd(ctx),
|
|
584
|
+
effectiveCwd: path.resolve(childCwd),
|
|
585
|
+
messageStyle: "executor",
|
|
586
|
+
});
|
|
579
587
|
}
|
|
580
588
|
|
|
581
589
|
function permissionProfileTrustError(agent: AgentConfig, ctx: ExtensionContext, childCwd: string): string | undefined {
|
|
582
|
-
return projectScopedProfileTrustError({
|
|
583
|
-
kind: "permission",
|
|
584
|
-
agentName: agent.name,
|
|
585
|
-
profileName: agent.permissionProfile ?? "",
|
|
586
|
-
projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
|
|
587
|
-
trustedCwd: trustedProjectCwd(ctx),
|
|
588
|
-
effectiveCwd: path.resolve(childCwd),
|
|
589
|
-
messageStyle: "executor",
|
|
590
|
-
});
|
|
590
|
+
return projectScopedProfileTrustError({
|
|
591
|
+
kind: "permission",
|
|
592
|
+
agentName: agent.name,
|
|
593
|
+
profileName: agent.permissionProfile ?? "",
|
|
594
|
+
projectScoped: Boolean(agent.permissionProfile) && (agent.source === "project" || agent.override?.scope === "project"),
|
|
595
|
+
trustedCwd: trustedProjectCwd(ctx),
|
|
596
|
+
effectiveCwd: path.resolve(childCwd),
|
|
597
|
+
messageStyle: "executor",
|
|
598
|
+
});
|
|
591
599
|
}
|
|
592
600
|
|
|
593
601
|
export function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean {
|
|
@@ -668,6 +676,11 @@ function trustedSessionRootsForStatus(ctx: ExtensionContext, deps: ExecutorDeps)
|
|
|
668
676
|
return [...new Set(roots)];
|
|
669
677
|
}
|
|
670
678
|
|
|
679
|
+
/** Children follow the launching session's trust; hosts older than Pi's trust concept keep Pi's default. */
|
|
680
|
+
function sessionProjectTrust(ctx: ExtensionContext): boolean | undefined {
|
|
681
|
+
return typeof ctx.isProjectTrusted === "function" ? ctx.isProjectTrusted() : undefined;
|
|
682
|
+
}
|
|
683
|
+
|
|
671
684
|
function spawnBudgetErrorResult(message: string, mode: "single" | "parallel" | "chain"): AgentToolResult<Details> {
|
|
672
685
|
return {
|
|
673
686
|
content: [{ type: "text", text: message }],
|
|
@@ -846,8 +859,8 @@ function rememberForegroundRun(state: SubagentState, input: { modelResponseAlias
|
|
|
846
859
|
...(result.detachedReason ? { detachedReason: result.detachedReason } : {}),
|
|
847
860
|
...(result.acceptance ? { acceptance: result.acceptance } : {}),
|
|
848
861
|
...(Object.keys(resumeContract).length ? { resumeContract } : {}),
|
|
849
|
-
...(result.sandbox ? { sandbox: result.sandbox } : {}),
|
|
850
|
-
...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
|
|
862
|
+
...(result.sandbox ? { sandbox: result.sandbox } : {}),
|
|
863
|
+
...(result.permissionProfile ? { permissionProfile: result.permissionProfile } : {}),
|
|
851
864
|
...(result.launchContractDigest ? { launchContractDigest: result.launchContractDigest } : {}),
|
|
852
865
|
...(input.extensionBindings ? { extensionBindings: input.extensionBindings } : {}),
|
|
853
866
|
...(input.requiredExtensions?.length ? { requiredExtensions: input.requiredExtensions } : {}),
|
|
@@ -930,8 +943,8 @@ function updateRememberedForegroundChild(state: SubagentState, input: { runId: s
|
|
|
930
943
|
...(input.result.transcriptError ? { transcriptError: input.result.transcriptError } : {}),
|
|
931
944
|
...(input.result.detachedReason ? { detachedReason: input.result.detachedReason } : {}),
|
|
932
945
|
...(input.result.acceptance ? { acceptance: input.result.acceptance } : {}),
|
|
933
|
-
...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
|
|
934
|
-
...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
|
|
946
|
+
...(input.result.sandbox ? { sandbox: input.result.sandbox } : {}),
|
|
947
|
+
...(input.result.permissionProfile ? { permissionProfile: input.result.permissionProfile } : {}),
|
|
935
948
|
...(input.result.launchContractDigest ? { launchContractDigest: input.result.launchContractDigest } : {}),
|
|
936
949
|
...(input.result.launchResolvedExtensions ? { launchResolvedExtensions: input.result.launchResolvedExtensions } : {}),
|
|
937
950
|
...(input.result.runtimeAcknowledgedExtensions ? { runtimeAcknowledgedExtensions: input.result.runtimeAcknowledgedExtensions } : {}),
|
|
@@ -1001,8 +1014,8 @@ function resolveForegroundResumeTarget(params: SubagentParamsLike, state: Subage
|
|
|
1001
1014
|
sessionFile,
|
|
1002
1015
|
...(child.model ? { model: child.model } : {}),
|
|
1003
1016
|
...(child.thinking ? { thinking: child.thinking } : {}),
|
|
1004
|
-
...(child.sandbox ? { sandbox: child.sandbox } : {}),
|
|
1005
|
-
...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
|
|
1017
|
+
...(child.sandbox ? { sandbox: child.sandbox } : {}),
|
|
1018
|
+
...(child.permissionProfile ? { permissionProfile: child.permissionProfile } : {}),
|
|
1006
1019
|
...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
|
|
1007
1020
|
...(child.resumeContract ? { resumeContract: child.resumeContract } : {}),
|
|
1008
1021
|
...(child.extensionBindings ? { extensionBindings: normalizeExtensionBindings(child.extensionBindings)!.value } : {}),
|
|
@@ -1024,8 +1037,8 @@ type NestedResumeSourceTarget = {
|
|
|
1024
1037
|
sessionFile: string;
|
|
1025
1038
|
model?: string;
|
|
1026
1039
|
thinking?: AgentConfig["thinking"];
|
|
1027
|
-
sandbox?: string;
|
|
1028
|
-
permissionProfile?: string;
|
|
1040
|
+
sandbox?: string;
|
|
1041
|
+
permissionProfile?: string;
|
|
1029
1042
|
launchContractDigest?: string;
|
|
1030
1043
|
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
1031
1044
|
recoveryDescriptor?: SteeringRecoveryDescriptor;
|
|
@@ -1407,9 +1420,10 @@ function appendStepToAsyncChain(input: {
|
|
|
1407
1420
|
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
1408
1421
|
currentModelProvider: parentModel?.provider,
|
|
1409
1422
|
currentModel: parentModel,
|
|
1423
|
+
scopedModelIds: scopedModelIdsFromContext(input.ctx),
|
|
1410
1424
|
modelScope: discoveredForAppend.modelScope,
|
|
1411
|
-
projectTrusted: currentProjectTrusted(input.ctx),
|
|
1412
|
-
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
1425
|
+
projectTrusted: currentProjectTrusted(input.ctx),
|
|
1426
|
+
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
1413
1427
|
modelResponseAliases: input.deps.config.modelResponseAliases,
|
|
1414
1428
|
interactive: input.ctx.hasUI,
|
|
1415
1429
|
permissions: input.deps.config.permissions,
|
|
@@ -1561,7 +1575,7 @@ function resolveNestedResumeTarget(match: ResolvedSubagentRunId & { kind: "neste
|
|
|
1561
1575
|
index: 0,
|
|
1562
1576
|
cwd: asyncDir ? path.dirname(asyncDir) : undefined,
|
|
1563
1577
|
sessionFile: validateNestedSessionFile(run, trustedSessionRoots),
|
|
1564
|
-
...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
|
|
1578
|
+
...(recoveryDescriptor?.sandbox ?? run.sandbox ? { sandbox: recoveryDescriptor?.sandbox ?? run.sandbox } : {}),
|
|
1565
1579
|
...(run.capabilityCeiling ? { capabilityCeiling: run.capabilityCeiling } : {}),
|
|
1566
1580
|
...(recoveryDescriptor ? { recoveryDescriptor } : {}),
|
|
1567
1581
|
});
|
|
@@ -1840,11 +1854,13 @@ async function resumeExternalJobFollowUp(input: {
|
|
|
1840
1854
|
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
1841
1855
|
currentModelProvider: parentModel?.provider,
|
|
1842
1856
|
currentModel: parentModel,
|
|
1857
|
+
scopedModelIds: scopedModelIdsFromContext(input.ctx),
|
|
1843
1858
|
modelScope: input.modelScope,
|
|
1844
1859
|
modelResponseAliases: input.deps.config.modelResponseAliases,
|
|
1845
1860
|
interactive: input.ctx.hasUI,
|
|
1846
1861
|
permissions: input.deps.config.permissions,
|
|
1847
1862
|
childRuntime: input.deps.childRuntime,
|
|
1863
|
+
projectTrusted: currentProjectTrusted(input.ctx),
|
|
1848
1864
|
}),
|
|
1849
1865
|
cwd: input.effectiveCwd,
|
|
1850
1866
|
artifactsDir,
|
|
@@ -1920,6 +1936,14 @@ async function resumeAsyncRun(input: {
|
|
|
1920
1936
|
details: { mode: "management", results: [] },
|
|
1921
1937
|
};
|
|
1922
1938
|
}
|
|
1939
|
+
const timeoutOverflowError = timerDelayOverflowError("timeoutMs", input.params.timeoutMs);
|
|
1940
|
+
if (timeoutOverflowError) {
|
|
1941
|
+
return {
|
|
1942
|
+
content: [{ type: "text", text: timeoutOverflowError }],
|
|
1943
|
+
isError: true,
|
|
1944
|
+
details: { mode: "management", results: [] },
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1923
1947
|
if (input.params.model !== undefined) {
|
|
1924
1948
|
return {
|
|
1925
1949
|
content: [{ type: "text", text: "action='resume' reuses the persisted child model and does not accept a model override." }],
|
|
@@ -2101,12 +2125,13 @@ async function resumeAsyncRun(input: {
|
|
|
2101
2125
|
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
2102
2126
|
currentModelProvider: parentModel?.provider,
|
|
2103
2127
|
currentModel: parentModel,
|
|
2128
|
+
scopedModelIds: scopedModelIdsFromContext(input.ctx),
|
|
2104
2129
|
modelScope,
|
|
2105
|
-
projectTrusted: currentProjectTrusted(input.ctx),
|
|
2106
|
-
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
2130
|
+
projectTrusted: currentProjectTrusted(input.ctx),
|
|
2131
|
+
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
2107
2132
|
modelResponseAliases: input.deps.config.modelResponseAliases,
|
|
2108
2133
|
interactive: input.ctx.hasUI,
|
|
2109
|
-
|
|
2134
|
+
permissions: input.deps.config.permissions,
|
|
2110
2135
|
childRuntime: input.deps.childRuntime,
|
|
2111
2136
|
}),
|
|
2112
2137
|
availableModels,
|
|
@@ -2223,7 +2248,7 @@ projectTrusted: currentProjectTrusted(input.ctx),
|
|
|
2223
2248
|
goal: effectiveFollowUp,
|
|
2224
2249
|
agentConfig,
|
|
2225
2250
|
recoveryAgentConfig,
|
|
2226
|
-
...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
|
|
2251
|
+
...(recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : undefined) } : {}),
|
|
2227
2252
|
ctx: compactOptional<Parameters<typeof executeAsyncSingle>[1]["ctx"]>({
|
|
2228
2253
|
pi: input.deps.pi,
|
|
2229
2254
|
cwd: input.requestCwd,
|
|
@@ -2231,9 +2256,10 @@ projectTrusted: currentProjectTrusted(input.ctx),
|
|
|
2231
2256
|
parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
|
|
2232
2257
|
currentModelProvider: parentModel?.provider,
|
|
2233
2258
|
currentModel: parentModel,
|
|
2259
|
+
scopedModelIds: scopedModelIdsFromContext(input.ctx),
|
|
2234
2260
|
modelScope,
|
|
2235
|
-
projectTrusted: currentProjectTrusted(input.ctx),
|
|
2236
|
-
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
2261
|
+
projectTrusted: currentProjectTrusted(input.ctx),
|
|
2262
|
+
...(trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {}),
|
|
2237
2263
|
// Absence in the retained contract is meaningful; never acquire current aliases.
|
|
2238
2264
|
modelResponseAliases: recoveryDescriptor ? recoveryDescriptor.modelResponseAliases : foregroundContract?.modelResponseAliases,
|
|
2239
2265
|
interactive: input.ctx.hasUI,
|
|
@@ -2333,63 +2359,31 @@ projectTrusted: currentProjectTrusted(input.ctx),
|
|
|
2333
2359
|
if (input.params.workflowParentRunId !== undefined && result.details.asyncDir) {
|
|
2334
2360
|
const asyncDir = result.details.asyncDir;
|
|
2335
2361
|
const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
|
|
2336
|
-
const
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
}
|
|
2345
|
-
if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, revivedId, completed.importedPublication);
|
|
2346
|
-
emitWorkflowAwaitedChildComplete(input.deps.pi, input.deps.state, revivedId, asyncDir, input.params.workflowParentRunId, completed);
|
|
2347
|
-
const usage = importedAsyncRootUsage(completed);
|
|
2348
|
-
const childResult: SingleResult = {
|
|
2349
|
-
index: 0,
|
|
2350
|
-
agent: completed.agent,
|
|
2351
|
-
...(completed.sessionName ? { sessionName: completed.sessionName } : {}),
|
|
2352
|
-
task: effectiveFollowUp,
|
|
2353
|
-
exitCode: completed.exitCode,
|
|
2354
|
-
usage,
|
|
2355
|
-
finalOutput: completed.output,
|
|
2356
|
-
outputState: completed.output.trim() ? "present" : "absent",
|
|
2357
|
-
...(completed.error ? { error: completed.error } : {}),
|
|
2358
|
-
...(completed.timedOut ? { timedOut: true } : {}),
|
|
2359
|
-
...(completed.stopped ? { stopped: true } : {}),
|
|
2360
|
-
...(completed.sessionFile ? { sessionFile: completed.sessionFile } : {}),
|
|
2361
|
-
...(completed.model ? { model: completed.model } : {}),
|
|
2362
|
-
...(completed.requestedModel ? { requestedModel: completed.requestedModel } : {}),
|
|
2363
|
-
...(completed.contextOverflow ? { contextOverflow: true } : {}),
|
|
2364
|
-
...(completed.structuredOutput !== undefined ? { structuredOutput: completed.structuredOutput } : {}),
|
|
2365
|
-
...(completed.structuredOutputPath ? { structuredOutputPath: completed.structuredOutputPath } : {}),
|
|
2366
|
-
...(completed.structuredOutputSchemaPath ? { structuredOutputSchemaPath: completed.structuredOutputSchemaPath } : {}),
|
|
2367
|
-
...(completed.acceptance ? { acceptance: completed.acceptance } : {}),
|
|
2368
|
-
...(completed.artifactPaths ? { artifactPaths: completed.artifactPaths } : {}),
|
|
2369
|
-
...(completed.savedOutputPath ? { savedOutputPath: completed.savedOutputPath } : {}),
|
|
2370
|
-
...(completed.outputSaveError ? { outputSaveError: completed.outputSaveError } : {}),
|
|
2371
|
-
...(completed.transcriptPath ? { transcriptPath: completed.transcriptPath } : {}),
|
|
2372
|
-
...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
|
|
2373
|
-
};
|
|
2374
|
-
return {
|
|
2375
|
-
content: [{ type: "text", text: completed.success ? completed.output || completed.error || `Revived ${target.source} subagent ${revivedId} completed without output.` : completed.error || completed.output || `Revived ${target.source} subagent ${revivedId} completed without output.` }],
|
|
2376
|
-
...(completed.success ? {} : { isError: true }),
|
|
2377
|
-
details: {
|
|
2378
|
-
...result.details,
|
|
2379
|
-
runId: revivedId,
|
|
2380
|
-
results: [childResult],
|
|
2381
|
-
...(target.launchContractDigest ? { sourceLaunchContractDigest: target.launchContractDigest } : {}),
|
|
2382
|
-
},
|
|
2383
|
-
};
|
|
2362
|
+
const stopListener = stopAwaitedAsyncChildOnAbort(input.signal, input.deps.state, revivedId, asyncDir, input.deps.kill);
|
|
2363
|
+
const completed = await waitForImportedAsyncRoot({ runId: revivedId, asyncDir, resultPath, index: 0 }, {
|
|
2364
|
+
shouldAbort: () => input.signal?.aborted === true,
|
|
2365
|
+
timeoutMessage: "Workflow stopped before async child completed.",
|
|
2366
|
+
abortedAsStopped: true,
|
|
2367
|
+
}).finally(stopListener.remove);
|
|
2368
|
+
const details: Details = { ...result.details };
|
|
2369
|
+
if (target.launchContractDigest) details.sourceLaunchContractDigest = target.launchContractDigest;
|
|
2370
|
+
return importWorkflowAwaitedChildResult(completed, { runId: revivedId, asyncDir, resultPath, task: effectiveFollowUp, parentWorkflowRunId: input.params.workflowParentRunId, details, emptyOutputText: `Revived ${target.source} subagent ${revivedId} completed without output.`, state: input.deps.state, pi: input.deps.pi });
|
|
2384
2371
|
}
|
|
2385
2372
|
const revivedTarget = intercomBridge.active ? resolveSubagentIntercomTarget(revivedId, target.agent, 0) : undefined;
|
|
2386
2373
|
const sourceLabel = target.source;
|
|
2374
|
+
let workflowRevivalWarning: string | undefined;
|
|
2375
|
+
try {
|
|
2376
|
+
if (target.source === "async") recordWorkflowRevival(DIRS.async, target.runId, revivedId);
|
|
2377
|
+
} catch (error) {
|
|
2378
|
+
workflowRevivalWarning = `Warning: workflow key link not recorded: ${error instanceof Error ? error.message : String(error)}`;
|
|
2379
|
+
}
|
|
2387
2380
|
const lines = [
|
|
2388
2381
|
`Revived ${sourceLabel} subagent from ${target.runId}.`,
|
|
2389
2382
|
`Revived run: ${revivedId}`,
|
|
2390
2383
|
`Agent: ${target.agent}`,
|
|
2391
2384
|
`Session: ${target.sessionFile}`,
|
|
2392
2385
|
result.details.asyncDir ? `Async dir: ${result.details.asyncDir}` : undefined,
|
|
2386
|
+
workflowRevivalWarning,
|
|
2393
2387
|
revivedTarget ? `Intercom target: ${revivedTarget} (if registered)` : undefined,
|
|
2394
2388
|
`Status if needed: subagent({ action: "status", id: "${revivedId}" })`,
|
|
2395
2389
|
].filter((line): line is string => Boolean(line));
|
|
@@ -2557,6 +2551,28 @@ function canonicalizeAgentName(name: string, agents: AgentConfig[], diagnostics:
|
|
|
2557
2551
|
return { name: resolved.agent.name };
|
|
2558
2552
|
}
|
|
2559
2553
|
|
|
2554
|
+
// Mirrors child launch: workflow children without their own cwd/agentScope discover agents at the workflow cwd and scope.
|
|
2555
|
+
function workflowValidationOptions(deps: ExecutorDeps, params: SubagentParamsLike, runtimeCwd: string, parentModelProvider: () => string | undefined): Parameters<typeof validateWorkflowScript>[1] {
|
|
2556
|
+
const cwd = resolveRequestedCwd(runtimeCwd, params.cwd);
|
|
2557
|
+
const scope = resolveExecutionAgentScope(params.agentScope);
|
|
2558
|
+
let discovered: ReturnType<ExecutorDeps["discoverAgents"]> | undefined;
|
|
2559
|
+
return {
|
|
2560
|
+
maxSubagentSpawnsPerRun: params.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
|
|
2561
|
+
agentNameError: (name) => {
|
|
2562
|
+
discovered ??= deps.discoverAgents(cwd, scope, parentModelProvider());
|
|
2563
|
+
const { agents } = discovered;
|
|
2564
|
+
const resolved = resolveAgentName(name, agents);
|
|
2565
|
+
if (resolved.agent || resolved.error) return canonicalizeAgentName(name, agents, discovered.agentDiagnostics, diagnosticContextFromDiscovery(discovered, cwd, scope)).error;
|
|
2566
|
+
const requested = name.trim().toLowerCase();
|
|
2567
|
+
const suggestion = [...new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])]))]
|
|
2568
|
+
.map((candidate) => ({ candidate, distance: editDistance(requested, candidate.toLowerCase()) }))
|
|
2569
|
+
.filter(({ candidate, distance }) => distance <= Math.max(1, Math.floor(candidate.length / 4)) || hasSingleAdjacentTransposition(requested, candidate.toLowerCase()))
|
|
2570
|
+
.sort((left, right) => left.distance - right.distance || left.candidate.localeCompare(right.candidate))[0]?.candidate;
|
|
2571
|
+
return `Unknown agent '${name}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Use subagent({ action: "list" }) to inspect agents.`;
|
|
2572
|
+
},
|
|
2573
|
+
};
|
|
2574
|
+
}
|
|
2575
|
+
|
|
2560
2576
|
function canonicalizeExecutionParams(params: SubagentParamsLike, agents: AgentConfig[], diagnostics: AgentDiscoveryDiagnostic[] | undefined, context: UnknownAgentDiagnosticContext): { params?: SubagentParamsLike; error?: string } {
|
|
2561
2577
|
const resolve = (name: string, location?: string): { name?: string; error?: string } => {
|
|
2562
2578
|
const result = canonicalizeAgentName(name, agents, diagnostics, context);
|
|
@@ -2979,6 +2995,12 @@ export { DEFAULT_ASYNC_TIMEOUT_MS };
|
|
|
2979
2995
|
*/
|
|
2980
2996
|
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
|
2981
2997
|
|
|
2998
|
+
function timerDelayOverflowError(name: string, value: unknown): string | undefined {
|
|
2999
|
+
return typeof value === "number" && value > MAX_TIMER_DELAY_MS
|
|
3000
|
+
? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.`
|
|
3001
|
+
: undefined;
|
|
3002
|
+
}
|
|
3003
|
+
|
|
2982
3004
|
/**
|
|
2983
3005
|
* Resolve the optional global default runtime deadline from extension config
|
|
2984
3006
|
* (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
|
|
@@ -3002,6 +3024,8 @@ export function resolveForegroundTimeout(params: SubagentParamsLike, defaultTime
|
|
|
3002
3024
|
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
|
|
3003
3025
|
return { error: `${name} must be a positive integer.` };
|
|
3004
3026
|
}
|
|
3027
|
+
const overflowError = timerDelayOverflowError(name, value);
|
|
3028
|
+
if (overflowError) return { error: overflowError };
|
|
3005
3029
|
}
|
|
3006
3030
|
if (rawTimeout !== undefined && rawMaxRuntime !== undefined && rawTimeout !== rawMaxRuntime) {
|
|
3007
3031
|
return { error: "timeoutMs and maxRuntimeMs are aliases; provide only one value or use the same value for both." };
|
|
@@ -3157,6 +3181,7 @@ function resolveStaticLaunchSummary(input: {
|
|
|
3157
3181
|
explicitModel?: string;
|
|
3158
3182
|
agents: AgentConfig[];
|
|
3159
3183
|
parentModel?: ParentModel;
|
|
3184
|
+
scopedModelIds?: string[];
|
|
3160
3185
|
availableModels: ModelInfo[];
|
|
3161
3186
|
currentProvider?: string;
|
|
3162
3187
|
modelScope?: ModelScopeConfig;
|
|
@@ -3164,7 +3189,7 @@ function resolveStaticLaunchSummary(input: {
|
|
|
3164
3189
|
}): StaticLaunchSummary {
|
|
3165
3190
|
const agentConfig = input.agents.find((agent) => agent.name === input.agent);
|
|
3166
3191
|
const externalRunner = agentConfig?.runner?.type === "external-cli" || agentConfig?.runner?.type === "external-job";
|
|
3167
|
-
const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel);
|
|
3192
|
+
const modelScopes = resolveModelScopesForAgent(input.modelScope, input.agent, input.parentModel, input.scopedModelIds);
|
|
3168
3193
|
const model = externalRunner
|
|
3169
3194
|
? undefined
|
|
3170
3195
|
: resolveEffectiveSubagentModel(
|
|
@@ -3181,7 +3206,7 @@ function resolveStaticLaunchSummary(input: {
|
|
|
3181
3206
|
agent: input.agent,
|
|
3182
3207
|
...(model ? { model } : {}),
|
|
3183
3208
|
...(thinking ? { thinking } : {}),
|
|
3184
|
-
...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
|
|
3209
|
+
...(agentConfig?.sandbox ? { sandbox: agentConfig.sandbox } : {}),
|
|
3185
3210
|
};
|
|
3186
3211
|
}
|
|
3187
3212
|
|
|
@@ -3189,6 +3214,7 @@ function collectStaticLaunchSummaries(input: {
|
|
|
3189
3214
|
params: SubagentParamsLike;
|
|
3190
3215
|
agents: AgentConfig[];
|
|
3191
3216
|
parentModel?: ParentModel;
|
|
3217
|
+
scopedModelIds?: string[];
|
|
3192
3218
|
availableModels: ModelInfo[];
|
|
3193
3219
|
currentProvider?: string;
|
|
3194
3220
|
modelScope?: ModelScopeConfig;
|
|
@@ -3201,6 +3227,7 @@ function collectStaticLaunchSummaries(input: {
|
|
|
3201
3227
|
explicitModel,
|
|
3202
3228
|
agents: input.agents,
|
|
3203
3229
|
parentModel: input.parentModel,
|
|
3230
|
+
scopedModelIds: input.scopedModelIds,
|
|
3204
3231
|
availableModels: input.availableModels,
|
|
3205
3232
|
currentProvider: input.currentProvider,
|
|
3206
3233
|
modelScope: input.modelScope,
|
|
@@ -3386,28 +3413,13 @@ function emitWorkflowAwaitedChildComplete(
|
|
|
3386
3413
|
});
|
|
3387
3414
|
}
|
|
3388
3415
|
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
options: { runId: string; task: string;
|
|
3393
|
-
):
|
|
3394
|
-
if (
|
|
3395
|
-
|
|
3396
|
-
const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
|
|
3397
|
-
const stopOnAbort = () => { stopAsyncRun(options.state, options.runId, options.kill, { asyncDir, resolvedId: options.runId }); };
|
|
3398
|
-
if (options.signal?.aborted) stopOnAbort();
|
|
3399
|
-
else options.signal?.addEventListener("abort", stopOnAbort, { once: true });
|
|
3400
|
-
let completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>;
|
|
3401
|
-
try {
|
|
3402
|
-
completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
|
|
3403
|
-
shouldAbort: () => options.signal?.aborted === true,
|
|
3404
|
-
timeoutMessage: "Workflow stopped before async child completed.",
|
|
3405
|
-
}));
|
|
3406
|
-
} finally {
|
|
3407
|
-
options.signal?.removeEventListener("abort", stopOnAbort);
|
|
3408
|
-
}
|
|
3409
|
-
if (completed.importedPublication) removeWorkflowAwaitedResult(asyncDir, resultPath, options.runId, completed.importedPublication);
|
|
3410
|
-
emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, asyncDir, params.workflowParentRunId, completed);
|
|
3416
|
+
/** Consumes an awaited workflow child's published result: clears the payload, announces completion, and builds the tool result. */
|
|
3417
|
+
function importWorkflowAwaitedChildResult(
|
|
3418
|
+
completed: Awaited<ReturnType<typeof waitForImportedAsyncRoot>>,
|
|
3419
|
+
options: { runId: string; asyncDir: string; resultPath: string; task: string; parentWorkflowRunId: string | undefined; details: Details; emptyOutputText?: string; state: SubagentState; pi: ExtensionAPI },
|
|
3420
|
+
): AgentToolResult<Details> {
|
|
3421
|
+
if (completed.importedPublication) removeWorkflowAwaitedResult(options.asyncDir, options.resultPath, options.runId, completed.importedPublication);
|
|
3422
|
+
emitWorkflowAwaitedChildComplete(options.pi, options.state, options.runId, options.asyncDir, options.parentWorkflowRunId, completed);
|
|
3411
3423
|
const usage = importedAsyncRootUsage(completed);
|
|
3412
3424
|
const childResult: SingleResult = omitUndefinedProperties({
|
|
3413
3425
|
index: 0,
|
|
@@ -3436,16 +3448,55 @@ async function waitForWorkflowAsyncSingleResult(
|
|
|
3436
3448
|
...(completed.transcriptError ? { transcriptError: completed.transcriptError } : {}),
|
|
3437
3449
|
});
|
|
3438
3450
|
return {
|
|
3439
|
-
content: [{ type: "text", text: completed.success ? completed.output || completed.error
|
|
3451
|
+
content: [{ type: "text", text: (completed.success ? completed.output || completed.error : completed.error || completed.output) || (options.emptyOutputText ?? `Async workflow child ${options.runId} completed without output.`) }],
|
|
3440
3452
|
...(completed.success ? {} : { isError: true }),
|
|
3441
3453
|
details: {
|
|
3442
|
-
...
|
|
3454
|
+
...options.details,
|
|
3443
3455
|
runId: options.runId,
|
|
3444
3456
|
results: [childResult],
|
|
3445
3457
|
},
|
|
3446
3458
|
};
|
|
3447
3459
|
}
|
|
3448
3460
|
|
|
3461
|
+
// A replaced runtime leaves the child running so a relaunch of the workflow can re-attach to it.
|
|
3462
|
+
function stopAwaitedAsyncChildOnAbort(signal: AbortSignal | undefined, state: SubagentState, runId: string, asyncDir: string, kill?: ExecutorDeps["kill"]): { remove: () => void } {
|
|
3463
|
+
const stopOnAbort = () => { if (!workflowStopCause(signal?.reason)) stopAsyncRun(state, runId, kill, { asyncDir, resolvedId: runId }); };
|
|
3464
|
+
if (signal?.aborted) stopOnAbort();
|
|
3465
|
+
else signal?.addEventListener("abort", stopOnAbort, { once: true });
|
|
3466
|
+
return { remove: () => signal?.removeEventListener("abort", stopOnAbort) };
|
|
3467
|
+
}
|
|
3468
|
+
|
|
3469
|
+
// Live workflow controls are keyed by the full run id; a stop id may be a prefix or the launch tool-call id.
|
|
3470
|
+
function resolveLiveWorkflowRunId(deps: ExecutorDeps, id: string): string | undefined {
|
|
3471
|
+
const controllers = deps.state.workflowControllers;
|
|
3472
|
+
if (!controllers?.size) return undefined;
|
|
3473
|
+
if (controllers.has(id)) return id;
|
|
3474
|
+
try {
|
|
3475
|
+
const resolved = resolveSubagentRunId(id, omitUndefinedProperties({ state: deps.state, nested: nestedResolutionScopeForExecutor(deps) }));
|
|
3476
|
+
return resolved?.kind === "async" && controllers.has(resolved.id) ? resolved.id : undefined;
|
|
3477
|
+
} catch {
|
|
3478
|
+
// The generic stop path resolves the id again and reports the error.
|
|
3479
|
+
return undefined;
|
|
3480
|
+
}
|
|
3481
|
+
}
|
|
3482
|
+
|
|
3483
|
+
async function waitForWorkflowAsyncSingleResult(
|
|
3484
|
+
params: SubagentParamsLike,
|
|
3485
|
+
launchResult: AgentToolResult<Details>,
|
|
3486
|
+
options: { runId: string; task: string; signal?: AbortSignal; state: SubagentState; pi: ExtensionAPI; kill?: ExecutorDeps["kill"] },
|
|
3487
|
+
): Promise<AgentToolResult<Details>> {
|
|
3488
|
+
if (params.workflowAwaitAsync !== true || !launchResult.details.asyncDir) return launchResult;
|
|
3489
|
+
const asyncDir = launchResult.details.asyncDir;
|
|
3490
|
+
const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
|
|
3491
|
+
const stopListener = stopAwaitedAsyncChildOnAbort(options.signal, options.state, options.runId, asyncDir, options.kill);
|
|
3492
|
+
const completed = await waitForImportedAsyncRoot({ runId: options.runId, asyncDir, resultPath, index: 0 }, omitUndefinedProperties({
|
|
3493
|
+
shouldAbort: () => options.signal?.aborted === true,
|
|
3494
|
+
timeoutMessage: "Workflow stopped before async child completed.",
|
|
3495
|
+
abortedAsStopped: true,
|
|
3496
|
+
})).finally(stopListener.remove);
|
|
3497
|
+
return importWorkflowAwaitedChildResult(completed, { runId: options.runId, asyncDir, resultPath, task: options.task, parentWorkflowRunId: params.workflowParentRunId, details: launchResult.details, state: options.state, pi: options.pi });
|
|
3498
|
+
}
|
|
3499
|
+
|
|
3449
3500
|
async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Promise<AgentToolResult<Details> | null> {
|
|
3450
3501
|
const {
|
|
3451
3502
|
params,
|
|
@@ -3487,10 +3538,11 @@ async function runAsyncPath(data: ExecutionContextData, deps: ExecutorDeps): Pro
|
|
|
3487
3538
|
parentSessionId: data.parentPiSessionId,
|
|
3488
3539
|
currentModelProvider: parentModel?.provider,
|
|
3489
3540
|
currentModel: parentModel,
|
|
3541
|
+
scopedModelIds: data.scopedModelIds,
|
|
3490
3542
|
modelScope: data.modelScope,
|
|
3491
|
-
projectTrusted: currentProjectTrusted(ctx),
|
|
3492
|
-
...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
|
|
3493
|
-
modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
|
|
3543
|
+
projectTrusted: currentProjectTrusted(ctx),
|
|
3544
|
+
...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
|
|
3545
|
+
modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
|
|
3494
3546
|
permissions: deps.config.permissions,
|
|
3495
3547
|
childRuntime: deps.childRuntime,
|
|
3496
3548
|
});
|
|
@@ -3510,18 +3562,18 @@ modelResponseAliases: deps.config.modelResponseAliases, interactive: ctx.hasUI,
|
|
|
3510
3562
|
details: { mode: "single" as const, results: [] },
|
|
3511
3563
|
};
|
|
3512
3564
|
}
|
|
3513
|
-
const sandboxTrustError = params.worktree === true
|
|
3514
|
-
? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
|
|
3515
|
-
: sandboxProfileTrustError(a, ctx, effectiveCwd);
|
|
3516
|
-
if (sandboxTrustError) {
|
|
3517
|
-
return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
|
|
3518
|
-
}
|
|
3519
|
-
const permissionProfileTrustErrorForAgent = params.worktree === true
|
|
3520
|
-
? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
|
|
3521
|
-
: permissionProfileTrustError(a, ctx, effectiveCwd);
|
|
3522
|
-
if (permissionProfileTrustErrorForAgent) {
|
|
3523
|
-
return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
|
|
3524
|
-
}
|
|
3565
|
+
const sandboxTrustError = params.worktree === true
|
|
3566
|
+
? sandboxProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
|
|
3567
|
+
: sandboxProfileTrustError(a, ctx, effectiveCwd);
|
|
3568
|
+
if (sandboxTrustError) {
|
|
3569
|
+
return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single" as const, results: [] } };
|
|
3570
|
+
}
|
|
3571
|
+
const permissionProfileTrustErrorForAgent = params.worktree === true
|
|
3572
|
+
? permissionProfileTrustError(a, ctx, path.join(effectiveCwd, ".pi-subagents-worktree"))
|
|
3573
|
+
: permissionProfileTrustError(a, ctx, effectiveCwd);
|
|
3574
|
+
if (permissionProfileTrustErrorForAgent) {
|
|
3575
|
+
return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }], isError: true, details: { mode: "single" as const, results: [] } };
|
|
3576
|
+
}
|
|
3525
3577
|
const rawOutput = params.output !== undefined ? params.output : a.output;
|
|
3526
3578
|
const effectiveOutput = normalizeSingleOutputOverride(rawOutput, a.output);
|
|
3527
3579
|
const effectiveOutputMode = params.outputMode ?? a.outputMode ?? "inline";
|
|
@@ -3534,7 +3586,7 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForAgent }],
|
|
|
3534
3586
|
if ((a.runner?.type === "external-cli" || a.runner?.type === "external-job") && (params.fast ?? a.fast) === true) {
|
|
3535
3587
|
return buildRequestedModeError(params, `Agent '${a.name}' uses runner.type='${a.runner.type}' and does not support fast mode.`);
|
|
3536
3588
|
}
|
|
3537
|
-
const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel);
|
|
3589
|
+
const modelScopes = resolveModelScopesForAgent(data.modelScope, a.name, parentModel, data.scopedModelIds);
|
|
3538
3590
|
const modelOrigin = resolveModelOrigin({
|
|
3539
3591
|
storedOrigin: params.modelOrigin as ModelOrigin | undefined,
|
|
3540
3592
|
explicitModel: params.model as string | undefined,
|
|
@@ -3725,6 +3777,45 @@ function appendWorkflowOutputWarning(text: string, warning: string | undefined):
|
|
|
3725
3777
|
return warning ? `${text}\n\n${warning}` : text;
|
|
3726
3778
|
}
|
|
3727
3779
|
|
|
3780
|
+
const WORKFLOW_TRACE_ERROR_MAX_CHARS = 500;
|
|
3781
|
+
|
|
3782
|
+
// Return, emits, console, and trace errors (which carry child text) have no size limit of their
|
|
3783
|
+
// own, so only they are cut; other host sections stay whole. The saved full result is uncut.
|
|
3784
|
+
function formatWorkflowResultText(input: {
|
|
3785
|
+
head: string[];
|
|
3786
|
+
script: string[];
|
|
3787
|
+
trace: Array<{ line: string; error?: string }>;
|
|
3788
|
+
tail: string[];
|
|
3789
|
+
maxOutput: MaxOutputConfig | undefined;
|
|
3790
|
+
aggregateOutputPath: string | undefined;
|
|
3791
|
+
fullResultPath: string;
|
|
3792
|
+
producedChildOutputPaths: ReadonlySet<string>;
|
|
3793
|
+
}): string {
|
|
3794
|
+
const traceSection = (error: (text: string) => string) => input.trace.length > 0
|
|
3795
|
+
? [`Call trace:\n${input.trace.map((entry) => `${entry.line}${entry.error ? ` — ${error(entry.error)}` : ""}`).join("\n")}`]
|
|
3796
|
+
: [];
|
|
3797
|
+
const fullText = [...input.head, ...input.script, ...traceSection((error) => error), ...input.tail].join("\n\n");
|
|
3798
|
+
const outputWarning = writeWorkflowAggregateOutput(input.aggregateOutputPath, fullText, input.producedChildOutputPaths);
|
|
3799
|
+
const scriptText = input.script.join("\n\n");
|
|
3800
|
+
const config = { ...DEFAULT_MAX_OUTPUT, ...input.maxOutput };
|
|
3801
|
+
const scriptCut = truncateOutput(scriptText, config).truncated;
|
|
3802
|
+
const traceCut = input.trace.some((entry) => (entry.error?.length ?? 0) > WORKFLOW_TRACE_ERROR_MAX_CHARS);
|
|
3803
|
+
let shownScriptText = scriptText;
|
|
3804
|
+
let saveWarning: string | undefined;
|
|
3805
|
+
let savedPath: string | undefined;
|
|
3806
|
+
if (scriptCut || traceCut) {
|
|
3807
|
+
const aggregateHoldsFullText = input.aggregateOutputPath !== undefined && !outputWarning
|
|
3808
|
+
&& !input.producedChildOutputPaths.has(resolveWorkflowHostOutputClaimPath(input.aggregateOutputPath));
|
|
3809
|
+
if (!aggregateHoldsFullText) saveWarning = writeWorkflowAggregateOutput(input.fullResultPath, fullText, new Set());
|
|
3810
|
+
savedPath = aggregateHoldsFullText ? input.aggregateOutputPath : saveWarning ? undefined : input.fullResultPath;
|
|
3811
|
+
if (scriptCut) shownScriptText = truncateOutput(scriptText, config, savedPath).text;
|
|
3812
|
+
}
|
|
3813
|
+
const shownTrace = traceSection((error) => error.length > WORKFLOW_TRACE_ERROR_MAX_CHARS ? `${error.slice(0, WORKFLOW_TRACE_ERROR_MAX_CHARS)}… (+${error.length - WORKFLOW_TRACE_ERROR_MAX_CHARS} chars)` : error);
|
|
3814
|
+
const traceNote = traceCut && !scriptCut && savedPath ? [`[TRUNCATED: trace errors shortened - full output at ${savedPath}]`] : [];
|
|
3815
|
+
const text = [...input.head, ...(shownScriptText ? [shownScriptText] : []), ...shownTrace, ...input.tail, ...traceNote].join("\n\n");
|
|
3816
|
+
return appendWorkflowOutputWarning(appendWorkflowOutputWarning(text, outputWarning), saveWarning);
|
|
3817
|
+
}
|
|
3818
|
+
|
|
3728
3819
|
export function resolveWorkflowChildLocalCwd(input: {
|
|
3729
3820
|
workflowCwd: string;
|
|
3730
3821
|
discoverAgents: (cwd: string, scope: AgentScope) => { agents: AgentConfig[] };
|
|
@@ -4013,7 +4104,7 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
|
|
|
4013
4104
|
const parentModel = data.parentModel;
|
|
4014
4105
|
const currentProvider = parentModel?.provider;
|
|
4015
4106
|
const availableModels: ModelInfo[] = ctx.modelRegistry.getAvailable().map(toModelInfo);
|
|
4016
|
-
const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel);
|
|
4107
|
+
const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
|
|
4017
4108
|
let task = typeof params.task === "string" ? params.task : "";
|
|
4018
4109
|
const modelOrigin = resolveModelOrigin({
|
|
4019
4110
|
storedOrigin: params.modelOrigin as ModelOrigin | undefined,
|
|
@@ -4082,16 +4173,16 @@ async function runSinglePath(data: ExecutionContextData, deps: ExecutorDeps): Pr
|
|
|
4082
4173
|
return worktreeSetupError;
|
|
4083
4174
|
}
|
|
4084
4175
|
const singleCwd = worktreeSetup?.worktrees[0]?.agentCwd ?? sourceCwd;
|
|
4085
|
-
const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
|
|
4086
|
-
if (sandboxTrustError) {
|
|
4087
|
-
if (worktreeSetup) cleanupWorktrees(worktreeSetup);
|
|
4088
|
-
return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
|
|
4089
|
-
}
|
|
4090
|
-
const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
|
|
4091
|
-
if (permissionProfileTrustErrorForLaunch) {
|
|
4092
|
-
if (worktreeSetup) cleanupWorktrees(worktreeSetup);
|
|
4093
|
-
return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
|
|
4094
|
-
}
|
|
4176
|
+
const sandboxTrustError = sandboxProfileTrustError(agentConfig, ctx, singleCwd);
|
|
4177
|
+
if (sandboxTrustError) {
|
|
4178
|
+
if (worktreeSetup) cleanupWorktrees(worktreeSetup);
|
|
4179
|
+
return { content: [{ type: "text", text: sandboxTrustError }], isError: true, details: { mode: "single", results: [] } };
|
|
4180
|
+
}
|
|
4181
|
+
const permissionProfileTrustErrorForLaunch = permissionProfileTrustError(agentConfig, ctx, singleCwd);
|
|
4182
|
+
if (permissionProfileTrustErrorForLaunch) {
|
|
4183
|
+
if (worktreeSetup) cleanupWorktrees(worktreeSetup);
|
|
4184
|
+
return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }], isError: true, details: { mode: "single", results: [] } };
|
|
4185
|
+
}
|
|
4095
4186
|
const cleanupSingleWorktree = async () => {
|
|
4096
4187
|
if (!worktreeSetup) return;
|
|
4097
4188
|
let admitted = false;
|
|
@@ -4148,6 +4239,20 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
|
|
|
4148
4239
|
let detachForeground: ((reason?: string) => boolean) | undefined;
|
|
4149
4240
|
let childSessionControls: ForegroundChildSessionControls | undefined;
|
|
4150
4241
|
const foregroundControl = deps.state.foregroundControls.get(runId);
|
|
4242
|
+
const syncHerdrForegroundChild = () => {
|
|
4243
|
+
if (!foregroundControl?.parentWorkflowRunId) return;
|
|
4244
|
+
try {
|
|
4245
|
+
deps.pi.events.emit(HERDR_FOREGROUND_CONTROL_CHANGED_EVENT, { runId: foregroundControl.parentWorkflowRunId });
|
|
4246
|
+
} catch (error) {
|
|
4247
|
+
console.error("Failed to sync Herdr foreground child:", error);
|
|
4248
|
+
}
|
|
4249
|
+
};
|
|
4250
|
+
const finishTrackedForegroundChild = () => {
|
|
4251
|
+
if (!foregroundControl) return;
|
|
4252
|
+
const wasActive = foregroundControl.activeChildren?.has(0) === true;
|
|
4253
|
+
finishForegroundChild(foregroundControl, 0);
|
|
4254
|
+
if (wasActive) syncHerdrForegroundChild();
|
|
4255
|
+
};
|
|
4151
4256
|
if (foregroundControl) {
|
|
4152
4257
|
const thinking = resolveEffectiveThinking(modelOverride, thinkingOverrideForTask());
|
|
4153
4258
|
beginForegroundChild(foregroundControl, omitUndefinedProperties({
|
|
@@ -4183,6 +4288,7 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
|
|
|
4183
4288
|
}));
|
|
4184
4289
|
// Capture the owned mailbox before a child can start and finish between polling ticks.
|
|
4185
4290
|
if (deps.childRuntime?.fanoutChild) deps.activateSupervisorTransport?.();
|
|
4291
|
+
syncHerdrForegroundChild();
|
|
4186
4292
|
}
|
|
4187
4293
|
|
|
4188
4294
|
const modelResponseAliases = deps.config.modelResponseAliases === undefined ? undefined : structuredClone(deps.config.modelResponseAliases);
|
|
@@ -4208,8 +4314,8 @@ return { content: [{ type: "text", text: permissionProfileTrustErrorForLaunch }]
|
|
|
4208
4314
|
permissions: deps.config.permissions,
|
|
4209
4315
|
runtimeSnapshotHost: deps.pi,
|
|
4210
4316
|
parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
|
|
4211
|
-
projectTrusted: currentProjectTrusted(ctx),
|
|
4212
|
-
...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
|
|
4317
|
+
projectTrusted: currentProjectTrusted(ctx),
|
|
4318
|
+
...(trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {}),
|
|
4213
4319
|
requiredExtensions,
|
|
4214
4320
|
childRuntime: deps.childRuntime,
|
|
4215
4321
|
onChildSession: (controls) => { childSessionControls = controls; },
|
|
@@ -4219,6 +4325,7 @@ projectTrusted: currentProjectTrusted(ctx),
|
|
|
4219
4325
|
cwd: singleCwd,
|
|
4220
4326
|
requestedCwd: data.requestedCwd,
|
|
4221
4327
|
signal,
|
|
4328
|
+
abortedAsStopped: params.workflowParentRunId !== undefined,
|
|
4222
4329
|
interruptSignal: interruptController.signal,
|
|
4223
4330
|
allowIntercomDetach: agentConfig.systemPrompt?.includes(INTERCOM_BRIDGE_MARKER) === true,
|
|
4224
4331
|
intercomEvents: deps.pi.events,
|
|
@@ -4294,7 +4401,7 @@ projectTrusted: currentProjectTrusted(ctx),
|
|
|
4294
4401
|
if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
|
|
4295
4402
|
} finally {
|
|
4296
4403
|
try {
|
|
4297
|
-
|
|
4404
|
+
finishTrackedForegroundChild();
|
|
4298
4405
|
} finally {
|
|
4299
4406
|
removeForegroundControlIfIdle(deps.state, runId, deps.trackRetainedNestedRoute);
|
|
4300
4407
|
}
|
|
@@ -4321,7 +4428,7 @@ projectTrusted: currentProjectTrusted(ctx),
|
|
|
4321
4428
|
// authoritative completion remains live.
|
|
4322
4429
|
if (!r?.detached) {
|
|
4323
4430
|
if (!artifactConfig.enabled) cleanupStructuredOutputRuntime(structuredRuntime);
|
|
4324
|
-
|
|
4431
|
+
finishTrackedForegroundChild();
|
|
4325
4432
|
}
|
|
4326
4433
|
}
|
|
4327
4434
|
if (!r.detached) {
|
|
@@ -4428,7 +4535,7 @@ projectTrusted: currentProjectTrusted(ctx),
|
|
|
4428
4535
|
}
|
|
4429
4536
|
|
|
4430
4537
|
function inferExecutionMode(params: SubagentParamsLike): Details["mode"] {
|
|
4431
|
-
if (params.workflowScript !== undefined) return "workflow";
|
|
4538
|
+
if (params.workflowScript !== undefined || params.workflow !== undefined) return "workflow";
|
|
4432
4539
|
if ((params.chain?.length ?? 0) > 0) return "chain";
|
|
4433
4540
|
if ((params.tasks?.length ?? 0) > 0) return "parallel";
|
|
4434
4541
|
return "single";
|
|
@@ -4529,16 +4636,19 @@ function workflowChildResult(
|
|
|
4529
4636
|
? result.details.results[0].finalOutput
|
|
4530
4637
|
: receiptOutput;
|
|
4531
4638
|
const childError = result.details.results.map((child) => child.error).find((error): error is string => Boolean(error));
|
|
4532
|
-
const
|
|
4533
|
-
|
|
4534
|
-
|
|
4639
|
+
const stopped = result.details.results.some((child) => child.stopped);
|
|
4640
|
+
// A stopped child's receipt text carries the run fan-out annotation; report the structured stop reason instead.
|
|
4641
|
+
const failureErrorBase = stopped && childError
|
|
4642
|
+
? childError
|
|
4643
|
+
: childError && receiptOutput
|
|
4644
|
+
? receiptOutput.includes(childError) ? receiptOutput : `${childError}\n\n${receiptOutput}`
|
|
4645
|
+
: childError || receiptOutput || output || "Child run failed.";
|
|
4535
4646
|
const savedOutputEvidence = [...new Set(result.details.results.map((child) => child.savedOutputPath).filter((value): value is string => Boolean(value)))]
|
|
4536
4647
|
.filter((savedOutputPath) => !failureErrorBase.includes(savedOutputPath))
|
|
4537
4648
|
.map((savedOutputPath) => `Saved output: ${savedOutputPath}`);
|
|
4538
4649
|
const failureError = [failureErrorBase, ...savedOutputEvidence].join("\n");
|
|
4539
4650
|
const detached = result.details.results.some((child) => child.detached);
|
|
4540
4651
|
const interrupted = result.details.results.some((child) => child.interrupted);
|
|
4541
|
-
const stopped = result.details.results.some((child) => child.stopped);
|
|
4542
4652
|
const terminalOutcome = forcedTerminalOutcome
|
|
4543
4653
|
?? (result.details.results.some((child) => child.timedOut)
|
|
4544
4654
|
? { state: "partial" as const, reason: "timeout" as const }
|
|
@@ -4634,9 +4744,9 @@ function workflowRunningChildrenSummary(children: WorkflowScriptChildResult[]):
|
|
|
4634
4744
|
}
|
|
4635
4745
|
|
|
4636
4746
|
function workflowResultChildren(children: WorkflowScriptChildResult[], status: AsyncStatus, includeFailureFields: boolean) {
|
|
4637
|
-
return children.map((child) => {
|
|
4747
|
+
return withWorkflowRevivals(DIRS.async, status.runId, children).map((child) => {
|
|
4638
4748
|
const sessionName = status.steps?.find((step) => step.workflowKey === child.key)?.sessionName;
|
|
4639
|
-
return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
|
|
4749
|
+
return { workflowKey: child.key, ...(child.agent ? { agent: child.agent } : {}), ...(child.runId ? { runId: child.runId } : {}), ...(child.revival ? { revival: formatWorkflowKeyRevival(child.revival) } : {}), ...(sessionName ? { sessionName } : {}), ...workflowChildAccountingFields(child), output: child.output, outputState: child.output.trim() || child.structuredOutput !== undefined ? "present" : "absent", structuredOutput: child.structuredOutput, ...(child.state === "running" ? { state: "running" } : { success: child.ok }), ...(child.asyncDir ? { asyncDir: child.asyncDir } : {}), ...(child.outputReference ? { outputReference: child.outputReference } : {}), ...(includeFailureFields && child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}), ...(child.outputPathMapping ? { outputPathMapping: child.outputPathMapping } : {}), ...(child.stopped ? { stopped: true } : {}), ...(child.interrupted ? { interrupted: true } : {}), ...(includeFailureFields && child.detached && status.state !== "complete" ? { detached: true } : {}), ...(child.outputArtifactPath || child.outputReference ? { artifactPaths: { outputPath: child.outputArtifactPath ?? child.outputReference } } : {}) };
|
|
4640
4750
|
});
|
|
4641
4751
|
}
|
|
4642
4752
|
|
|
@@ -4793,7 +4903,7 @@ function terminalWorkflowReceipt(
|
|
|
4793
4903
|
resource?: WorkflowReceipt["resource"],
|
|
4794
4904
|
argsDigest?: string,
|
|
4795
4905
|
): WorkflowReceipt {
|
|
4796
|
-
return buildWorkflowReceipt({ workflowRunId, state, children, workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
|
|
4906
|
+
return buildWorkflowReceipt({ workflowRunId, state, children: withWorkflowRevivals(DIRS.async, workflowRunId, children), workflowChildren, terminalOutcome, hostSteps, resource, ...(argsDigest ? { argsDigest } : {}) });
|
|
4797
4907
|
}
|
|
4798
4908
|
|
|
4799
4909
|
function workflowFailureTerminalOutcome(error: unknown, _children: WorkflowScriptChildResult[], usageBudget: ReturnType<typeof usageBudgetState>): WorkflowTerminalOutcome | undefined {
|
|
@@ -5221,6 +5331,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5221
5331
|
const workflowPermitContexts = new WeakMap<object, { root: WorkflowChildPermit } | { child: WorkflowChildPermitContext }>();
|
|
5222
5332
|
const warnedArtifactPackageDirs = new Set<string>();
|
|
5223
5333
|
const scheduledOwnerExecutors = new Map<string | null, Map<string, { state: SubagentState; executor: ReturnType<typeof createSubagentExecutor> }>>();
|
|
5334
|
+
const disabledFeatures = resolveDisabledFeatureSurface(deps.config);
|
|
5335
|
+
const disabledFeatureResult = (params: SubagentParamsLike): AgentToolResult<Details> | undefined => {
|
|
5336
|
+
const error = disabledFeatureUseError(params, disabledFeatures);
|
|
5337
|
+
if (!error) return undefined;
|
|
5338
|
+
return { content: [{ type: "text", text: error }], isError: true, details: { mode: params.action === undefined ? inferExecutionMode(params) : "management", results: [] } };
|
|
5339
|
+
};
|
|
5340
|
+
const admitEnabledWorkflowChildren = (calls: Array<{ key: string; params: Record<string, unknown> }>): void => {
|
|
5341
|
+
for (const call of calls) {
|
|
5342
|
+
const error = disabledFeatureUseError(call.params, disabledFeatures, `workflow child '${call.key}'`);
|
|
5343
|
+
if (error) throw new Error(error);
|
|
5344
|
+
}
|
|
5345
|
+
};
|
|
5224
5346
|
const execute = async (
|
|
5225
5347
|
_id: string,
|
|
5226
5348
|
params: SubagentParamsLike,
|
|
@@ -5250,18 +5372,25 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5250
5372
|
const capacityOverrideError = validateWorkflowCapacityOverrides(requestParams);
|
|
5251
5373
|
if (capacityOverrideError) return buildRequestedModeError(requestParams, capacityOverrideError);
|
|
5252
5374
|
let workflowPreflight: import("../../shared/types.ts").WorkflowPreflight | undefined;
|
|
5375
|
+
// Only workflow requests read the session here; other actions (for example doctor) must not.
|
|
5376
|
+
const resolveWorkflowParentModel = () => parentModelOverride !== undefined
|
|
5377
|
+
? parentModelOverride
|
|
5378
|
+
: (() => {
|
|
5379
|
+
const currentParentModel = normalizeParentModel(ctx.model);
|
|
5380
|
+
return (preserveActiveSession
|
|
5381
|
+
? currentParentModel
|
|
5382
|
+
: rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
|
|
5383
|
+
})();
|
|
5253
5384
|
try {
|
|
5254
|
-
if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined
|
|
5255
|
-
throw new Error("preflight requires
|
|
5385
|
+
if (requestParams.preflight !== undefined && requestParams.workflowScript === undefined) {
|
|
5386
|
+
throw new Error("preflight requires workflow: true or a workflow script path.");
|
|
5256
5387
|
}
|
|
5257
5388
|
workflowPreflight = normalizeWorkflowPreflight(requestParams.preflight);
|
|
5258
5389
|
if (workflowPreflight) requestParams = { ...requestParams, preflight: workflowPreflight };
|
|
5259
5390
|
} catch (error) {
|
|
5260
5391
|
const message = error instanceof Error ? error.message : String(error);
|
|
5261
5392
|
if (requestParams.action?.trim() === "validate") {
|
|
5262
|
-
const validation = validateWorkflowScript(requestParams.workflowScript ?? "",
|
|
5263
|
-
maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
|
|
5264
|
-
});
|
|
5393
|
+
const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
|
|
5265
5394
|
const invalidValidation = { ...validation, ok: false, errors: [...validation.errors, { message }] };
|
|
5266
5395
|
return {
|
|
5267
5396
|
content: [{ type: "text", text: JSON.stringify(invalidValidation) }],
|
|
@@ -5272,9 +5401,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5272
5401
|
return buildRequestedModeError(requestParams, message);
|
|
5273
5402
|
}
|
|
5274
5403
|
if (requestParams.action?.trim() === "validate") {
|
|
5275
|
-
const validation = validateWorkflowScript(requestParams.workflowScript ?? "",
|
|
5276
|
-
maxSubagentSpawnsPerRun: requestParams.maxSubagentSpawnsPerRun ?? resolveMaxSubagentSpawnsPerRun(deps.config.maxSubagentSpawnsPerRun),
|
|
5277
|
-
});
|
|
5404
|
+
const validation = validateWorkflowScript(requestParams.workflowScript ?? "", workflowValidationOptions(deps, requestParams, ctx.cwd, () => resolveWorkflowParentModel()?.provider));
|
|
5278
5405
|
return buildWorkflowValidationResult(validation, "management", workflowPreflight);
|
|
5279
5406
|
}
|
|
5280
5407
|
const normalizedAction = typeof requestParams.action === "string" ? requestParams.action.trim() : requestParams.action;
|
|
@@ -5290,15 +5417,18 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5290
5417
|
const workflowArgsEvidence = requestParams.args === undefined ? undefined : { args: requestParams.args, argsDigest: stableJsonDigest(requestParams.args) };
|
|
5291
5418
|
const workflowArgs = workflowArgsEvidence?.args;
|
|
5292
5419
|
const workflowArgsDigest = workflowArgsEvidence?.argsDigest;
|
|
5293
|
-
const
|
|
5294
|
-
|
|
5295
|
-
});
|
|
5420
|
+
const workflowParentModel = resolveWorkflowParentModel();
|
|
5421
|
+
const workflowValidation = validateWorkflowScript(requestParams.workflowScript, workflowValidationOptions(deps, requestParams, ctx.cwd, () => workflowParentModel?.provider));
|
|
5296
5422
|
if (!workflowValidation.ok && publicExecution) return buildWorkflowValidationResult(workflowValidation, "workflow", workflowPreflight);
|
|
5297
|
-
const
|
|
5298
|
-
if (
|
|
5299
|
-
return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${
|
|
5423
|
+
const launchBlockingErrors = workflowValidation.errors.filter((error) => error.kind === "spawn-budget" || error.kind === "agent");
|
|
5424
|
+
if (launchBlockingErrors.length > 0) {
|
|
5425
|
+
return buildRequestedModeError(requestParams, `Workflow '${_id}' validation failed before child launch; no children launched. ${launchBlockingErrors.map((error) => error.message).join(" ")}`);
|
|
5426
|
+
}
|
|
5427
|
+
// A package chain's per-step stop check defeats static launch counting; runtime fan-out enforcement still applies.
|
|
5428
|
+
const structuredResource = workflowResource?.provenance.name === "chain" || workflowResource?.provenance.name === "tasks";
|
|
5429
|
+
for (const warning of workflowValidation.warnings ?? []) {
|
|
5430
|
+
if (!(structuredResource && warning.kind === "dynamic-spawn-count")) console.warn(`[pi-subagents] ${warning.message}`);
|
|
5300
5431
|
}
|
|
5301
|
-
for (const warning of workflowValidation.warnings ?? []) console.warn(`[pi-subagents] ${warning.message}`);
|
|
5302
5432
|
const acceptanceErrors = validateAcceptanceInput(requestParams.acceptance);
|
|
5303
5433
|
if (acceptanceErrors.length > 0) return buildRequestedModeError(requestParams, acceptanceErrors.join(" "));
|
|
5304
5434
|
const foregroundWorkflowRunId = encodeIndexSegment(_id);
|
|
@@ -5307,14 +5437,6 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5307
5437
|
if (permitError) return buildRequestedModeError(requestParams, permitError);
|
|
5308
5438
|
if (requestParams.async !== false) return buildRequestedModeError(requestParams, "Workflow child permit supports foreground workflow roots only; set async:false.");
|
|
5309
5439
|
}
|
|
5310
|
-
const workflowParentModel = parentModelOverride !== undefined
|
|
5311
|
-
? parentModelOverride
|
|
5312
|
-
: (() => {
|
|
5313
|
-
const currentParentModel = normalizeParentModel(ctx.model);
|
|
5314
|
-
return (preserveActiveSession
|
|
5315
|
-
? currentParentModel
|
|
5316
|
-
: rememberParentModel(deps.state, resolveCurrentSessionId(ctx.sessionManager), currentParentModel)) ?? null;
|
|
5317
|
-
})();
|
|
5318
5440
|
if (requestParams.extensionBindings !== undefined) {
|
|
5319
5441
|
try {
|
|
5320
5442
|
requestParams.extensionBindings = normalizeExtensionBindings(requestParams.extensionBindings)!.value;
|
|
@@ -5323,6 +5445,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5323
5445
|
}
|
|
5324
5446
|
}
|
|
5325
5447
|
const parentCwd = ctx.cwd;
|
|
5448
|
+
for (const [name, value] of [["timeoutMs", requestParams.timeoutMs], ["maxRuntimeMs", requestParams.maxRuntimeMs]] as const) {
|
|
5449
|
+
if (value === undefined) continue;
|
|
5450
|
+
const overflowError = timerDelayOverflowError(name, value);
|
|
5451
|
+
if (overflowError) return buildRequestedModeError(requestParams, overflowError);
|
|
5452
|
+
}
|
|
5326
5453
|
const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : undefined);
|
|
5327
5454
|
const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
|
|
5328
5455
|
if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
|
|
@@ -5428,6 +5555,11 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5428
5555
|
const workflowCapabilityCeiling = intersectSubagentCapabilityCeilings(requestParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(currentSessionId));
|
|
5429
5556
|
const completionOwnerId = deps.state.completionOwnerId ?? currentCompletionOwnerId();
|
|
5430
5557
|
deps.state.completionOwnerId = completionOwnerId;
|
|
5558
|
+
const workflowScriptSourceDigest = workflowScriptDigest(requestParams.workflowScript);
|
|
5559
|
+
const workflowReuseSource = findWorkflowReuseSource(DIRS.async, currentSessionId, workflowScriptSourceDigest, workflowArgsDigest);
|
|
5560
|
+
const workflowRunEvidence: Pick<NonNullable<AsyncStatus["workflow"]>, "args" | "argsDigest" | "scriptDigest" | "reusedFrom" | "stopCause"> = { ...workflowArgsEvidence, scriptDigest: workflowScriptSourceDigest };
|
|
5561
|
+
if (workflowReuseSource) workflowRunEvidence.reusedFrom = workflowReuseSource.runId;
|
|
5562
|
+
const workflowJournalFingerprints = new Map<string, string>();
|
|
5431
5563
|
try {
|
|
5432
5564
|
fs.mkdirSync(asyncDir, { recursive: true });
|
|
5433
5565
|
writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
|
|
@@ -5459,7 +5591,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5459
5591
|
...(workflowCapabilityCeiling ? { admissionCapabilityCeiling: workflowCapabilityCeiling } : {}),
|
|
5460
5592
|
steps: [],
|
|
5461
5593
|
...(workflowPreflight ? { preflight: workflowPreflight } : {}),
|
|
5462
|
-
workflow: { trace: [], emits: [], console: [], ...
|
|
5594
|
+
workflow: { trace: [], emits: [], console: [], ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}) },
|
|
5463
5595
|
workflowChildren: workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "running", inventoryComplete: false }),
|
|
5464
5596
|
runFanoutBudget: getRunFanoutBudgetSnapshot(workflowFanoutBudget),
|
|
5465
5597
|
};
|
|
@@ -5951,6 +6083,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5951
6083
|
workflowSteps.set(entry.key, step);
|
|
5952
6084
|
}
|
|
5953
6085
|
const projectedStep = workflowSteps.get(entry.key);
|
|
6086
|
+
if (entry.reused && projectedStep) projectedStep.reused = true;
|
|
5954
6087
|
if (entry.state === "stopped" && projectedStep) {
|
|
5955
6088
|
appendWorkflowEvent({
|
|
5956
6089
|
type: "subagent.child-status",
|
|
@@ -5984,7 +6117,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5984
6117
|
timeoutMs: timeout,
|
|
5985
6118
|
signal: controller.signal,
|
|
5986
6119
|
continueAfterAbortWhenChildrenSettled: (abortError) => {
|
|
5987
|
-
if (abortError
|
|
6120
|
+
if (!workflowStopCause(abortError)) return false;
|
|
5988
6121
|
const activeAsyncChild = [...(deps.state.asyncJobs?.values() ?? [])].some((job) => job.parentWorkflowRunId === workflowRunId && (job.status === "queued" || job.status === "running"));
|
|
5989
6122
|
const activeForegroundChild = [...deps.state.foregroundControls.values()].some((control) => control.parentWorkflowRunId === workflowRunId && (control.activeChildren?.size ?? 0) > 0);
|
|
5990
6123
|
return !activeAsyncChild && !activeForegroundChild;
|
|
@@ -5996,6 +6129,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
5996
6129
|
...(workflowState ? { state: workflowState } : {}),
|
|
5997
6130
|
onTrace: updateTrace,
|
|
5998
6131
|
onChildSettled: (notification) => {
|
|
6132
|
+
const journalFingerprint = workflowJournalFingerprints.get(notification.childKey);
|
|
6133
|
+
if (journalFingerprint) appendWorkflowChildJournal(asyncDir, { type: "settle", key: notification.childKey, fingerprint: journalFingerprint, result: notification.result });
|
|
5999
6134
|
appendWorkflowEvent({
|
|
6000
6135
|
type: "subagent.workflow.child_settled",
|
|
6001
6136
|
childKey: notification.childKey,
|
|
@@ -6030,6 +6165,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6030
6165
|
} });
|
|
6031
6166
|
},
|
|
6032
6167
|
admit: async (calls, admissionSignal) => {
|
|
6168
|
+
admitEnabledWorkflowChildren(calls);
|
|
6033
6169
|
await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: parentCwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
|
|
6034
6170
|
const outputClaims = workflowChildOutputClaims({ ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
|
|
6035
6171
|
if (outputClaims.error) throw new Error(outputClaims.error);
|
|
@@ -6046,6 +6182,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6046
6182
|
appendWorkflowEvent({ type: "subagent.workflow.emit", value: emits.at(-1) });
|
|
6047
6183
|
},
|
|
6048
6184
|
launch: async (key, childParams, workflowSignal, admission) => {
|
|
6185
|
+
const journalFingerprint = workflowJournalFingerprints.get(key) ?? workflowChildFingerprint(childParams);
|
|
6186
|
+
workflowJournalFingerprints.set(key, journalFingerprint);
|
|
6187
|
+
const priorChild = workflowReuseSource ? matchWorkflowReuse(workflowReuseSource, key, journalFingerprint) : undefined;
|
|
6188
|
+
if (priorChild?.kind === "settled") {
|
|
6189
|
+
if (priorChild.result.runId) workflowChildRunIds.set(key, priorChild.result.runId);
|
|
6190
|
+
return { ...priorChild.result, reused: true };
|
|
6191
|
+
}
|
|
6192
|
+
if (priorChild?.kind === "started") {
|
|
6193
|
+
// The previous run's awaited async child may still be running: wait for that exact run
|
|
6194
|
+
// instead of launching again. Journal it first so another reload can re-attach too.
|
|
6195
|
+
const priorRunId = priorChild.runId;
|
|
6196
|
+
const priorAsyncDir = path.join(DIRS.async, priorRunId);
|
|
6197
|
+
appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: priorRunId });
|
|
6198
|
+
const stopListener = stopAwaitedAsyncChildOnAbort(workflowSignal, deps.state, priorRunId, priorAsyncDir, deps.kill);
|
|
6199
|
+
const reattached = await awaitExistingAsyncRun(priorAsyncDir, priorRunId, workflowSignal).finally(stopListener.remove);
|
|
6200
|
+
const claimedPath = reattached.status === "settled" ? claimWorkflowAwaitedResult(priorAsyncDir, workflowRunId) : undefined;
|
|
6201
|
+
if (reattached.status === "settled" && claimedPath) {
|
|
6202
|
+
const imported = importWorkflowAwaitedChildResult(reattached.result, { runId: priorRunId, asyncDir: priorAsyncDir, resultPath: claimedPath, task: typeof childParams.task === "string" ? childParams.task : "", parentWorkflowRunId: workflowReuseSource?.runId, details: { mode: "single", asyncId: priorRunId, asyncDir: priorAsyncDir, results: [] }, state: deps.state, pi: deps.pi });
|
|
6203
|
+
const reattachedResult = workflowChildResult(key, imported, childParams, deps.state);
|
|
6204
|
+
// Like a settled journal match: only a successful child is reused; a failed or stopped one launches fresh.
|
|
6205
|
+
if (reattachedResult.ok) {
|
|
6206
|
+
workflowChildRunIds.set(key, priorRunId);
|
|
6207
|
+
return { ...reattachedResult, reused: true };
|
|
6208
|
+
}
|
|
6209
|
+
}
|
|
6210
|
+
}
|
|
6049
6211
|
if (workflowUsageBudget.budget && childParams.async === true) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, "workflow usageBudget does not support async runs.run launches."), childParams, deps.state);
|
|
6050
6212
|
const budgetState = usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults));
|
|
6051
6213
|
if (budgetState?.exhausted) return workflowChildResult(key, buildRequestedModeError(childParams as SubagentParamsLike, usageBudgetExceededMessage(budgetState)), childParams, deps.state, { state: "partial", reason: "budget_exhausted" });
|
|
@@ -6070,6 +6232,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6070
6232
|
preparedChildParams = childRequest;
|
|
6071
6233
|
if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
|
|
6072
6234
|
workflowLaunchObservers.set(childRequest, (launch) => {
|
|
6235
|
+
if (launch.runId) appendWorkflowChildJournal(asyncDir, { type: "start", key, fingerprint: journalFingerprint, runId: launch.runId });
|
|
6073
6236
|
const step = status.steps?.find((candidate) => candidate.workflowKey === key);
|
|
6074
6237
|
if (step) {
|
|
6075
6238
|
step.agent = launch.agent;
|
|
@@ -6145,16 +6308,19 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6145
6308
|
});
|
|
6146
6309
|
const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, workflow.trace, { settled: true });
|
|
6147
6310
|
const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
|
|
6148
|
-
const
|
|
6149
|
-
const
|
|
6311
|
+
const returnText = formatWorkflowValue(workflow.value);
|
|
6312
|
+
const emitText = workflow.emits.map(formatWorkflowValue).join(", ");
|
|
6313
|
+
const returnPreview = returnText.length > 1_000 ? `${returnText.slice(0, 1_000)}…` : returnText;
|
|
6314
|
+
const emitPreview = workflow.emits.length > 0 ? ` Emitted: ${emitText.length > 1_000 ? `${emitText.slice(0, 1_000)}…` : emitText}` : "";
|
|
6315
|
+
const previewNote = returnText.length > 1_000 || emitText.length > 1_000 ? ` (truncated; full return value and emits: ${statusPath} (workflow.value, workflow.emits))` : "";
|
|
6150
6316
|
const runningSummary = workflowRunningChildrenSummary(workflow.children);
|
|
6151
|
-
const summary = `${runningSummary ? `Workflow dispatch completed; ${runningSummary}` : `Workflow completed with ${workflow.children.length} child run(s).`} Return: ${returnPreview}${emitPreview} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
|
|
6317
|
+
const summary = `${runningSummary ? `Workflow dispatch completed; ${runningSummary}` : `Workflow completed with ${workflow.children.length} child run(s).`} Return: ${returnPreview}${emitPreview}${previewNote} Trace: ${workflow.trace.length} event(s).${workflowOutputPathMappingSummary(workflow.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
|
|
6152
6318
|
const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, summary, producedChildOutputPaths);
|
|
6153
6319
|
const resultSummary = appendWorkflowOutputWarning(summary, outputWarning);
|
|
6154
6320
|
const workflowUsage = sumResultsUsage(workflowResults);
|
|
6155
6321
|
settleWorkflowSteerInbox("complete");
|
|
6156
6322
|
const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children, steps: status.steps });
|
|
6157
|
-
status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...
|
|
6323
|
+
status = { ...status, state: "complete", endedAt: Date.now(), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren, totalTokens: { input: workflowUsage.input, output: workflowUsage.output, total: workflowUsage.input + workflowUsage.output }, totalCost: sumResultsCost(workflowResults) };
|
|
6158
6324
|
const receipt = terminalWorkflowReceipt(workflowRunId, "complete", workflow.children, workflowChildren, undefined, validHostStepNodes(status.workflowGraph), workflowResource?.provenance, workflowArgsDigest);
|
|
6159
6325
|
delete status.workflowReceiptPath;
|
|
6160
6326
|
let workflowReceipt: { path: string; receipt: WorkflowReceipt } | undefined;
|
|
@@ -6173,6 +6339,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6173
6339
|
} catch (error) {
|
|
6174
6340
|
const partial = error instanceof WorkflowScriptError ? error.partial : { trace: [], emits: [], console: [], children: [] };
|
|
6175
6341
|
const stopped = controller.signal.aborted;
|
|
6342
|
+
const stopCause = stopped ? workflowStopCause(controller.signal.reason) : undefined;
|
|
6343
|
+
if (stopCause) workflowRunEvidence.stopCause = stopCause;
|
|
6176
6344
|
const detachedChildKeys = new Set(partial.children.filter((child) => child.detached).map((child) => child.key));
|
|
6177
6345
|
const hasRealFailedChild = partial.children.some((child) => !child.ok && child.state !== "running" && !child.detached);
|
|
6178
6346
|
const pauseForDetached = !stopped && error instanceof WorkflowScriptError && error.errorKind === "detached-child" && detachedChildKeys.size > 0 && !hasRealFailedChild;
|
|
@@ -6193,14 +6361,16 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6193
6361
|
const workflowChildren = workflowChildSummary({ parentToolCallId: toolCallId, workflowRunId, workflowState, inventoryComplete: true, trace: partial.trace, children: partial.children, steps: status.steps });
|
|
6194
6362
|
const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
|
|
6195
6363
|
const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
|
|
6196
|
-
status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached || status.activityState === "needs_attention" ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(
|
|
6364
|
+
status = compactOptional<AsyncStatus>({ ...status, state, stopped: stopped || undefined, activityState: pauseForDetached || status.activityState === "needs_attention" ? "needs_attention" : undefined, error: workflowFailureMessage(error, workflowRunId, partial.children), endedAt: Date.now(), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(error instanceof WorkflowScriptError && error.errorKind ? { failureKind: error.errorKind } : {}), ...workflowRunEvidence, ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}) }, workflowChildren });
|
|
6197
6365
|
if (pauseForDetached) {
|
|
6198
6366
|
const promoted = promotePausedWorkflowIfSettled(status);
|
|
6199
6367
|
if (promoted) status = promoted;
|
|
6200
6368
|
}
|
|
6369
|
+
// A script can throw an error of any size; status.json keeps the full text.
|
|
6370
|
+
const errorPreview = status.error && status.error.length > 1_000 ? `${status.error.slice(0, 1_000)}… (truncated; full error: ${statusPath} (error))` : status.error;
|
|
6201
6371
|
const terminalSummary = `${status.state === "complete"
|
|
6202
6372
|
? "Workflow completed after detached child finished."
|
|
6203
|
-
:
|
|
6373
|
+
: errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
|
|
6204
6374
|
const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
|
|
6205
6375
|
const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
|
|
6206
6376
|
const receiptState: WorkflowReceiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
|
|
@@ -6243,6 +6413,9 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6243
6413
|
const workflowOutput = typeof workflowChildDefaults.output === "string" || typeof workflowChildDefaults.output === "boolean" ? workflowChildDefaults.output : undefined;
|
|
6244
6414
|
const configuredOutputBaseDir = resolveConfiguredSingleRunOutputBaseDir(deps);
|
|
6245
6415
|
const workflowAggregateOutputPath = resolveSingleOutputPath(workflowOutput, ctx.cwd, workflowCwd, resolveSingleRunOutputBaseDir(deps, workflowArtifactsDir, foregroundWorkflowRunId));
|
|
6416
|
+
// A top-level artifact file: outside outputs/, where children save their reports, and
|
|
6417
|
+
// within artifact retention, which only removes top-level files.
|
|
6418
|
+
const workflowFullResultPath = path.join(workflowArtifactsDir, `${sanitizeRunPathSegment(foregroundWorkflowRunId)}_workflow-result.md`);
|
|
6246
6419
|
const claimedOutputPaths = new Map<string, string>();
|
|
6247
6420
|
const childOutputOverrides = new Map<string, string>();
|
|
6248
6421
|
const childOutputClaimPaths = new Map<string, string>();
|
|
@@ -6303,6 +6476,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6303
6476
|
sendWorkflowProgress();
|
|
6304
6477
|
},
|
|
6305
6478
|
admit: async (calls, admissionSignal) => {
|
|
6479
|
+
admitEnabledWorkflowChildren(calls);
|
|
6306
6480
|
await preflightWorkflowWorktrees({ workflowDefaults: workflowChildDefaults, defaultWorktree: deps.config.worktree, calls, ctxCwd: ctx.cwd, signal: admissionSignal, deadlineAt: workflowDeadlineAt });
|
|
6307
6481
|
const outputClaims = workflowChildOutputClaims({ ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, workflowRunId: foregroundWorkflowRunId, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, state: deps.state, claimedOutputPaths, entries: calls });
|
|
6308
6482
|
if (outputClaims.error) throw new Error(outputClaims.error);
|
|
@@ -6402,22 +6576,26 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6402
6576
|
const finalPreflightTrace = annotateWorkflowPreflightTrace(workflow.trace, workflowPreflight);
|
|
6403
6577
|
const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "completed", inventoryComplete: true, trace: workflow.trace, children: workflow.children });
|
|
6404
6578
|
const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "complete", workflow.children, workflowChildren, undefined, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
|
|
6405
|
-
const
|
|
6579
|
+
const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.durationMs !== undefined ? ` in ${entry.durationMs}ms` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
|
|
6406
6580
|
const runningSummary = workflowRunningChildrenSummary(workflow.children);
|
|
6407
|
-
const sections = [
|
|
6408
|
-
...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
|
|
6409
|
-
runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed.",
|
|
6410
|
-
`Return:\n${formatWorkflowValue(workflow.value)}`,
|
|
6411
|
-
];
|
|
6412
|
-
if (workflow.emits.length > 0) sections.push(`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`);
|
|
6413
|
-
if (workflow.console.length > 0) sections.push(`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
|
|
6414
|
-
if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
|
|
6415
|
-
if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
|
|
6416
6581
|
const outputMappings = workflowOutputPathMappingSummary(workflow.children).trim();
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
6582
|
+
const displayText = formatWorkflowResultText({
|
|
6583
|
+
head: [...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []), runningSummary ? `Workflow dispatch completed; ${runningSummary}` : "Workflow completed."],
|
|
6584
|
+
script: [
|
|
6585
|
+
`Return:\n${formatWorkflowValue(workflow.value)}`,
|
|
6586
|
+
...(workflow.emits.length > 0 ? [`Emitted:\n${workflow.emits.map(formatWorkflowValue).join("\n")}`] : []),
|
|
6587
|
+
...(workflow.console.length > 0 ? [`Console:\n${workflow.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
|
|
6588
|
+
],
|
|
6589
|
+
trace,
|
|
6590
|
+
tail: [
|
|
6591
|
+
...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
|
|
6592
|
+
...(outputMappings ? [outputMappings] : []),
|
|
6593
|
+
],
|
|
6594
|
+
maxOutput: requestParams.maxOutput,
|
|
6595
|
+
aggregateOutputPath: workflowAggregateOutputPath,
|
|
6596
|
+
fullResultPath: workflowFullResultPath,
|
|
6597
|
+
producedChildOutputPaths,
|
|
6598
|
+
});
|
|
6421
6599
|
return attachWorkflowMission(withRunFanoutBudget({
|
|
6422
6600
|
content: [{ type: "text", text: displayText }],
|
|
6423
6601
|
details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(workflow.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { value: workflow.value, trace: finalPreflightTrace, emits: workflow.emits, console: workflow.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
|
|
@@ -6427,27 +6605,32 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6427
6605
|
const text = workflowFailureMessage(error, foregroundWorkflowRunId, partial.children);
|
|
6428
6606
|
const finalPreflightWarnings = workflowPreflightWarnings(workflowPreflight, partial.trace, { settled: true });
|
|
6429
6607
|
const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
|
|
6430
|
-
const
|
|
6431
|
-
const sections = [
|
|
6432
|
-
...(workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : []),
|
|
6433
|
-
`Workflow failed: ${text}`,
|
|
6434
|
-
];
|
|
6435
|
-
if (partial.emits.length > 0) sections.push(`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`);
|
|
6436
|
-
if (partial.console.length > 0) sections.push(`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`);
|
|
6437
|
-
if (traceLines.length > 0) sections.push(`Call trace:\n${traceLines.join("\n")}`);
|
|
6438
|
-
if (finalPreflightWarnings.length > 0) sections.push(formatWorkflowPreflightWarnings(finalPreflightWarnings));
|
|
6608
|
+
const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
|
|
6439
6609
|
const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
|
|
6440
|
-
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6610
|
+
const displayText = formatWorkflowResultText({
|
|
6611
|
+
head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
|
|
6612
|
+
script: [
|
|
6613
|
+
`Workflow failed: ${text}`,
|
|
6614
|
+
...(partial.emits.length > 0 ? [`Emitted:\n${partial.emits.map(formatWorkflowValue).join("\n")}`] : []),
|
|
6615
|
+
...(partial.console.length > 0 ? [`Console:\n${partial.console.map((entry) => `[${entry.level}] ${entry.text}`).join("\n")}`] : []),
|
|
6616
|
+
],
|
|
6617
|
+
trace,
|
|
6618
|
+
tail: [
|
|
6619
|
+
...(finalPreflightWarnings.length > 0 ? [formatWorkflowPreflightWarnings(finalPreflightWarnings)] : []),
|
|
6620
|
+
...(outputMappings ? [outputMappings] : []),
|
|
6621
|
+
],
|
|
6622
|
+
maxOutput: requestParams.maxOutput,
|
|
6623
|
+
aggregateOutputPath: workflowAggregateOutputPath,
|
|
6624
|
+
fullResultPath: workflowFullResultPath,
|
|
6625
|
+
producedChildOutputPaths,
|
|
6626
|
+
});
|
|
6444
6627
|
const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
|
|
6445
6628
|
const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
|
|
6446
6629
|
const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
|
|
6447
6630
|
return attachWorkflowMission(withRunFanoutBudget({
|
|
6448
6631
|
content: [{ type: "text", text: displayText }],
|
|
6449
6632
|
isError: true,
|
|
6450
|
-
details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
|
|
6633
|
+
details: compactOptional<Details>({ mode: "workflow", runId: foregroundWorkflowRunId, results: workflowDetailsResults(partial.children), ...(workflowPreflight ? { preflight: workflowPreflight } : {}), workflowChildren, totalChildUsage: sumResultsUsage(workflowResults), totalCost: sumResultsCost(workflowResults), usageBudget: usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)), workflow: { trace: finalPreflightTrace, emits: partial.emits, console: partial.console, ...(error instanceof WorkflowScriptError && error.errorKind ? { failureKind: error.errorKind } : {}), ...(workflowArgsEvidence ?? {}), ...(workflowResource ? { resource: workflowResource.provenance } : {}), ...(finalPreflightWarnings.length ? { preflightWarnings: finalPreflightWarnings } : {}), receipt }, chatProgress }),
|
|
6451
6634
|
}, workflowFanoutBudget));
|
|
6452
6635
|
} finally {
|
|
6453
6636
|
workflowProgressClosed = true;
|
|
@@ -6733,8 +6916,10 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6733
6916
|
}
|
|
6734
6917
|
if (action === "guide") {
|
|
6735
6918
|
try {
|
|
6919
|
+
const guide = readSubagentGuide(paramsWithResolvedCwd.topic);
|
|
6920
|
+
const notice = paramsWithResolvedCwd.topic === "tool-reference" ? disabledFeatureNotice(disabledFeatures) : undefined;
|
|
6736
6921
|
return {
|
|
6737
|
-
content: [{ type: "text", text:
|
|
6922
|
+
content: [{ type: "text", text: notice ? `${notice}\n\n${guide}` : guide }],
|
|
6738
6923
|
details: { mode: "management", results: [] },
|
|
6739
6924
|
};
|
|
6740
6925
|
} catch (error) {
|
|
@@ -6951,7 +7136,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6951
7136
|
}
|
|
6952
7137
|
if (action.startsWith("schedule.")) {
|
|
6953
7138
|
if (!isScheduledRunAction(action)) {
|
|
6954
|
-
return { content: [{ type: "text", text: unknownSubagentActionMessage(action) }], isError: true, details: { mode: "management", results: [] } };
|
|
7139
|
+
return { content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }], isError: true, details: { mode: "management", results: [] } };
|
|
6955
7140
|
}
|
|
6956
7141
|
if (deps.allowMutatingManagementActions === false && MUTATING_MANAGEMENT_ACTIONS.has(action)) {
|
|
6957
7142
|
return {
|
|
@@ -6993,47 +7178,40 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
6993
7178
|
}
|
|
6994
7179
|
if (action === "stop") {
|
|
6995
7180
|
const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
|
|
6996
|
-
|
|
6997
|
-
|
|
6998
|
-
|
|
6999
|
-
|
|
7000
|
-
|
|
7001
|
-
|
|
7002
|
-
|
|
7003
|
-
|
|
7004
|
-
|
|
7005
|
-
|
|
7006
|
-
|
|
7007
|
-
|
|
7008
|
-
|
|
7009
|
-
|
|
7010
|
-
|
|
7011
|
-
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
|
|
7015
|
-
|
|
7016
|
-
|
|
7017
|
-
|
|
7018
|
-
|
|
7019
|
-
|
|
7020
|
-
|
|
7021
|
-
|
|
7022
|
-
|
|
7023
|
-
|
|
7024
|
-
|
|
7025
|
-
|
|
7026
|
-
|
|
7027
|
-
}
|
|
7028
|
-
console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
|
|
7029
|
-
}
|
|
7030
|
-
return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
|
|
7181
|
+
// Whole-workflow stops reach stopAsyncRun below, which stops a live workflow in-process.
|
|
7182
|
+
const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== undefined ? resolveLiveWorkflowRunId(deps, targetRunId) : undefined;
|
|
7183
|
+
if (workflowRunId && paramsWithResolvedCwd.childId !== undefined) {
|
|
7184
|
+
const stopChild = deps.state.workflowChildStops?.get(workflowRunId);
|
|
7185
|
+
const asyncJob = deps.state.asyncJobs.get(workflowRunId);
|
|
7186
|
+
if (!asyncJob?.asyncDir) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
|
|
7187
|
+
const status = readStatus(asyncJob.asyncDir);
|
|
7188
|
+
if (!status) return { content: [{ type: "text", text: `Status file not found for async workflow '${workflowRunId}'.` }], isError: true, details: { mode: "management", results: [] } };
|
|
7189
|
+
const resolution = resolveAsyncStatusChild(status, paramsWithResolvedCwd.childId);
|
|
7190
|
+
if (!resolution.ok) return { content: [{ type: "text", text: resolution.message }], isError: true, details: { mode: "management", results: [] } };
|
|
7191
|
+
if (!isStoppableAsyncStatusStep(resolution.child.step)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in async run '${workflowRunId}' is ${resolution.child.step.status}; stop only supports pending or running children.` }], isError: true, details: { mode: "management", results: [] } };
|
|
7192
|
+
if (!stopChild) return { content: [{ type: "text", text: `Workflow ${workflowRunId} child stop is unavailable in this extension runtime.` }], isError: true, details: { mode: "management", results: [] } };
|
|
7193
|
+
if (!stopChild(resolution.child.id, `Workflow child '${resolution.child.id}' stopped.`)) return { content: [{ type: "text", text: `Child '${paramsWithResolvedCwd.childId}' in workflow ${workflowRunId} is not available to stop.` }], isError: true, details: { mode: "management", results: [] } };
|
|
7194
|
+
try {
|
|
7195
|
+
fs.appendFileSync(path.join(asyncJob.asyncDir, "events.jsonl"), `${JSON.stringify({
|
|
7196
|
+
type: "subagent.child-status",
|
|
7197
|
+
version: 1,
|
|
7198
|
+
runId: workflowRunId,
|
|
7199
|
+
childId: resolution.child.id,
|
|
7200
|
+
status: "stopping",
|
|
7201
|
+
ts: Date.now(),
|
|
7202
|
+
reason: "subagent-action",
|
|
7203
|
+
source: "async",
|
|
7204
|
+
stepIndex: resolution.child.index,
|
|
7205
|
+
agent: resolution.child.step.agent,
|
|
7206
|
+
...(resolution.child.step.runId ? { childRunId: resolution.child.step.runId } : {}),
|
|
7207
|
+
...(resolution.child.step.workflowKey ? { workflowKey: resolution.child.step.workflowKey } : {}),
|
|
7208
|
+
...(resolution.child.step.phase ? { phase: resolution.child.step.phase } : {}),
|
|
7209
|
+
...(resolution.child.step.label ? { label: resolution.child.step.label } : {}),
|
|
7210
|
+
} satisfies SubagentChildStatusEvent)}\n`, "utf-8");
|
|
7211
|
+
} catch (error) {
|
|
7212
|
+
console.error(`Failed to append child status event for workflow ${workflowRunId}:`, error);
|
|
7031
7213
|
}
|
|
7032
|
-
|
|
7033
|
-
const status = asyncJob?.asyncDir ? readStatus(asyncJob.asyncDir) : undefined;
|
|
7034
|
-
if (status) stopStoppableAsyncStatusChildren(status, stopChild, "Workflow stopped.");
|
|
7035
|
-
workflowController.abort(new Error("Workflow stopped."));
|
|
7036
|
-
return { content: [{ type: "text", text: `Stop requested for async workflow ${targetRunId}.` }], details: { mode: "management", results: [] } };
|
|
7214
|
+
return { content: [{ type: "text", text: `Stop requested for child ${resolution.child.id} in async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
|
|
7037
7215
|
}
|
|
7038
7216
|
let resolved: ResolvedSubagentRunId | undefined;
|
|
7039
7217
|
if (paramsWithResolvedCwd.dir) {
|
|
@@ -7113,7 +7291,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7113
7291
|
}
|
|
7114
7292
|
if (!(SUBAGENT_ACTIONS as readonly string[]).includes(action)) {
|
|
7115
7293
|
return {
|
|
7116
|
-
content: [{ type: "text", text: unknownSubagentActionMessage(action) }],
|
|
7294
|
+
content: [{ type: "text", text: unknownSubagentActionMessage(action, disabledFeatures) }],
|
|
7117
7295
|
isError: true,
|
|
7118
7296
|
details: { mode: "management" as const, results: [] },
|
|
7119
7297
|
};
|
|
@@ -7513,6 +7691,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7513
7691
|
contextPolicy,
|
|
7514
7692
|
modelScope,
|
|
7515
7693
|
parentModel: requestParentModel,
|
|
7694
|
+
scopedModelIds: scopedModelIdsFromContext(ctx),
|
|
7516
7695
|
parentSessionId: requestSessionId,
|
|
7517
7696
|
parentPiSessionId: requestPiSessionId,
|
|
7518
7697
|
capabilityCeiling: intersectSubagentCapabilityCeilings(effectiveParams.capabilityCeiling, resolveCurrentSubagentCapabilityCeiling(requestSessionId)),
|
|
@@ -7604,6 +7783,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7604
7783
|
params: effectiveParams,
|
|
7605
7784
|
agents,
|
|
7606
7785
|
parentModel: requestParentModel,
|
|
7786
|
+
scopedModelIds: scopedModelIdsFromContext(ctx),
|
|
7607
7787
|
availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
|
|
7608
7788
|
currentProvider: requestParentModel?.provider,
|
|
7609
7789
|
modelScope,
|
|
@@ -7641,7 +7821,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7641
7821
|
agents: agentsForSummary,
|
|
7642
7822
|
...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model) ? { model: type === "subagent.nested.started" ? startedLaunches[0]?.model : details?.results[0]?.model } : {}),
|
|
7643
7823
|
...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking) ? { thinking: type === "subagent.nested.started" ? startedLaunches[0]?.thinking : details?.results[0]?.thinking } : {}),
|
|
7644
|
-
...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
|
|
7824
|
+
...(agentsForSummary.length === 1 && (type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox) ? { sandbox: type === "subagent.nested.started" ? startedLaunches[0]?.sandbox : details?.results[0]?.sandbox } : {}),
|
|
7645
7825
|
startedAt: foregroundControl?.startedAt ?? now,
|
|
7646
7826
|
...(state !== "running" ? { endedAt: now } : {}),
|
|
7647
7827
|
lastUpdate: now,
|
|
@@ -7653,7 +7833,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7653
7833
|
status: "running" as const,
|
|
7654
7834
|
...(launch.model ? { model: launch.model } : {}),
|
|
7655
7835
|
...(launch.thinking ? { thinking: launch.thinking } : {}),
|
|
7656
|
-
...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
|
|
7836
|
+
...(launch.sandbox ? { sandbox: launch.sandbox } : {}),
|
|
7657
7837
|
})) }
|
|
7658
7838
|
: details?.results.length
|
|
7659
7839
|
? { steps: details.results.map((child) => ({
|
|
@@ -7662,7 +7842,7 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7662
7842
|
status: child.interrupted || child.detached ? "paused" as const : child.exitCode === 0 ? "complete" as const : "failed" as const,
|
|
7663
7843
|
...(child.model ? { model: child.model } : {}),
|
|
7664
7844
|
...(child.thinking ? { thinking: child.thinking } : {}),
|
|
7665
|
-
...(child.sandbox ? { sandbox: child.sandbox } : {}),
|
|
7845
|
+
...(child.sandbox ? { sandbox: child.sandbox } : {}),
|
|
7666
7846
|
...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
|
|
7667
7847
|
...(child.error ? { error: child.error } : {}),
|
|
7668
7848
|
})) }
|
|
@@ -7764,28 +7944,45 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7764
7944
|
onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
|
|
7765
7945
|
ctx: ExtensionContext,
|
|
7766
7946
|
): Promise<AgentToolResult<Details>> => {
|
|
7767
|
-
const
|
|
7947
|
+
const disabledFeatureError = disabledFeatureResult(params);
|
|
7948
|
+
if (disabledFeatureError) return Promise.resolve(disabledFeatureError);
|
|
7949
|
+
const normalized = normalizePublicSubagentExecution(params, { structuredWorkflows: disabledFeatures.features.has("workflow-scripts") });
|
|
7768
7950
|
if (!normalized.ok) {
|
|
7769
7951
|
return Promise.resolve({ content: [{ type: "text", text: normalized.error }], isError: true, details: { mode: normalized.mode, results: [] } });
|
|
7770
7952
|
}
|
|
7771
7953
|
let publicParams = normalized.params as SubagentParamsLike;
|
|
7772
|
-
|
|
7773
|
-
|
|
7774
|
-
|
|
7954
|
+
const workflow = publicParams.workflow;
|
|
7955
|
+
const errorResult = (text: string): Promise<AgentToolResult<Details>> => Promise.resolve({ content: [{ type: "text", text }], isError: true, details: { mode: publicParams.action ? "management" : "workflow", results: [] } });
|
|
7956
|
+
// Models tend to put script text in the workflow string; say how to pass it instead.
|
|
7957
|
+
const scriptTextHint = " A workflow string is a named workflow resource or a script file path. To run script text, write it in one ```js workflow block in the same reply and call subagent({ workflow: true }).";
|
|
7958
|
+
if (publicParams.tasks !== undefined || publicParams.chain !== undefined) {
|
|
7959
|
+
// Normalization admits chain/tasks only with workflow scripts disabled; the original input was checked above.
|
|
7960
|
+
const kind = publicParams.tasks !== undefined ? "tasks" : "chain";
|
|
7961
|
+
const resolved = resolveStructuredWorkflowResource({ kind, steps: publicParams[kind], task: publicParams.task });
|
|
7962
|
+
if (!resolved.ok) return errorResult(resolved.error);
|
|
7963
|
+
const { tasks: _tasks, chain: _chain, task: _task, ...withoutStructuredInput } = publicParams;
|
|
7964
|
+
publicParams = { ...withoutStructuredInput, workflowScript: resolved.resource.script };
|
|
7965
|
+
workflowResourcePermits.set(publicParams, resolved.resource.permit);
|
|
7966
|
+
} else if (typeof workflow === "string" && !isWorkflowScriptPath(workflow)) {
|
|
7967
|
+
const resolved = resolveWorkflowResource(workflow, publicParams.args, ctx.sessionManager.getSessionId() ?? undefined);
|
|
7968
|
+
if (!resolved.ok) return Promise.resolve({ content: [{ type: "text", text: resolved.error + scriptTextHint }], isError: true, details: { mode: "workflow", results: [] } });
|
|
7775
7969
|
const { workflow: _workflow, args: _args, ...withoutResourceInput } = publicParams;
|
|
7776
7970
|
publicParams = { ...withoutResourceInput, workflowScript: resolved.resource.script };
|
|
7777
7971
|
workflowResourcePermits.set(publicParams, resolved.resource.permit);
|
|
7778
|
-
} else if (
|
|
7972
|
+
} else if (workflow !== undefined || publicParams.workflowScript !== undefined) {
|
|
7779
7973
|
const normalizedArgs = normalizeWorkflowArgs(publicParams.args);
|
|
7780
|
-
if ("error" in normalizedArgs) return
|
|
7781
|
-
|
|
7782
|
-
|
|
7783
|
-
|
|
7784
|
-
|
|
7785
|
-
|
|
7974
|
+
if ("error" in normalizedArgs) return errorResult(normalizedArgs.error);
|
|
7975
|
+
let workflowScript = publicParams.workflowScript;
|
|
7976
|
+
if (workflow !== undefined) {
|
|
7977
|
+
const source = workflow === true ? readReplyWorkflowScript(ctx.sessionManager, id) : readWorkflowScriptFile(workflow, publicParams.cwd, ctx.cwd);
|
|
7978
|
+
if ("error" in source) return errorResult(workflow === true ? source.error : source.error + scriptTextHint);
|
|
7979
|
+
workflowScript = source.script;
|
|
7980
|
+
}
|
|
7981
|
+
const { workflow: _workflow, ...withoutWorkflowSource } = publicParams;
|
|
7982
|
+
publicParams = { ...withoutWorkflowSource, workflowScript, args: deepFreezeWorkflowArgs(normalizedArgs.args) };
|
|
7786
7983
|
}
|
|
7787
|
-
publicExecutions.add(
|
|
7788
|
-
return executeWithSingleDispatchGuard(id,
|
|
7984
|
+
publicExecutions.add(publicParams);
|
|
7985
|
+
return executeWithSingleDispatchGuard(id, publicParams, signal, onUpdate, ctx);
|
|
7789
7986
|
};
|
|
7790
7987
|
|
|
7791
7988
|
const executeDelegated = async (
|
|
@@ -7795,6 +7992,8 @@ export function createSubagentExecutor(deps: ExecutorDeps): {
|
|
|
7795
7992
|
onUpdate: ((r: AgentToolResult<Details>) => void) | undefined,
|
|
7796
7993
|
ctx: ExtensionContext,
|
|
7797
7994
|
): Promise<AgentToolResult<Details>> => {
|
|
7995
|
+
const disabledFeatureError = disabledFeatureResult(params);
|
|
7996
|
+
if (disabledFeatureError) return disabledFeatureError;
|
|
7798
7997
|
const delegatedParams = { ...params };
|
|
7799
7998
|
const privateParams = delegatedParams as SubagentParamsLike & {
|
|
7800
7999
|
delegatedThinkingOverride?: AgentConfig["thinking"];
|