@xzzpig/pi-subagents 0.8.0 → 0.10.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 +477 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +195 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +384 -115
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +14 -2
- package/src/agents/agents.ts +935 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +42 -21
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +77 -21
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +65 -29
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +7 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +417 -133
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +60 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +204 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +718 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +489 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1223 -402
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +364 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +366 -0
- package/src/runs/shared/child-tool-plan.ts +632 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +146 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +99 -77
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +20 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/sandbox-profile-guard.ts +85 -0
- package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +11 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/sandbox-profile.ts +23 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +545 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
4
4
|
import { safeTerminalText } from "../../shared/display-text.ts";
|
|
5
|
-
import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns } from "./async-status.ts";
|
|
5
|
+
import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, formatWorkflowStageLine, listAsyncRuns } from "./async-status.ts";
|
|
6
6
|
import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.ts";
|
|
7
7
|
import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
|
|
8
8
|
import { formatModelThinking } from "../../shared/formatters.ts";
|
|
@@ -11,6 +11,7 @@ import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type Ne
|
|
|
11
11
|
import { inspectActiveAsyncCapacityOwner, type ActiveAsyncCapacityInspection } from "./active-async-capacity.ts";
|
|
12
12
|
import { readStatus } from "../../shared/utils.ts";
|
|
13
13
|
import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
|
|
14
|
+
import { normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
|
|
14
15
|
import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
|
|
15
16
|
import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
|
|
16
17
|
import { formatWaitSubscriptions } from "./wait-subscriptions.ts";
|
|
@@ -21,8 +22,14 @@ import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-
|
|
|
21
22
|
import { attachRootChildrenToSteps, findNestedRouteForRootId, projectNestedRegistryForRoot, type NestedRunResolutionScope } from "../shared/nested-events.ts";
|
|
22
23
|
import { readMissionBinding } from "../../missions/lifecycle.ts";
|
|
23
24
|
import { formatWorkflowJsonPreview } from "../../workflows/scripted-workflow.ts";
|
|
25
|
+
import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
|
|
26
|
+
import { formatWorkflowPreflightPlanSummary, formatWorkflowPreflightWarningSummary } from "../../workflows/workflow-preflight.ts";
|
|
24
27
|
import { formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
|
|
28
|
+
import { workflowGraphStageNodes } from "../shared/workflow-graph.ts";
|
|
25
29
|
import { getExternalJobProvider } from "../../api/external-job-provider.ts";
|
|
30
|
+
import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
|
|
31
|
+
import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
|
|
32
|
+
import { validHostStepNodes } from "../shared/host-step-status.ts";
|
|
26
33
|
|
|
27
34
|
interface RunStatusParams {
|
|
28
35
|
action?: string;
|
|
@@ -62,13 +69,14 @@ function formatCapacityOwner(inspect: ActiveAsyncCapacityInspection): string[] {
|
|
|
62
69
|
}
|
|
63
70
|
|
|
64
71
|
function formatWorkflowDebug(status: AsyncStatus): string[] {
|
|
65
|
-
if (status.mode !== "workflow" && !status.parentWorkflowRunId && !status.workflowKey) return [];
|
|
72
|
+
if (status.mode !== "workflow" && !status.parentWorkflowRunId && !status.workflowKey && !status.lane) return [];
|
|
66
73
|
const lines = [
|
|
67
74
|
status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
|
|
68
75
|
status.mode === "workflow" ? `Workflow children: ${(status.steps ?? []).length}` : undefined,
|
|
76
|
+
status.lane ? `Lane: ${status.lane.key}${status.lane.mode ? ` (${status.lane.mode})` : ""}` : undefined,
|
|
69
77
|
].filter((line): line is string => line !== undefined);
|
|
70
78
|
for (const [index, step] of (status.steps ?? []).entries()) {
|
|
71
|
-
lines.push(` ${index + 1}. key ${step.workflowKey ?? "n/a"} · ${step
|
|
79
|
+
lines.push(` ${index + 1}. key ${step.workflowKey ?? "n/a"} · ${runStatusStepDisplayName(step)} · ${step.status} · async ${step.async === undefined ? "unknown" : step.async ? "yes" : "no"}${step.runId ? ` · run ${step.runId}` : ""}${step.lane ? ` · lane ${step.lane.key}` : ""}${step.worktreePath ? ` · worktree ${step.worktreePath} · branch ${step.branch ?? "unknown"}${step.provider ? ` · provider ${step.provider}` : ""}` : ""}`);
|
|
72
80
|
}
|
|
73
81
|
return lines;
|
|
74
82
|
}
|
|
@@ -86,6 +94,7 @@ function formatRunLifecycleDebug(input: { status: AsyncStatus; asyncDir: string;
|
|
|
86
94
|
`Mode: ${status.mode}`,
|
|
87
95
|
status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}` : undefined,
|
|
88
96
|
status.workflowKey ? `Workflow key: ${status.workflowKey}` : undefined,
|
|
97
|
+
status.lane ? `Lane: ${status.lane.key}${status.lane.mode ? ` (${status.lane.mode})` : ""}` : undefined,
|
|
89
98
|
`Status process terminal: ${formatProcessTerminal(overlayProcessTerminal)}`,
|
|
90
99
|
`Sidecar process terminal: ${formatProcessTerminal(sidecarProcessTerminal)}`,
|
|
91
100
|
...formatCapacityOwner(capacity),
|
|
@@ -103,6 +112,7 @@ interface RunStatusDeps {
|
|
|
103
112
|
nested?: NestedRunResolutionScope;
|
|
104
113
|
sessionRoots?: string[];
|
|
105
114
|
activeCapacityRoot?: string;
|
|
115
|
+
abandonedSlotReleaseAfterMs?: number | false;
|
|
106
116
|
}
|
|
107
117
|
|
|
108
118
|
function hasExistingSessionFile(value: unknown): value is string {
|
|
@@ -120,7 +130,7 @@ function formatResumeGuidance(runId: string | undefined, children: Array<{ agent
|
|
|
120
130
|
const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
|
|
121
131
|
if (workflowChildren.length > 0) {
|
|
122
132
|
return [
|
|
123
|
-
...supervisorDetachedWorkflowChildren.map(({ child }) => `Recovery workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: reply to the supervisor request first, then wait with
|
|
133
|
+
...supervisorDetachedWorkflowChildren.map(({ child }) => `Recovery workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: reply to the supervisor request first, then wait with bg_wait({ id: "${child.runId}" }). Use subagent({ action: "status", id: "${child.runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`),
|
|
124
134
|
...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`),
|
|
125
135
|
].join("\n");
|
|
126
136
|
}
|
|
@@ -149,7 +159,12 @@ function stepLineLabel(status: AsyncStatus, index: number): string {
|
|
|
149
159
|
return `Step ${index + 1}`;
|
|
150
160
|
}
|
|
151
161
|
|
|
162
|
+
function runStatusStepDisplayName(step: { agent: string; sessionName?: string; label?: string }): string {
|
|
163
|
+
return step.sessionName?.trim() || (step.label ? `${step.label} (${step.agent})` : step.agent);
|
|
164
|
+
}
|
|
165
|
+
|
|
152
166
|
function nestedRunDisplayName(run: NestedRunSummary): string {
|
|
167
|
+
if (run.sessionName?.trim()) return run.sessionName.trim();
|
|
153
168
|
if (run.agent) return run.agent;
|
|
154
169
|
if (run.agents?.length) return run.agents.join(", ");
|
|
155
170
|
return run.id;
|
|
@@ -194,7 +209,7 @@ function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
|
|
|
194
209
|
for (const child of run.children) {
|
|
195
210
|
const output = rememberedForegroundChildOutput(child).trim().split(/\r?\n/).find((line) => line.trim());
|
|
196
211
|
const parts = [
|
|
197
|
-
`${child.index + 1}. ${child.agent} ${child.status}`,
|
|
212
|
+
`${child.index + 1}. ${child.sessionName?.trim() || child.agent} ${child.status}`,
|
|
198
213
|
child.exitCode !== undefined ? `exit ${child.exitCode}` : undefined,
|
|
199
214
|
child.detachedReason ? `detached: ${child.detachedReason}` : undefined,
|
|
200
215
|
child.acceptance ? `acceptance: ${child.acceptance.status}` : undefined,
|
|
@@ -215,7 +230,7 @@ function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
|
|
|
215
230
|
const detached = run.children.some((child) => child.status === "detached");
|
|
216
231
|
const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
|
|
217
232
|
if (detached) {
|
|
218
|
-
lines.push(`Recovery: reply to the supervisor request first, then wait with
|
|
233
|
+
lines.push(`Recovery: reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
|
|
219
234
|
} else if (resumable) {
|
|
220
235
|
lines.push(run.children.length === 1
|
|
221
236
|
? `Revive: subagent({ action: "resume", id: "${run.runId}", message: "..." })`
|
|
@@ -238,7 +253,7 @@ function formatRememberedForegroundTranscript(run: ForegroundResumeRun, options:
|
|
|
238
253
|
const lines = [
|
|
239
254
|
`Run: ${run.runId}`,
|
|
240
255
|
`State: ${child.status}`,
|
|
241
|
-
`Child: ${index} (${child.agent})`,
|
|
256
|
+
`Child: ${index} (${child.sessionName?.trim() || child.agent})`,
|
|
242
257
|
child.sessionFile ? `Session: ${child.sessionFile}` : undefined,
|
|
243
258
|
child.transcriptPath ? `Transcript: ${child.transcriptPath}` : undefined,
|
|
244
259
|
child.artifactPaths?.outputPath ? `Output: ${child.artifactPaths.outputPath}` : undefined,
|
|
@@ -274,7 +289,7 @@ function formatNestedExactStatus(rootRunId: string, run: NestedRunSummary): stri
|
|
|
274
289
|
for (const [index, step] of run.steps.entries()) {
|
|
275
290
|
const activity = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
|
|
276
291
|
const budget = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
277
|
-
lines.push(` ${index + 1}. ${step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
|
|
292
|
+
lines.push(` ${index + 1}. ${step.sessionName?.trim() || step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
|
|
278
293
|
lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true }));
|
|
279
294
|
}
|
|
280
295
|
}
|
|
@@ -405,7 +420,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
405
420
|
if (!status && diskStatus?.displayDismissedAt !== undefined) {
|
|
406
421
|
if (params.action === "debug.run") {
|
|
407
422
|
const { sidecar, overlay } = debugProcessTerminal(asyncDir, diskStatus);
|
|
408
|
-
const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
|
|
423
|
+
const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
|
|
409
424
|
return {
|
|
410
425
|
content: [{ type: "text", text: formatRunLifecycleDebug({ status: diskStatus, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
|
|
411
426
|
details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
|
|
@@ -432,7 +447,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
432
447
|
if (status) {
|
|
433
448
|
if (params.action === "debug.run") {
|
|
434
449
|
const { sidecar, overlay } = debugProcessTerminal(asyncDir, status);
|
|
435
|
-
const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
|
|
450
|
+
const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
|
|
436
451
|
return {
|
|
437
452
|
content: [{ type: "text", text: formatRunLifecycleDebug({ status, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
|
|
438
453
|
details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
|
|
@@ -470,6 +485,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
470
485
|
currentStep: status.currentStep,
|
|
471
486
|
chainStepCount: status.chainStepCount,
|
|
472
487
|
parallelGroups: status.parallelGroups,
|
|
488
|
+
workflowGraph: status.workflowGraph,
|
|
473
489
|
steps: (status.steps ?? []).map((step, index) => ({ index, agent: step.agent, status: step.status })),
|
|
474
490
|
});
|
|
475
491
|
const started = new Date(status.startedAt).toISOString();
|
|
@@ -501,11 +517,21 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
501
517
|
statusActivityText ? `Activity: ${statusActivityText}` : undefined,
|
|
502
518
|
steeringText ? `Steering: ${steeringText}` : undefined,
|
|
503
519
|
`Mode: ${status.mode}`,
|
|
520
|
+
...(status.preflight ? [formatWorkflowPreflightPlanSummary(status.preflight)] : []),
|
|
521
|
+
...(status.workflow?.preflightWarnings?.length ? [formatWorkflowPreflightWarningSummary(status.workflow.preflightWarnings)] : []),
|
|
504
522
|
runFanoutBudget ? formatRunFanoutBudget(runFanoutBudget) : undefined,
|
|
505
523
|
status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
|
|
506
524
|
status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
|
|
507
525
|
status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
|
|
508
526
|
`Progress: ${progressLabel}`,
|
|
527
|
+
...(status.mode === "workflow" ? formatWorkflowChecklistText(projectWorkflowChecklist({
|
|
528
|
+
graph: status.workflowGraph,
|
|
529
|
+
steps: status.steps,
|
|
530
|
+
hostSteps: validHostStepNodes(status.workflowGraph),
|
|
531
|
+
preflight: status.preflight,
|
|
532
|
+
trace: status.workflow?.trace,
|
|
533
|
+
now: status.lastUpdate ?? status.endedAt ?? Date.now(),
|
|
534
|
+
}), "", { includeItems: false }) : []),
|
|
509
535
|
status.pendingAppends ? `Pending appends: ${status.pendingAppends}` : undefined,
|
|
510
536
|
`Started: ${started}`,
|
|
511
537
|
`Updated: ${updated}`,
|
|
@@ -519,7 +545,6 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
519
545
|
const liveWorkflowControls = status.mode === "workflow" && deps.state?.currentSessionId === status.sessionId && deps.state?.workflowControllers?.has(status.runId)
|
|
520
546
|
? [...(deps.state?.foregroundControls.values() ?? [])].filter((control) => control.parentWorkflowRunId === status.runId
|
|
521
547
|
&& control.sessionId === status.sessionId
|
|
522
|
-
&& Boolean(control.workflowSteeringDir && fs.existsSync(control.workflowSteeringDir))
|
|
523
548
|
&& (control.activeChildren?.size ?? 0) > 0)
|
|
524
549
|
: [];
|
|
525
550
|
let hasExternalJobFollowUpHint = false;
|
|
@@ -532,13 +557,37 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
532
557
|
const errorText = step.error ? `, error: ${step.error}` : "";
|
|
533
558
|
const acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "";
|
|
534
559
|
const budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
|
|
535
|
-
const display =
|
|
560
|
+
const display = runStatusStepDisplayName(step);
|
|
536
561
|
const phase = step.phase ? `[${step.phase}] ` : "";
|
|
537
562
|
lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
|
|
563
|
+
const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
|
|
564
|
+
if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
|
|
565
|
+
if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
|
|
566
|
+
lines.push(...formatTimeoutRecoveryLines(step.timeoutRecovery, " "));
|
|
538
567
|
if (step.runner?.type === "external-cli") {
|
|
539
|
-
|
|
568
|
+
const runner = normalizeExternalCliRunnerStatus(step.runner);
|
|
569
|
+
if (runner) {
|
|
570
|
+
lines.push(` Runner: external-cli (${runner.command}${runner.args.length ? ` ${runner.args.join(" ")}` : ""})`);
|
|
571
|
+
lines.push(` Adapter: ${runner.adapter.id} v${runner.adapter.version} (${runner.adapter.executionMode})`);
|
|
572
|
+
if (runner.safety) {
|
|
573
|
+
if ("approvalPolicy" in runner.safety) lines.push(` Safety: ${"access" in runner.safety ? `access=${runner.safety.access}, ` : ""}sandbox=${runner.safety.sandbox}, approval=${runner.safety.approvalPolicy}, ephemeral=${runner.safety.ephemeral}`);
|
|
574
|
+
else if ("mode" in runner.safety) lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, mode=${runner.safety.mode}, sandbox=${runner.safety.sandbox}, workspaceTrust=${runner.safety.workspaceTrust}, sessionReuse=${runner.safety.sessionReuse}`);
|
|
575
|
+
else if ("authentication" in runner.safety) lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, settingsTrust=${runner.safety.userSettingsTrust}, persistence=${runner.safety.sessionPersistence}`);
|
|
576
|
+
else lines.push(` Safety: access=read-only, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, persistence=${runner.safety.sessionPersistence}`);
|
|
577
|
+
}
|
|
578
|
+
lines.push(` Capabilities: stop=${runner.capabilities.stop}, steer=false, resume=false, structuredOutput=false, toolEvents=false, supervisor=unsupported, forkContext=false, extensionBindings=false`);
|
|
579
|
+
lines.push(` Unsupported steer: ${runner.unsupportedReasons.steer}`);
|
|
580
|
+
lines.push(` Unsupported resume: ${runner.nonResumableReason}`);
|
|
581
|
+
lines.push(` Unsupported supervisor: ${runner.unsupportedReasons.supervisor}`);
|
|
582
|
+
lines.push(` Context handoff: fresh only (${runner.unsupportedReasons.forkContext})`);
|
|
583
|
+
} else {
|
|
584
|
+
lines.push(" Runner: external-cli (invalid persisted runner metadata)");
|
|
585
|
+
}
|
|
540
586
|
if (step.externalProcess?.pid !== undefined) lines.push(` Process: ${step.externalProcess.pid}`);
|
|
541
|
-
if (step.externalProcess)
|
|
587
|
+
if (step.externalProcess) {
|
|
588
|
+
lines.push(` Stdout: ${step.externalProcess.stdoutPath}`, ` Stderr: ${step.externalProcess.stderrPath}`);
|
|
589
|
+
if (step.externalProcess.finalOutputPath) lines.push(` Final output: ${step.externalProcess.finalOutputPath}`);
|
|
590
|
+
}
|
|
542
591
|
} else if (step.runner?.type === "external-job") {
|
|
543
592
|
lines.push(` Runner: external-job (${step.runner.provider})`);
|
|
544
593
|
if (step.externalJob?.providerJobId) lines.push(` Provider job: ${step.externalJob.providerJobId}`);
|
|
@@ -560,6 +609,11 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
560
609
|
lines.push(" Steer: unavailable; external runners do not accept live messages.");
|
|
561
610
|
}
|
|
562
611
|
}
|
|
612
|
+
const loadedWorkflowKeys = new Set((status.steps ?? []).flatMap((step) => step.workflowKey ? [step.workflowKey] : []));
|
|
613
|
+
const graphStages = status.mode === "workflow" ? workflowGraphStageNodes(status.workflowGraph) : [];
|
|
614
|
+
for (const [index, node] of graphStages.entries()) {
|
|
615
|
+
if (!loadedWorkflowKeys.has(node.id)) lines.push(` ${formatWorkflowStageLine(node, index, graphStages.length)}`);
|
|
616
|
+
}
|
|
563
617
|
const attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? []));
|
|
564
618
|
const unattached = nestedChildren.filter((child) => !attached.has(child.id));
|
|
565
619
|
lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: true, maxLines: 20 }));
|
|
@@ -583,7 +637,9 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
583
637
|
if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
|
|
584
638
|
if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
|
|
585
639
|
|
|
586
|
-
|
|
640
|
+
const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
|
|
641
|
+
if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
|
|
642
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(status.preflight ? { preflight: status.preflight } : {}), ...(status.workflow?.preflightWarnings?.length ? { preflightWarnings: status.workflow.preflightWarnings } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
|
|
587
643
|
}
|
|
588
644
|
}
|
|
589
645
|
|
|
@@ -597,7 +653,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
597
653
|
}
|
|
598
654
|
try {
|
|
599
655
|
const raw = fs.readFileSync(resultPath, "utf-8");
|
|
600
|
-
const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; runId?: string; workflowKey?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null }> };
|
|
656
|
+
const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; timeoutRecovery?: unknown; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; sessionName?: string; runId?: string; workflowKey?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null; timeoutRecovery?: unknown }> };
|
|
601
657
|
if (params.view === "transcript") {
|
|
602
658
|
try {
|
|
603
659
|
return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
|
|
@@ -625,9 +681,20 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
|
|
|
625
681
|
const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line): line is string => Boolean(line));
|
|
626
682
|
if (data.parallelHandoff?.path) lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
|
|
627
683
|
const children = Array.isArray(data.results) ? data.results : data.agent ? [{ agent: data.agent, sessionFile: data.sessionFile }] : [];
|
|
684
|
+
lines.push(...formatTimeoutRecoveryLines(data.timeoutRecovery, " "));
|
|
685
|
+
for (const [index, child] of children.entries()) {
|
|
686
|
+
const structuredOutput = (child as { structuredOutput?: unknown }).structuredOutput;
|
|
687
|
+
const structuredOutputPreview = structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(structuredOutput, 4_000);
|
|
688
|
+
if (structuredOutputPreview !== undefined) lines.push(` Structured output${children.length > 1 ? ` (${index + 1})` : ""}: ${structuredOutputPreview}`);
|
|
689
|
+
const structuredOutputPath = (child as { structuredOutputPath?: unknown }).structuredOutputPath;
|
|
690
|
+
if (typeof structuredOutputPath === "string" && structuredOutputPath.trim()) lines.push(` Structured output path${children.length > 1 ? ` (${index + 1})` : ""}: ${structuredOutputPath}`);
|
|
691
|
+
lines.push(...formatTimeoutRecoveryLines(child.timeoutRecovery, " "));
|
|
692
|
+
}
|
|
628
693
|
lines.push(formatResumeGuidance(runId, children, data.sessionFile, { stopped: status === "stopped" }));
|
|
629
694
|
if (data.summary) lines.push("", data.summary);
|
|
630
|
-
|
|
695
|
+
const workflowChildren = parseWorkflowChildSummary((data as unknown as Record<string, unknown>).workflowChildren);
|
|
696
|
+
if (workflowChildren && workflowChildren.workflowRunId !== runId) throw new Error("workflowChildren.workflowRunId does not match the result run id.");
|
|
697
|
+
return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(workflowChildren ? { workflowChildren } : {}) } };
|
|
631
698
|
} catch (error) {
|
|
632
699
|
const message = error instanceof Error ? error.message : String(error);
|
|
633
700
|
return {
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Module aliases for the detached async runner.
|
|
3
|
+
*
|
|
4
|
+
* The runner is a plain Node process started through jiti. The child hooks it
|
|
5
|
+
* loads import pi's host packages (`@earendil-works/pi-coding-agent`,
|
|
6
|
+
* `pi-agent-core`, `pi-ai`, `pi-tui`, `typebox`), which are peer packages of
|
|
7
|
+
* this extension and are not installed next to it. pi's own extension loader
|
|
8
|
+
* aliases those specifiers to the copies shipped inside the installed pi
|
|
9
|
+
* package; the parent computes the same map and hands it to the runner
|
|
10
|
+
* through `JITI_ALIAS`, so the runner's child sessions and hooks share one
|
|
11
|
+
* copy of every host package.
|
|
12
|
+
*/
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
|
|
16
|
+
export const JITI_ALIAS_ENV = "JITI_ALIAS";
|
|
17
|
+
|
|
18
|
+
/** Specifiers the runner's import graph may use, with the package and export subpath each resolves to. */
|
|
19
|
+
export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string }> = [
|
|
20
|
+
{ specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
|
|
21
|
+
{ specifier: "@earendil-works/pi-agent-core", pkg: "@earendil-works/pi-agent-core", subpath: "." },
|
|
22
|
+
{ specifier: "@earendil-works/pi-tui", pkg: "@earendil-works/pi-tui", subpath: "." },
|
|
23
|
+
{ specifier: "@earendil-works/pi-ai", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
|
|
24
|
+
{ specifier: "@earendil-works/pi-ai/compat", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
|
|
25
|
+
{ specifier: "@earendil-works/pi-ai/oauth", pkg: "@earendil-works/pi-ai", subpath: "./oauth" },
|
|
26
|
+
{ specifier: "@earendil-works/pi-ai/providers/all", pkg: "@earendil-works/pi-ai", subpath: "./providers/all" },
|
|
27
|
+
{ specifier: "typebox", pkg: "typebox", subpath: "." },
|
|
28
|
+
{ specifier: "typebox/compile", pkg: "typebox", subpath: "./compile" },
|
|
29
|
+
{ specifier: "typebox/value", pkg: "typebox", subpath: "./value" },
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
interface PackageManifest {
|
|
33
|
+
name?: unknown;
|
|
34
|
+
main?: unknown;
|
|
35
|
+
exports?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readManifest(packageDir: string): PackageManifest | undefined {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf-8")) as PackageManifest;
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pick the import target of one exports entry (string, conditions object, or array of those). */
|
|
47
|
+
function exportTarget(entry: unknown): string | undefined {
|
|
48
|
+
if (typeof entry === "string") return entry;
|
|
49
|
+
if (Array.isArray(entry)) {
|
|
50
|
+
for (const candidate of entry) {
|
|
51
|
+
const target = exportTarget(candidate);
|
|
52
|
+
if (target) return target;
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
if (entry && typeof entry === "object") {
|
|
57
|
+
const conditions = entry as Record<string, unknown>;
|
|
58
|
+
for (const condition of ["import", "node", "default"]) {
|
|
59
|
+
if (condition in conditions) {
|
|
60
|
+
const target = exportTarget(conditions[condition]);
|
|
61
|
+
if (target) return target;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Resolve `subpath` of the package at `packageDir` through its `exports` map (with `*` patterns) or `main`. */
|
|
69
|
+
export function resolvePackageSubpath(packageDir: string, subpath: string): string | undefined {
|
|
70
|
+
const manifest = readManifest(packageDir);
|
|
71
|
+
if (!manifest) return undefined;
|
|
72
|
+
const exportsField = manifest.exports;
|
|
73
|
+
if (exportsField !== undefined) {
|
|
74
|
+
const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
|
|
75
|
+
? { ".": exportsField }
|
|
76
|
+
: exportsField as Record<string, unknown>;
|
|
77
|
+
const exact = exportTarget(map[subpath]);
|
|
78
|
+
if (exact) return path.resolve(packageDir, exact);
|
|
79
|
+
for (const [pattern, entry] of Object.entries(map)) {
|
|
80
|
+
const star = pattern.indexOf("*");
|
|
81
|
+
if (star === -1) continue;
|
|
82
|
+
const prefix = pattern.slice(0, star);
|
|
83
|
+
const suffix = pattern.slice(star + 1);
|
|
84
|
+
if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix) || subpath.length < prefix.length + suffix.length) continue;
|
|
85
|
+
const target = exportTarget(entry);
|
|
86
|
+
if (!target) continue;
|
|
87
|
+
const wildcard = subpath.slice(prefix.length, subpath.length - suffix.length);
|
|
88
|
+
return path.resolve(packageDir, target.replace("*", wildcard));
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
if (subpath !== ".") return undefined;
|
|
93
|
+
return path.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Find `pkg` as the pi package itself, one of its dependencies, or a sibling in a hoisted install. */
|
|
97
|
+
export function findHostPeerPackageDir(piPackageRoot: string, pkg: string): string | undefined {
|
|
98
|
+
if (readManifest(piPackageRoot)?.name === pkg) return piPackageRoot;
|
|
99
|
+
const candidates = [path.join(piPackageRoot, "node_modules", pkg)];
|
|
100
|
+
let dir = piPackageRoot;
|
|
101
|
+
for (;;) {
|
|
102
|
+
const parent = path.dirname(dir);
|
|
103
|
+
if (parent === dir) break;
|
|
104
|
+
if (path.basename(parent) === "node_modules" || path.basename(path.dirname(parent)) === "node_modules") {
|
|
105
|
+
const modulesRoot = path.basename(parent) === "node_modules" ? parent : path.dirname(parent);
|
|
106
|
+
candidates.push(path.join(modulesRoot, pkg));
|
|
107
|
+
}
|
|
108
|
+
candidates.push(path.join(parent, "node_modules", pkg));
|
|
109
|
+
dir = parent;
|
|
110
|
+
}
|
|
111
|
+
return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The alias map the runner needs, or the specifiers that could not be resolved. */
|
|
115
|
+
export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
|
|
116
|
+
const aliases: Record<string, string> = {};
|
|
117
|
+
const missing: string[] = [];
|
|
118
|
+
for (const { specifier, pkg, subpath } of HOST_PEER_ALIASES) {
|
|
119
|
+
const packageDir = findHostPeerPackageDir(piPackageRoot, pkg);
|
|
120
|
+
const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
|
|
121
|
+
if (target && fs.existsSync(target)) aliases[specifier] = target;
|
|
122
|
+
else missing.push(specifier);
|
|
123
|
+
}
|
|
124
|
+
return { aliases, missing };
|
|
125
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child session factory for the detached async runner.
|
|
3
|
+
*
|
|
4
|
+
* The runner imports `@earendil-works/pi-coding-agent` like the parent does;
|
|
5
|
+
* the parent aliases that specifier (and the other host peer packages) to the
|
|
6
|
+
* installed pi package through `JITI_ALIAS` when it spawns the runner, see
|
|
7
|
+
* `runner-aliases.ts`. Tests replace the factory with a scripted one by
|
|
8
|
+
* naming a module in the runner config.
|
|
9
|
+
*/
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { createDefaultChildSessionFactory, type ChildSessionFactory } from "../shared/child-session.ts";
|
|
13
|
+
|
|
14
|
+
export interface RunnerChildSessionConfig {
|
|
15
|
+
/** Test seam: module whose default export is a `ChildSessionFactory`, or a function returning one. */
|
|
16
|
+
childSessionFactoryModule?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function isChildSessionFactory(value: unknown): value is ChildSessionFactory {
|
|
20
|
+
return Boolean(value) && typeof value === "object" && typeof (value as ChildSessionFactory).create === "function" && typeof (value as ChildSessionFactory).dispose === "function";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function loadRunnerChildSessionFactory(config: RunnerChildSessionConfig): Promise<ChildSessionFactory> {
|
|
24
|
+
if (!config.childSessionFactoryModule) return createDefaultChildSessionFactory();
|
|
25
|
+
const loaded = await import(pathToFileURL(path.resolve(config.childSessionFactoryModule)).href) as { default?: unknown };
|
|
26
|
+
const candidate = typeof loaded.default === "function" ? (loaded.default as () => unknown)() : loaded.default;
|
|
27
|
+
if (!isChildSessionFactory(candidate)) {
|
|
28
|
+
throw new Error(`Child session factory module '${config.childSessionFactoryModule}' must default-export a ChildSessionFactory or a function returning one.`);
|
|
29
|
+
}
|
|
30
|
+
return candidate;
|
|
31
|
+
}
|