pi-subagents 0.88.0 → 0.88.1
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 +18 -0
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-SVIXQDIV.js → chunk-4ZQBZDF3.js} +2 -2
- package/bundle/{chunk-YZPVALSQ.js → chunk-5EMPFFO4.js} +3 -3
- package/bundle/{chunk-CKLZ5FGU.js → chunk-6CG2VAG4.js} +1 -1
- package/bundle/{chunk-6EUQPQY7.js → chunk-7OX6O7DQ.js} +3 -3
- package/bundle/{chunk-3DT5X2QC.js → chunk-CPSUJHZE.js} +11 -8
- package/bundle/{chunk-3MFYKBKI.js → chunk-D32H53HM.js} +3 -3
- package/bundle/{chunk-PJSOS2Q4.js → chunk-DSHQWGHO.js} +1 -1
- package/bundle/{chunk-4PM6RDE5.js → chunk-FLNDHNPE.js} +46 -28
- package/bundle/{chunk-RHYVKQQL.js → chunk-LV3CPYXJ.js} +2 -2
- package/bundle/{chunk-47GJDBIK.js → chunk-N6TAAIB3.js} +2 -2
- package/bundle/{chunk-4UGWHREQ.js → chunk-PCZEQQAQ.js} +75 -40
- package/bundle/{chunk-IZEKQEY4.js → chunk-PYKBTBY6.js} +23 -6
- package/bundle/{chunk-6PR44R7E.js → chunk-RMZAAXIR.js} +1 -1
- package/bundle/{chunk-UVDLJXL6.js → chunk-VTUUOLM4.js} +3 -3
- package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
- package/bundle/{chunk-MTPICU4A.js → chunk-YQSTGPEU.js} +7 -7
- package/bundle/{chunk-XAOHLFJO.js → chunk-ZJ2BT5TI.js} +21 -16
- package/bundle/index.js +1 -1
- package/bundle/preflight.js +4 -4
- package/bundle/required-child-extensions.js +1 -1
- package/docs/agents.md +4 -2
- package/docs/workflows.md +3 -1
- package/package.json +1 -1
- package/src/extension/index.d.ts +1 -1
- package/src/extension/index.js +43 -20
- package/src/extension/subagent-launch-tool.d.ts +6 -2
- package/src/extension/subagent-launch-tool.js +13 -9
- package/src/runs/background/stale-run-reconciler.js +17 -8
- package/src/runs/foreground/subagent-executor.js +11 -6
- package/src/runs/shared/child-launch.js +6 -3
- package/src/runs/shared/child-session.d.ts +1 -1
- package/src/runs/shared/child-session.js +3 -27
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -3
- package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -4
- package/src/shared/compaction-interruption.d.ts +9 -0
- package/src/shared/compaction-interruption.js +47 -0
- package/src/shared/parent-wake.d.ts +3 -2
- package/src/shared/parent-wake.js +14 -3
- package/src/shared/required-child-extensions.d.ts +2 -0
- package/src/shared/required-child-extensions.js +27 -0
- package/src/tui/fleet.d.ts +7 -2
- package/src/tui/fleet.js +22 -0
|
@@ -450,8 +450,23 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
|
|
|
450
450
|
const existingResultPath = effectiveStatus.sessionId
|
|
451
451
|
? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : undefined)
|
|
452
452
|
: regularFileExists(resultPath) ? resultPath : undefined;
|
|
453
|
+
const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
|
|
454
|
+
const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
|
|
455
|
+
const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
|
|
456
|
+
const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
|
|
457
|
+
kill: options.kill,
|
|
458
|
+
observedScope,
|
|
459
|
+
observedBootId: options.bootId ? options.bootId() : currentBootId(),
|
|
460
|
+
});
|
|
453
461
|
if (existingResultPath) {
|
|
454
|
-
|
|
462
|
+
// A live runner writes its result before its final status; repairing in that window would replace
|
|
463
|
+
// its pending exit proof with a placeholder. Only a confirmed-alive pid defers: a result is better
|
|
464
|
+
// evidence than an unprobeable pid, and a pid from another pid namespace can be alive here as an unrelated
|
|
465
|
+
// process. A workflow's pid is its host Pi process, which outlives the workflow.
|
|
466
|
+
const runnerStillFinishing = effectiveStatus.state === "running" && effectiveStatus.mode !== "workflow" && typeof effectiveStatus.pid === "number"
|
|
467
|
+
&& effectiveStatus.pidNamespaceScope === observedScope
|
|
468
|
+
&& now - lastUpdate <= staleAfterMs && runnerLiveness(effectiveStatus.pid) === "alive";
|
|
469
|
+
const terminalStatus = (effectiveStatus.state === "running" || effectiveStatus.state === "queued") && !runnerStillFinishing
|
|
455
470
|
? terminalStatusFromResult(effectiveStatus, existingResultPath, now)
|
|
456
471
|
: undefined;
|
|
457
472
|
if (terminalStatus) {
|
|
@@ -491,14 +506,8 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
|
|
|
491
506
|
return { status: null, repaired: false, resultPath };
|
|
492
507
|
}
|
|
493
508
|
}
|
|
494
|
-
const liveness =
|
|
495
|
-
kill: options.kill,
|
|
496
|
-
observedScope: options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope(),
|
|
497
|
-
observedBootId: options.bootId ? options.bootId() : currentBootId(),
|
|
498
|
-
});
|
|
509
|
+
const liveness = runnerLiveness(effectiveStatus.pid);
|
|
499
510
|
if (liveness !== "dead") {
|
|
500
|
-
const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
|
|
501
|
-
const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
|
|
502
511
|
if (now - lastUpdate <= staleAfterMs)
|
|
503
512
|
return { status: status ?? null, repaired: false, resultPath };
|
|
504
513
|
const probe = liveness === "alive" ? "is still live" : "cannot be probed from this process";
|
|
@@ -5963,9 +5963,12 @@ export function createSubagentExecutor(deps) {
|
|
|
5963
5963
|
const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
|
|
5964
5964
|
const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
|
|
5965
5965
|
preparedChildParams = childRequest;
|
|
5966
|
-
const
|
|
5967
|
-
if (
|
|
5968
|
-
return buildRequestedModeError(childRequest,
|
|
5966
|
+
const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
|
|
5967
|
+
if ("refusal" in approval)
|
|
5968
|
+
return buildRequestedModeError(childRequest, approval.refusal);
|
|
5969
|
+
// Assigned in place: the WeakMaps below are keyed on this object. A resume's task is its message, which stays as sent.
|
|
5970
|
+
if (approval.task !== undefined && childRequest.action !== "resume")
|
|
5971
|
+
childRequest.task = approval.task;
|
|
5969
5972
|
if (workflowUsageBudget.budget)
|
|
5970
5973
|
workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
|
|
5971
5974
|
if (workflowRequiredExtensions)
|
|
@@ -6294,9 +6297,11 @@ export function createSubagentExecutor(deps) {
|
|
|
6294
6297
|
const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
|
|
6295
6298
|
const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
|
|
6296
6299
|
preparedChildParams = childRequest;
|
|
6297
|
-
const
|
|
6298
|
-
if (
|
|
6299
|
-
return buildRequestedModeError(childRequest,
|
|
6300
|
+
const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
|
|
6301
|
+
if ("refusal" in approval)
|
|
6302
|
+
return buildRequestedModeError(childRequest, approval.refusal);
|
|
6303
|
+
if (approval.task !== undefined && childRequest.action !== "resume")
|
|
6304
|
+
childRequest.task = approval.task;
|
|
6300
6305
|
if (workflowUsageBudget.budget)
|
|
6301
6306
|
workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
|
|
6302
6307
|
if (workflowRequiredExtensions)
|
|
@@ -13,7 +13,7 @@ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV } from "./e
|
|
|
13
13
|
import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
|
|
14
14
|
import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
|
|
15
15
|
import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
|
|
16
|
-
import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
|
|
16
|
+
import { createRequiredChildExtensionIdentity, resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
|
|
17
17
|
import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
|
|
18
18
|
/** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
|
|
19
19
|
export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
|
|
@@ -57,6 +57,8 @@ function childProcessEnv(input, toolPlan) {
|
|
|
57
57
|
else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
|
|
58
58
|
env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
|
|
59
59
|
}
|
|
60
|
+
else if (input.tools === undefined && !toolPlan.capabilityCeiling)
|
|
61
|
+
env[MCP_DIRECT_TOOLS_ENV] = undefined;
|
|
60
62
|
else
|
|
61
63
|
env[MCP_DIRECT_TOOLS_ENV] = "__none__";
|
|
62
64
|
return env;
|
|
@@ -106,10 +108,11 @@ export function buildInProcessChildLaunch(input) {
|
|
|
106
108
|
permissionRules: input.permissionRules,
|
|
107
109
|
runtimeSnapshotHost: input.runtimeSnapshotHost,
|
|
108
110
|
});
|
|
109
|
-
// Foreground children load no ambient extensions, so
|
|
111
|
+
// Foreground children load no ambient extensions, so only their required extensions' registerMcpServer() runs in them.
|
|
110
112
|
if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
|
|
113
|
+
const requiredExtensionIdentity = createRequiredChildExtensionIdentity(toolPlan.requiredExtensions.map(({ path }) => path));
|
|
111
114
|
// Pi treats a session without a trust decision as trusted.
|
|
112
|
-
const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
|
|
115
|
+
const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false, (extensionPath) => requiredExtensionIdentity(extensionPath) !== undefined);
|
|
113
116
|
if (servers.length)
|
|
114
117
|
throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
|
|
115
118
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
|
|
4
|
-
import type
|
|
4
|
+
import { type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
|
|
5
5
|
import type { PlacementMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
|
|
6
6
|
export interface ChildSessionEvent {
|
|
7
7
|
type: string;
|
|
@@ -26,6 +26,7 @@ import { parseAcceptanceReport } from "./acceptance.js";
|
|
|
26
26
|
import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.js";
|
|
27
27
|
import { resolvePackageSubpath } from "../background/runner-aliases.js";
|
|
28
28
|
import { PI_CODING_AGENT_PACKAGE, resolveHostPiPackageRoot } from "./pi-spawn.js";
|
|
29
|
+
import { createRequiredChildExtensionIdentity } from "../../shared/required-child-extensions.js";
|
|
29
30
|
/** Mirror pi's JSON event projection: `message_update` drops the partial message. */
|
|
30
31
|
export function projectChildSessionEventForJson(event) {
|
|
31
32
|
if (event.type !== "message_update")
|
|
@@ -80,32 +81,6 @@ const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime
|
|
|
80
81
|
const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
|
|
81
82
|
/** Same class as UNICODE_SPACES in pi-coding-agent dist/utils/paths.js, which resolvePath(..., { normalizeUnicodeSpaces: true }) replaces with a space. */
|
|
82
83
|
const PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
|
|
83
|
-
function childExtensionFileIdentity(extensionPath) {
|
|
84
|
-
if (!path.isAbsolute(extensionPath))
|
|
85
|
-
return undefined;
|
|
86
|
-
try {
|
|
87
|
-
const stat = fs.statSync(extensionPath, { bigint: true });
|
|
88
|
-
return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
|
|
89
|
-
}
|
|
90
|
-
catch {
|
|
91
|
-
return undefined;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
function createRequiredChildExtensionIdentity(requiredPaths) {
|
|
95
|
-
const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
|
|
96
|
-
const identities = new Set(aliases.values());
|
|
97
|
-
return (extensionPath) => {
|
|
98
|
-
const known = aliases.get(extensionPath);
|
|
99
|
-
if (known !== undefined)
|
|
100
|
-
return known;
|
|
101
|
-
const identity = childExtensionFileIdentity(extensionPath);
|
|
102
|
-
if (identity === undefined || !identities.has(identity))
|
|
103
|
-
return undefined;
|
|
104
|
-
// Retain the alias even if the extension removes its file before reporting a failure.
|
|
105
|
-
aliases.set(extensionPath, identity);
|
|
106
|
-
return identity;
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
84
|
/** The prompt runtime filters parent-only context before ambient extensions inspect
|
|
110
85
|
* the child prompt, and the boundary hook appends the child boundary after every
|
|
111
86
|
* extension has added its prompt sections. Every other extension keeps its order. */
|
|
@@ -591,7 +566,8 @@ export function createDefaultChildSessionFactory(options = {}) {
|
|
|
591
566
|
await session.bindExtensions({
|
|
592
567
|
mode: "print",
|
|
593
568
|
onError: (error) => {
|
|
594
|
-
|
|
569
|
+
// Pi's unconnected-MCP-server report means the server's tools are outside this child's tool contract, which the child can run without.
|
|
570
|
+
if (binding && error.event !== "register_mcp_server" && isRequiredSource(error.extensionPath))
|
|
595
571
|
requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
|
|
596
572
|
launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
|
|
597
573
|
},
|
|
@@ -53,6 +53,7 @@ export interface McpRuntimeSnapshotHost {
|
|
|
53
53
|
/** Pi 0.99: servers extensions added with `pi.registerMcpServer()`. */
|
|
54
54
|
getMcpServers?(): readonly {
|
|
55
55
|
name: string;
|
|
56
|
+
extensionPath: string;
|
|
56
57
|
}[];
|
|
57
58
|
}
|
|
58
59
|
/** A `pi.getAllTools()` entry; `exposure` and `namespace` exist only from Pi 0.99. */
|
|
@@ -76,8 +77,9 @@ export declare function resolveMcpDirectToolResolution(mcpDirectTools: string[]
|
|
|
76
77
|
export declare function formatUnresolvedBuiltinMcpSelectors(agentName: string | undefined, selectors: readonly string[]): string;
|
|
77
78
|
/**
|
|
78
79
|
* Selected servers that only an extension registered, which a child without ambient extensions
|
|
79
|
-
* never has
|
|
80
|
-
* the
|
|
80
|
+
* never has unless the registering extension is one the child loads (`loadedByChild`). A server of
|
|
81
|
+
* the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
|
|
82
|
+
* only when the project is trusted.
|
|
81
83
|
*/
|
|
82
|
-
export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean): string[];
|
|
84
|
+
export declare function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean, loadedByChild: (extensionPath: string) => boolean): string[];
|
|
83
85
|
export declare function computeMcpServerHash(definition: ServerEntry): string;
|
|
@@ -118,11 +118,12 @@ export function formatUnresolvedBuiltinMcpSelectors(agentName, selectors) {
|
|
|
118
118
|
}
|
|
119
119
|
/**
|
|
120
120
|
* Selected servers that only an extension registered, which a child without ambient extensions
|
|
121
|
-
* never has
|
|
122
|
-
* the
|
|
121
|
+
* never has unless the registering extension is one the child loads (`loadedByChild`). A server of
|
|
122
|
+
* the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
|
|
123
|
+
* only when the project is trusted.
|
|
123
124
|
*/
|
|
124
|
-
export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted) {
|
|
125
|
-
const registered = new Set(host.getMcpServers?.().map(({ name }) => name));
|
|
125
|
+
export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted, loadedByChild) {
|
|
126
|
+
const registered = new Set(host.getMcpServers?.().filter(({ extensionPath }) => !loadedByChild(extensionPath)).map(({ name }) => name));
|
|
126
127
|
const servers = [...new Set(selections.map(({ selector }) => selector.split("/")[0]))].filter((server) => registered.has(server));
|
|
127
128
|
if (servers.length === 0)
|
|
128
129
|
return [];
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare function installCompactionInterruptionCapture(sessionClass: {
|
|
2
|
+
prototype: object;
|
|
3
|
+
}): void;
|
|
4
|
+
/** A manual compaction of this session is in progress, until compact() returns. */
|
|
5
|
+
export declare function compactionInProgress(sessionManager: object): boolean;
|
|
6
|
+
/** A manual compaction of this session that aborted an active run is in progress. */
|
|
7
|
+
export declare function compactionInterruptedRun(sessionManager: object): boolean;
|
|
8
|
+
/** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
|
|
9
|
+
export declare function takeCompactionAbort(sessionManager: object): boolean;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Pi's manual compaction (/compact, RPC, ctx.compact()) aborts the active run before any hook runs, and its
|
|
2
|
+
// events do not say whether it interrupted one. Record that in AgentSession.compact, their shared entry point.
|
|
3
|
+
const stateSymbol = Symbol.for("pi-subagents.compaction-interruption.v1");
|
|
4
|
+
const wrappedSymbol = Symbol.for("pi-subagents.compaction-interruption.v1.wrapped");
|
|
5
|
+
// Shared with the wrapper an earlier extension instance installed before a reload.
|
|
6
|
+
const globalStore = globalThis;
|
|
7
|
+
const compactions = globalStore[stateSymbol] ??= new WeakMap();
|
|
8
|
+
export function installCompactionInterruptionCapture(sessionClass) {
|
|
9
|
+
const prototype = sessionClass.prototype;
|
|
10
|
+
const original = prototype.compact;
|
|
11
|
+
if (original[wrappedSymbol])
|
|
12
|
+
return;
|
|
13
|
+
const compact = async function (...args) {
|
|
14
|
+
const manager = this.sessionManager;
|
|
15
|
+
const compaction = compactions.get(manager) ?? { calls: 0, interrupted: false, abortPending: false };
|
|
16
|
+
compactions.set(manager, compaction);
|
|
17
|
+
compaction.calls += 1;
|
|
18
|
+
// Overlapping calls share the record: a later idle call must not erase an earlier interruption.
|
|
19
|
+
if (this.isStreaming)
|
|
20
|
+
compaction.interrupted = compaction.abortPending = true;
|
|
21
|
+
try {
|
|
22
|
+
return await original.apply(this, args);
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
if (--compaction.calls === 0)
|
|
26
|
+
compactions.delete(manager);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
compact[wrappedSymbol] = true;
|
|
30
|
+
prototype.compact = compact;
|
|
31
|
+
}
|
|
32
|
+
/** A manual compaction of this session is in progress, until compact() returns. */
|
|
33
|
+
export function compactionInProgress(sessionManager) {
|
|
34
|
+
return compactions.has(sessionManager);
|
|
35
|
+
}
|
|
36
|
+
/** A manual compaction of this session that aborted an active run is in progress. */
|
|
37
|
+
export function compactionInterruptedRun(sessionManager) {
|
|
38
|
+
return compactions.get(sessionManager)?.interrupted === true;
|
|
39
|
+
}
|
|
40
|
+
/** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
|
|
41
|
+
export function takeCompactionAbort(sessionManager) {
|
|
42
|
+
const compaction = compactions.get(sessionManager);
|
|
43
|
+
if (!compaction?.abortPending)
|
|
44
|
+
return false;
|
|
45
|
+
compaction.abortPending = false;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
@@ -10,6 +10,7 @@ export interface ParentWake {
|
|
|
10
10
|
* Returns true when the message was only appended (held, or another wake is already starting
|
|
11
11
|
* the run): Pi emits no extension message_start for it.
|
|
12
12
|
* After userAborted() and until the next run starts, a turn-triggering message is only appended.
|
|
13
|
+
* So it is during a manual compaction, which Pi does not guard against a new run; takeDeferredWake() reports it.
|
|
13
14
|
*/
|
|
14
15
|
sendMessage(...args: Parameters<ExtensionAPI["sendMessage"]>): boolean;
|
|
15
16
|
/** True from an idle wake until its run starts or the session shuts down. Past the deadline it holds only while the parent is busy, which may still be the wake's preflight (for example compacting). */
|
|
@@ -18,9 +19,9 @@ export interface ParentWake {
|
|
|
18
19
|
agentStarted(): void;
|
|
19
20
|
/** The user stopped the parent run: hold wakes until the next run starts. */
|
|
20
21
|
userAborted(): void;
|
|
21
|
-
/** A deliberate resume (manual compaction) drops the hold without touching the shared wake reservation. */
|
|
22
|
-
releaseHold(): void;
|
|
23
22
|
isHeld(): boolean;
|
|
23
|
+
/** True once if a wake was only appended because a manual compaction was in progress. */
|
|
24
|
+
takeDeferredWake(): boolean;
|
|
24
25
|
sessionShutdown(reason: string | undefined): void;
|
|
25
26
|
}
|
|
26
27
|
export declare function createParentWake(pi: Pick<ExtensionAPI, "sendMessage">, now?: () => number): ParentWake;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { compactionInProgress } from "./compaction-interruption.js";
|
|
1
2
|
/** Ends a waking notice that reports results. */
|
|
2
3
|
export const COMPLETION_ACTION = "Read the saved results above and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
|
|
3
4
|
/** Ends a waking notice that reports a problem or a run state rather than results. */
|
|
@@ -14,6 +15,7 @@ export function createParentWake(pi, now = Date.now) {
|
|
|
14
15
|
// Captured at bind: Pi's ctx throws once stale, which it can be by session_shutdown.
|
|
15
16
|
let session;
|
|
16
17
|
let held = false;
|
|
18
|
+
let deferred = false;
|
|
17
19
|
// Look the reservation up on every access: another extension may have created this session's entry.
|
|
18
20
|
const reservation = () => {
|
|
19
21
|
// Pi can shut an extension down before session_start binds it; an unbound wake reserved nothing.
|
|
@@ -42,6 +44,11 @@ export function createParentWake(pi, now = Date.now) {
|
|
|
42
44
|
pi.sendMessage(message, { triggerTurn: false });
|
|
43
45
|
return true;
|
|
44
46
|
}
|
|
47
|
+
if (session && compactionInProgress(session.manager)) {
|
|
48
|
+
deferred = true;
|
|
49
|
+
pi.sendMessage(message, { triggerTurn: false });
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
45
52
|
if (ctx.isIdle())
|
|
46
53
|
reservation().sentAt = now();
|
|
47
54
|
pi.sendMessage(message, options);
|
|
@@ -51,15 +58,19 @@ export function createParentWake(pi, now = Date.now) {
|
|
|
51
58
|
bindSession(context) {
|
|
52
59
|
ctx = context;
|
|
53
60
|
session = { manager: context.sessionManager, id: context.sessionManager.getSessionId() };
|
|
54
|
-
held = false;
|
|
61
|
+
held = deferred = false;
|
|
55
62
|
},
|
|
56
63
|
agentStarted() {
|
|
57
64
|
reservation().sentAt = undefined;
|
|
58
|
-
held = false;
|
|
65
|
+
held = deferred = false;
|
|
59
66
|
},
|
|
60
67
|
userAborted: () => { held = true; },
|
|
61
|
-
releaseHold: () => { held = false; },
|
|
62
68
|
isHeld: () => held,
|
|
69
|
+
takeDeferredWake() {
|
|
70
|
+
const wasDeferred = deferred;
|
|
71
|
+
deferred = false;
|
|
72
|
+
return wasDeferred;
|
|
73
|
+
},
|
|
63
74
|
sessionShutdown(reason) {
|
|
64
75
|
if (reason !== "reload")
|
|
65
76
|
reservation().sentAt = undefined;
|
|
@@ -28,6 +28,8 @@ export declare function assertRequiredChildExtensionsAdmitted(snapshots: Readonl
|
|
|
28
28
|
runnerType?: string;
|
|
29
29
|
machine?: string;
|
|
30
30
|
}): void;
|
|
31
|
+
/** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
|
|
32
|
+
export declare function createRequiredChildExtensionIdentity(requiredPaths: Iterable<string>): (extensionPath: string) => string | undefined;
|
|
31
33
|
export declare function hasMandatoryRequiredChildExtensions(snapshot: RequiredChildExtensionSnapshot | undefined): snapshot is RequiredChildExtensionSnapshot;
|
|
32
34
|
/** Persist a run's mandatory snapshot so append-step admits against it; writes nothing without a mandatory entry. */
|
|
33
35
|
export declare function writeRetainedRequiredChildExtensions(asyncDir: string, snapshot: RequiredChildExtensionSnapshot): void;
|
|
@@ -87,6 +87,33 @@ export function assertRequiredChildExtensionsAdmitted(snapshots, launch) {
|
|
|
87
87
|
if (route)
|
|
88
88
|
throw new Error(`Agent '${launch.agent}' cannot run on ${route}: the host requires child extensions (${ids.join(", ")}) for every runner, and only local native Pi children load them.`);
|
|
89
89
|
}
|
|
90
|
+
function childExtensionFileIdentity(extensionPath) {
|
|
91
|
+
if (!path.isAbsolute(extensionPath))
|
|
92
|
+
return undefined;
|
|
93
|
+
try {
|
|
94
|
+
const stat = fs.statSync(extensionPath, { bigint: true });
|
|
95
|
+
return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
|
|
102
|
+
export function createRequiredChildExtensionIdentity(requiredPaths) {
|
|
103
|
+
const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
|
|
104
|
+
const identities = new Set(aliases.values());
|
|
105
|
+
return (extensionPath) => {
|
|
106
|
+
const known = aliases.get(extensionPath);
|
|
107
|
+
if (known !== undefined)
|
|
108
|
+
return known;
|
|
109
|
+
const identity = childExtensionFileIdentity(extensionPath);
|
|
110
|
+
if (identity === undefined || !identities.has(identity))
|
|
111
|
+
return undefined;
|
|
112
|
+
// Retain the alias even if the extension removes its file before reporting a failure.
|
|
113
|
+
aliases.set(extensionPath, identity);
|
|
114
|
+
return identity;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
90
117
|
export function hasMandatoryRequiredChildExtensions(snapshot) {
|
|
91
118
|
return snapshot?.some((entry) => entry.requireForAllRunners) === true;
|
|
92
119
|
}
|
package/src/tui/fleet.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { type Component, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
2
|
+
import { type Component, type Focusable, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
|
|
3
3
|
import { type ExternalRun } from "../api/external-runs.ts";
|
|
4
4
|
import { type FleetKeybindingAction, type FleetKeybindingsConfig, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
|
|
5
5
|
import { type AsyncRunSummary } from "../runs/background/async-status.ts";
|
|
@@ -14,6 +14,7 @@ type FleetTui = {
|
|
|
14
14
|
rows: number;
|
|
15
15
|
};
|
|
16
16
|
requestRender(): void;
|
|
17
|
+
getFocusedComponent?(): Component | null;
|
|
17
18
|
};
|
|
18
19
|
type AsyncStep = AsyncRunSummary["steps"][number];
|
|
19
20
|
export type FleetItem = ({
|
|
@@ -108,7 +109,7 @@ export declare function collectFleetSnapshot(state: SubagentState, options?: {
|
|
|
108
109
|
resultsDir?: string;
|
|
109
110
|
limit?: number;
|
|
110
111
|
}): FleetSnapshot;
|
|
111
|
-
export declare class SubagentFleetComponent implements Component {
|
|
112
|
+
export declare class SubagentFleetComponent implements Component, Focusable {
|
|
112
113
|
private snapshot;
|
|
113
114
|
private selected;
|
|
114
115
|
private selectedKey;
|
|
@@ -125,6 +126,8 @@ export declare class SubagentFleetComponent implements Component {
|
|
|
125
126
|
private actionBusy;
|
|
126
127
|
private transcriptCache;
|
|
127
128
|
private disposed;
|
|
129
|
+
private hasFocus;
|
|
130
|
+
private readonly openedOver;
|
|
128
131
|
private refreshTimer;
|
|
129
132
|
private readonly refreshMs;
|
|
130
133
|
private readonly tui;
|
|
@@ -154,6 +157,8 @@ export declare class SubagentFleetComponent implements Component {
|
|
|
154
157
|
private setActionNotice;
|
|
155
158
|
private runAction;
|
|
156
159
|
private scrollDetail;
|
|
160
|
+
get focused(): boolean;
|
|
161
|
+
set focused(value: boolean);
|
|
157
162
|
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined;
|
|
158
163
|
handleInput(data: string): void;
|
|
159
164
|
private rosterLines;
|
package/src/tui/fleet.js
CHANGED
|
@@ -770,6 +770,10 @@ export class SubagentFleetComponent {
|
|
|
770
770
|
actionBusy = false;
|
|
771
771
|
transcriptCache;
|
|
772
772
|
disposed = false;
|
|
773
|
+
// Undefined until a TUI first focuses the overlay, so a fleet rendered outside one still draws.
|
|
774
|
+
hasFocus;
|
|
775
|
+
// The component focused when the fleet opened (the overlay's preFocus).
|
|
776
|
+
openedOver;
|
|
773
777
|
refreshTimer;
|
|
774
778
|
refreshMs;
|
|
775
779
|
tui;
|
|
@@ -781,6 +785,7 @@ export class SubagentFleetComponent {
|
|
|
781
785
|
keybindings;
|
|
782
786
|
constructor(tui, theme, state, done, options = {}) {
|
|
783
787
|
this.tui = tui;
|
|
788
|
+
this.openedOver = tui.getFocusedComponent?.();
|
|
784
789
|
this.viewport = new FleetViewport(() => this.tui.requestRender());
|
|
785
790
|
this.theme = theme;
|
|
786
791
|
this.markdownTheme = options.markdownTheme ?? getMarkdownTheme();
|
|
@@ -984,6 +989,15 @@ export class SubagentFleetComponent {
|
|
|
984
989
|
scrollDetail(delta) {
|
|
985
990
|
this.viewport.scroll.scrollBy(delta);
|
|
986
991
|
}
|
|
992
|
+
get focused() {
|
|
993
|
+
return this.hasFocus === true;
|
|
994
|
+
}
|
|
995
|
+
set focused(value) {
|
|
996
|
+
if (value === this.hasFocus)
|
|
997
|
+
return;
|
|
998
|
+
this.hasFocus = value;
|
|
999
|
+
this.tui.requestRender();
|
|
1000
|
+
}
|
|
987
1001
|
handleMouse(event) {
|
|
988
1002
|
// Block pointer fallback as well as inspector actions while a text/confirmation modal owns input.
|
|
989
1003
|
if (this.steerDraft !== undefined || this.redoGuidanceDraft !== undefined || this.stopConfirming || this.actionBusy) {
|
|
@@ -1339,6 +1353,14 @@ export class SubagentFleetComponent {
|
|
|
1339
1353
|
return { header: [], body: this.withActionLines(lines) };
|
|
1340
1354
|
}
|
|
1341
1355
|
render(width) {
|
|
1356
|
+
// An inline dialog that took focus (a permission prompt, select, confirm) sits under this overlay and
|
|
1357
|
+
// would be covered while it owns the keys. Hiding the overlay through its handle would cancel the
|
|
1358
|
+
// TUI's focus restore, so draw nothing until the TUI gives focus back. Focus moving to the component the
|
|
1359
|
+
// fleet opened over (a fullscreen click on the editor) shows no dialog, and the next key returns to the fleet.
|
|
1360
|
+
if (this.hasFocus === false && this.tui.getFocusedComponent?.() !== this.openedOver) {
|
|
1361
|
+
this.renderedLayout = undefined;
|
|
1362
|
+
return [];
|
|
1363
|
+
}
|
|
1342
1364
|
const layout = fleetLayout(width, this.tui.terminal?.rows ?? 32, this.selected, this.snapshot.items);
|
|
1343
1365
|
this.renderedLayout = layout;
|
|
1344
1366
|
if (!layout)
|