oira666_pi-subagent 0.7.13 → 0.7.16
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/README.md +17 -0
- package/broker/root.ts +2 -1
- package/budget.ts +10 -1
- package/docs/configuration.md +6 -6
- package/docs/sessions.md +6 -7
- package/docs/usage.md +1 -1
- package/extension/async-jobs.ts +2 -1
- package/extension/broker-jobs.ts +2 -1
- package/extension/completion.ts +4 -2
- package/extension/events.ts +8 -25
- package/extension/interrupt.ts +24 -17
- package/extension/launch-budgets.ts +84 -0
- package/extension/launch-tool.ts +20 -46
- package/extension/progress.ts +2 -1
- package/extension/provider.ts +3 -14
- package/extension/reload-handoff.ts +139 -0
- package/extension/resume-offer.ts +28 -46
- package/extension/runtime.ts +31 -3
- package/extension/scheduler.ts +2 -1
- package/extension/session-start.ts +79 -36
- package/extension/settings-commands.ts +9 -19
- package/extension/state.ts +16 -1
- package/index.ts +3 -1
- package/package.json +3 -1
- package/resume-slots.ts +108 -0
- package/resume-tail.ts +86 -0
- package/resume.ts +98 -160
- package/settings.ts +0 -1
- package/startup.js +611 -384
- package/storage/process-registry.ts +20 -0
- package/storage/stopped-workers.ts +3 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { RUNTIME_PROTOCOL } from "../storage/process-registry.js";
|
|
3
|
+
import { isRecord } from "./contracts.js";
|
|
4
|
+
import { createExtensionState, type ExtensionState, type ReloadHandoff } from "./state.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A Pi reload keeps the process but replaces this extension instance. Live workers stay owned by
|
|
8
|
+
* the same ExtensionState object, which their callbacks already reference: the old instance parks
|
|
9
|
+
* it here and the reloaded instance rebinds it to its own Pi API. The slot's top-level fields are
|
|
10
|
+
* read by every release, so an incompatible newer release can still stop the old work.
|
|
11
|
+
*/
|
|
12
|
+
const SLOT = Symbol.for("pi-subagent.reload-handoff");
|
|
13
|
+
const ADOPTION_TIMEOUT_MS = 60_000;
|
|
14
|
+
|
|
15
|
+
interface HandoffSlot {
|
|
16
|
+
protocol: unknown;
|
|
17
|
+
pid: unknown;
|
|
18
|
+
state: unknown;
|
|
19
|
+
stop: () => Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function takeSlot(): HandoffSlot | undefined {
|
|
23
|
+
const value: unknown = Reflect.get(globalThis, SLOT);
|
|
24
|
+
Reflect.deleteProperty(globalThis, SLOT);
|
|
25
|
+
if (!isRecord(value)) return undefined;
|
|
26
|
+
const stop = value.stop;
|
|
27
|
+
if (typeof stop !== "function") return undefined;
|
|
28
|
+
return {
|
|
29
|
+
protocol: value.protocol,
|
|
30
|
+
pid: value.pid,
|
|
31
|
+
state: value.state,
|
|
32
|
+
stop: async () => {
|
|
33
|
+
await Reflect.apply(stop, value, []);
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function stopQuietly(stop: () => Promise<void>): void {
|
|
39
|
+
stop().catch((error: unknown) => console.error("[pi-subagent] Failed to stop work left by a reload:", error));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Old instance: keep live work running and offer it to the reloaded instance. */
|
|
43
|
+
export function publishReloadHandoff(
|
|
44
|
+
state: ExtensionState,
|
|
45
|
+
teardown: () => Promise<void>,
|
|
46
|
+
timeoutMs = ADOPTION_TIMEOUT_MS,
|
|
47
|
+
): void {
|
|
48
|
+
// A second unclaimed reload must not orphan the first one's work.
|
|
49
|
+
const previous = takeSlot();
|
|
50
|
+
if (previous) stopQuietly(previous.stop);
|
|
51
|
+
let stopping: Promise<void> | undefined;
|
|
52
|
+
const handoff: ReloadHandoff = {
|
|
53
|
+
sessionId: state.currentSessionId,
|
|
54
|
+
queue: [],
|
|
55
|
+
release: () => {
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
process.off("exit", onExit);
|
|
58
|
+
},
|
|
59
|
+
stop: () =>
|
|
60
|
+
(stopping ??= (async () => {
|
|
61
|
+
handoff.release();
|
|
62
|
+
if (state.reloadHandoff === handoff) state.reloadHandoff = undefined;
|
|
63
|
+
const slot: unknown = Reflect.get(globalThis, SLOT);
|
|
64
|
+
if (isRecord(slot) && slot.state === state) Reflect.deleteProperty(globalThis, SLOT);
|
|
65
|
+
await teardown();
|
|
66
|
+
})()),
|
|
67
|
+
};
|
|
68
|
+
// No adoption (failed reload, disabled or incompatible new instance) falls back to a normal shutdown.
|
|
69
|
+
const timer = setTimeout(() => stopQuietly(handoff.stop), timeoutMs);
|
|
70
|
+
timer.unref();
|
|
71
|
+
const onExit = () => stopQuietly(handoff.stop);
|
|
72
|
+
process.once("exit", onExit);
|
|
73
|
+
state.reloadHandoff = handoff;
|
|
74
|
+
Reflect.set(globalThis, SLOT, { protocol: RUNTIME_PROTOCOL, pid: process.pid, state, stop: handoff.stop });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isHandedOffState(value: unknown): value is ExtensionState {
|
|
78
|
+
return (
|
|
79
|
+
isRecord(value) &&
|
|
80
|
+
isRecord(value.reloadHandoff) &&
|
|
81
|
+
value.backgroundJobs instanceof Map &&
|
|
82
|
+
value.activeSubagents instanceof Map &&
|
|
83
|
+
typeof value.lifecycleGeneration === "number"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Keep live work and session identity; everything else is rebuilt as for a fresh instance. */
|
|
88
|
+
function rebindState(previous: ExtensionState, pi: ExtensionAPI): ExtensionState {
|
|
89
|
+
const fresh = createExtensionState(pi);
|
|
90
|
+
const live: Partial<ExtensionState> = {
|
|
91
|
+
reloadHandoff: previous.reloadHandoff,
|
|
92
|
+
backgroundJobs: previous.backgroundJobs,
|
|
93
|
+
pendingCompletionDeliveries: previous.pendingCompletionDeliveries,
|
|
94
|
+
pendingCompletionInterrupts: previous.pendingCompletionInterrupts,
|
|
95
|
+
interruptEpoch: previous.interruptEpoch,
|
|
96
|
+
lifecycleGeneration: previous.lifecycleGeneration,
|
|
97
|
+
scheduledTasks: previous.scheduledTasks,
|
|
98
|
+
activeSubagents: previous.activeSubagents,
|
|
99
|
+
activeResumeNames: previous.activeResumeNames,
|
|
100
|
+
activeSubagentUsageSummaries: previous.activeSubagentUsageSummaries,
|
|
101
|
+
latestBroadcastTargets: previous.latestBroadcastTargets,
|
|
102
|
+
nextActiveSubagentId: previous.nextActiveSubagentId,
|
|
103
|
+
currentSessionId: previous.currentSessionId,
|
|
104
|
+
currentSubagentSessionRoot: previous.currentSubagentSessionRoot,
|
|
105
|
+
currentNamesFile: previous.currentNamesFile,
|
|
106
|
+
currentOwnerId: previous.currentOwnerId,
|
|
107
|
+
currentBudget: previous.currentBudget,
|
|
108
|
+
};
|
|
109
|
+
for (const key of Object.keys(previous)) Reflect.deleteProperty(previous, key);
|
|
110
|
+
return Object.assign(previous, fresh, live);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** New instance, at load: reuse a compatible handed-off state, or stop work it cannot drive. */
|
|
114
|
+
export function claimReloadHandoff(pi: ExtensionAPI): ExtensionState | undefined {
|
|
115
|
+
const slot = takeSlot();
|
|
116
|
+
if (!slot) return undefined;
|
|
117
|
+
if (slot.protocol !== RUNTIME_PROTOCOL || slot.pid !== process.pid || !isHandedOffState(slot.state)) {
|
|
118
|
+
stopQuietly(slot.stop);
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
return rebindState(slot.state, pi);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* New instance, at session_start: adopt only a reload of the same session and return the buffered
|
|
126
|
+
* work to replay. Synchronous, so no completion can slip between the hand-off and the new binding.
|
|
127
|
+
* Any other hand-off stays on the state for the caller to stop.
|
|
128
|
+
*/
|
|
129
|
+
export function adoptReloadHandoff(
|
|
130
|
+
state: ExtensionState,
|
|
131
|
+
reason: string,
|
|
132
|
+
sessionId: string,
|
|
133
|
+
): Array<() => void> | undefined {
|
|
134
|
+
const handoff = state.reloadHandoff;
|
|
135
|
+
if (!handoff || reason !== "reload" || sessionId !== handoff.sessionId) return undefined;
|
|
136
|
+
state.reloadHandoff = undefined;
|
|
137
|
+
handoff.release();
|
|
138
|
+
return handoff.queue;
|
|
139
|
+
}
|
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { findLatestResumableSubagentCalls, parseBooleanEnv, SUBAGENT_RESUME_PROMPT_ENV } from "../resume.js";
|
|
1
|
+
import { findLatestResumableSubagentCalls, recoveryWorkerLabels } from "../resume.js";
|
|
3
2
|
import { RESUME_MODEL_ID, RESUME_PROVIDER } from "../shared.js";
|
|
4
3
|
import type { SessionContext } from "./contracts.js";
|
|
5
|
-
import { getRestorableModel,
|
|
4
|
+
import { getRestorableModel, SUBAGENT_FALLBACK_MODEL_ENV } from "./models.js";
|
|
6
5
|
import { ensureSubagentToolActive, hasCliInitialPrompt, isRpcMode } from "./policy.js";
|
|
7
|
-
import { restoreModelAfterResumeFailure
|
|
6
|
+
import { restoreModelAfterResumeFailure } from "./runtime.js";
|
|
8
7
|
import type { ExtensionState } from "./state.js";
|
|
9
8
|
|
|
10
|
-
export async function maybeOfferSubagentResume(
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
): Promise<void> {
|
|
9
|
+
export async function maybeOfferSubagentResume(state: ExtensionState, ctx: SessionContext): Promise<void> {
|
|
10
|
+
// Recovery requires an explicit yes. Print/JSON modes and parent-owned
|
|
11
|
+
// RPC workers have no human dialog responder. Top-level RPC clients can ask.
|
|
12
|
+
if (!ctx.hasUI || state.currentDepth > 0) return;
|
|
15
13
|
const generation = state.lifecycleGeneration;
|
|
16
14
|
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
17
|
-
const
|
|
15
|
+
const resumeEpoch = state.resumeEpoch ?? 0;
|
|
16
|
+
const canceled = () =>
|
|
17
|
+
generation !== state.lifecycleGeneration ||
|
|
18
|
+
interruptEpoch !== (state.interruptEpoch ?? 0) ||
|
|
19
|
+
resumeEpoch !== (state.resumeEpoch ?? 0);
|
|
18
20
|
const restorableModel = getRestorableModel(ctx, state.settings);
|
|
19
21
|
if (restorableModel) {
|
|
20
22
|
state.lastRestorableModel = restorableModel;
|
|
@@ -25,17 +27,16 @@ export async function maybeOfferSubagentResume(
|
|
|
25
27
|
if (plans.length === 0) return;
|
|
26
28
|
const totalTaskCount = plans.reduce((sum, plan) => sum + plan.tasks.length, 0);
|
|
27
29
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
30
|
+
const shouldResume = await ctx.ui.confirm(
|
|
31
|
+
"Resume subagents?",
|
|
32
|
+
`Resume ${totalTaskCount} interrupted subagent${totalTaskCount === 1 ? "" : "s"} from saved sessions?\n\n${recoveryWorkerLabels(
|
|
33
|
+
plans,
|
|
34
|
+
)
|
|
35
|
+
.map((label) => `- ${label}`)
|
|
36
|
+
.join("\n")}`,
|
|
37
|
+
);
|
|
37
38
|
if (canceled()) return;
|
|
38
|
-
if (
|
|
39
|
+
if (shouldResume !== true) {
|
|
39
40
|
if (ctx.model?.provider === RESUME_PROVIDER) {
|
|
40
41
|
if (restorableModel) {
|
|
41
42
|
await state.pi.setModel(restorableModel);
|
|
@@ -60,12 +61,9 @@ export async function maybeOfferSubagentResume(
|
|
|
60
61
|
state.pendingResumePlans = [...plans];
|
|
61
62
|
state.resumeState.plans = [...plans];
|
|
62
63
|
state.resumeState.phase = "tool";
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
// request. Interactive top-level sessions keep using a visible prompt so
|
|
67
|
-
// the user sees exactly what is happening.
|
|
68
|
-
const injectOnNextRequest = rpcMode || hasCliInitialPrompt(process.argv) || !ctx.hasUI;
|
|
64
|
+
// After approval, RPC/CLI prompts use the next request rather than
|
|
65
|
+
// inserting an extra user message ahead of their initial prompt.
|
|
66
|
+
const injectOnNextRequest = isRpcMode(process.argv) || hasCliInitialPrompt(process.argv);
|
|
69
67
|
state.resumeState.trigger = injectOnNextRequest ? "nextRequest" : "resumePrompt";
|
|
70
68
|
state.modelToRestoreAfterResume = restorableModel ?? ctx.model;
|
|
71
69
|
state.resumeModelRegistry = ctx.modelRegistry;
|
|
@@ -82,32 +80,16 @@ export async function maybeOfferSubagentResume(
|
|
|
82
80
|
return;
|
|
83
81
|
}
|
|
84
82
|
|
|
85
|
-
//
|
|
86
|
-
//
|
|
87
|
-
// a real assistant subagent tool call. In interactive mode, submit a short
|
|
88
|
-
// visible prompt that triggers the same synthetic provider path.
|
|
83
|
+
// An initial CLI/RPC prompt triggers the approved tool call on its next
|
|
84
|
+
// request. Otherwise queue a visible prompt after the initial chat render.
|
|
89
85
|
if (injectOnNextRequest) {
|
|
90
|
-
|
|
91
|
-
} else
|
|
86
|
+
ctx.ui.notify(`Resuming ${totalTaskCount} subagents...`, "info");
|
|
87
|
+
} else {
|
|
92
88
|
// Do not start the synthetic resume turn from session_start. Pi renders
|
|
93
89
|
// the resumed chat only after session_start/resources_discover complete;
|
|
94
90
|
// starting now lets that render wipe out the live tool component, so no
|
|
95
91
|
// real-time updates appear. Queue it for resources_discover instead,
|
|
96
92
|
// which is the last extension hook before the initial chat render.
|
|
97
93
|
state.pendingInteractiveResumePrompt = `Resuming ${totalTaskCount} subagents...`;
|
|
98
|
-
} else {
|
|
99
|
-
scheduleSessionTask(
|
|
100
|
-
state,
|
|
101
|
-
() => {
|
|
102
|
-
try {
|
|
103
|
-
sendAutomaticResumePrompt(state, `Resuming ${totalTaskCount} subagents...`);
|
|
104
|
-
} catch (err) {
|
|
105
|
-
console.error("[pi-subagent] Failed to start resume turn after tree navigation:", err);
|
|
106
|
-
void restoreModelAfterResumeFailure(state, ctx);
|
|
107
|
-
}
|
|
108
|
-
},
|
|
109
|
-
RESUME_INTERACTIVE_DELAY_MS,
|
|
110
|
-
true,
|
|
111
|
-
);
|
|
112
94
|
}
|
|
113
95
|
}
|
package/extension/runtime.ts
CHANGED
|
@@ -39,25 +39,53 @@ export function getParentModelForSubagent(state: ExtensionState, ctx: SessionCon
|
|
|
39
39
|
);
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/** During a reload hand-off no session is bound yet. Queue session work for the adopting instance. */
|
|
43
|
+
export function deferDuringReload(state: ExtensionState, generation: number, run: () => void): boolean {
|
|
44
|
+
const handoff = state.reloadHandoff;
|
|
45
|
+
if (state.sessionActive || !handoff || generation !== state.lifecycleGeneration) return false;
|
|
46
|
+
handoff.queue.push(run);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Durable tasks deliver worker results. They survive a reload hand-off; other tasks may hold a stale ctx.
|
|
51
|
+
const durableTasks = new WeakSet<object>();
|
|
52
|
+
|
|
42
53
|
export function scheduleSessionTask(
|
|
43
54
|
state: ExtensionState,
|
|
44
55
|
callback: () => void,
|
|
45
56
|
delayMs: number,
|
|
46
57
|
cancelOnInterrupt = false,
|
|
58
|
+
durable = false,
|
|
47
59
|
): void {
|
|
48
60
|
const expectedGeneration = state.lifecycleGeneration;
|
|
49
61
|
const interruptEpoch = state.interruptEpoch ?? 0;
|
|
50
|
-
const
|
|
51
|
-
state.scheduledTasks.delete(timer);
|
|
62
|
+
const run = () => {
|
|
52
63
|
if (!state.sessionActive || expectedGeneration !== state.lifecycleGeneration) return;
|
|
53
64
|
if (cancelOnInterrupt && interruptEpoch !== (state.interruptEpoch ?? 0)) return;
|
|
54
65
|
callback();
|
|
66
|
+
};
|
|
67
|
+
const timer = setTimeout(() => {
|
|
68
|
+
state.scheduledTasks.delete(timer);
|
|
69
|
+
if (!durable || !deferDuringReload(state, expectedGeneration, run)) run();
|
|
55
70
|
}, delayMs);
|
|
71
|
+
if (durable) durableTasks.add(timer);
|
|
56
72
|
state.scheduledTasks.add(timer);
|
|
57
73
|
}
|
|
58
74
|
|
|
75
|
+
export function clearSessionTasks(state: ExtensionState, keepDurable = false): void {
|
|
76
|
+
for (const timer of state.scheduledTasks) {
|
|
77
|
+
if (keepDurable && durableTasks.has(timer)) continue;
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
state.scheduledTasks.delete(timer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
59
83
|
export function sendAutomaticResumePrompt(state: ExtensionState, prompt: string): void {
|
|
60
|
-
state.pendingAutomaticResume = {
|
|
84
|
+
state.pendingAutomaticResume = {
|
|
85
|
+
prompt,
|
|
86
|
+
interruptEpoch: state.interruptEpoch ?? 0,
|
|
87
|
+
resumeEpoch: state.resumeEpoch ?? 0,
|
|
88
|
+
};
|
|
61
89
|
state.pi.sendUserMessage(prompt, { deliverAs: "steer" });
|
|
62
90
|
}
|
|
63
91
|
|
package/extension/scheduler.ts
CHANGED
|
@@ -12,10 +12,11 @@ import {
|
|
|
12
12
|
import type { ExtensionState } from "./state.js";
|
|
13
13
|
import { BROKER_DIR_ENV, BROKER_SECRET_ENV } from "../broker/contracts.js";
|
|
14
14
|
import { createRootBroker, shutdownRootBroker } from "../broker/root.js";
|
|
15
|
+
import { processRegistry } from "../storage/process-registry.js";
|
|
15
16
|
|
|
16
17
|
export { WorkerScheduler } from "../runner/worker-scheduler.js";
|
|
17
18
|
export type { WorkerStatus, WorkerTicket } from "../runner/worker-scheduler.js";
|
|
18
|
-
const schedulers = new WeakMap<ExtensionState, WorkerScheduler>();
|
|
19
|
+
const schedulers = processRegistry("schedulers", () => new WeakMap<ExtensionState, WorkerScheduler>());
|
|
19
20
|
|
|
20
21
|
/** Descendants inherit the root ledger. Their personal concurrency settings cannot change its cap. */
|
|
21
22
|
export function schedulerFor(state: ExtensionState): WorkerScheduler {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { stopBackgroundJobs } from "./async-jobs.js";
|
|
2
|
-
import { shutdownScheduler, treeStoreFor } from "./scheduler.js";
|
|
2
|
+
import { cachedSchedulerFor, shutdownScheduler, treeStoreFor } from "./scheduler.js";
|
|
3
|
+
import { adoptReloadHandoff, publishReloadHandoff } from "./reload-handoff.js";
|
|
3
4
|
import { detachBrokerJobs, restoreBrokerJobs } from "./broker-jobs.js";
|
|
4
5
|
import { WORKER_TOKEN_ENV } from "../storage/tree-concurrency.js";
|
|
5
6
|
import { loadPiSubagentsConfig } from "../config.js";
|
|
@@ -33,21 +34,37 @@ import { isSubagentToolName, STOP_SUBAGENT_TOOL_NAME } from "../types.js";
|
|
|
33
34
|
import { getRestorableModel } from "./models.js";
|
|
34
35
|
import { ensureSubagentToolActive, filterAgentsForPrompt } from "./policy.js";
|
|
35
36
|
import { maybeOfferSubagentResume } from "./resume-offer.js";
|
|
36
|
-
import {
|
|
37
|
+
import {
|
|
38
|
+
clearSessionTasks,
|
|
39
|
+
clearSyntheticResumeState,
|
|
40
|
+
restoreModelAfterResumeFailure,
|
|
41
|
+
scheduleSessionTask,
|
|
42
|
+
updateCombinedUsageStatus,
|
|
43
|
+
} from "./runtime.js";
|
|
37
44
|
import type { ExtensionState } from "./state.js";
|
|
38
45
|
|
|
39
46
|
export function registerSessionLifecycle(state: ExtensionState): void {
|
|
40
47
|
state.pi.on("session_start", async (event, ctx) => {
|
|
48
|
+
const replay = adoptReloadHandoff(state, event.reason, ctx.sessionManager.getSessionId?.() ?? "ephemeral");
|
|
49
|
+
if (replay) {
|
|
50
|
+
// Same session, same generation: workers handed off by the previous instance stay valid.
|
|
51
|
+
state.sessionActive = true;
|
|
52
|
+
state.latestSessionCtx = ctx;
|
|
53
|
+
scheduleSessionTask(state, () => replay.forEach((run) => run()), 0);
|
|
54
|
+
}
|
|
41
55
|
if (state.currentBudget) clearSessionBudgetLimit(state.currentBudget);
|
|
42
56
|
state.sessionSettings = {};
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
57
|
+
if (!replay) {
|
|
58
|
+
await state.reloadHandoff?.stop();
|
|
59
|
+
state.sessionActive = false;
|
|
60
|
+
state.lifecycleGeneration += 1;
|
|
61
|
+
state.pendingCompletionDeliveries.clear();
|
|
62
|
+
state.pendingCompletionInterrupts.clear();
|
|
63
|
+
await shutdownScheduler(state);
|
|
64
|
+
await stopBackgroundJobs(state);
|
|
65
|
+
state.sessionActive = true;
|
|
66
|
+
state.latestSessionCtx = ctx;
|
|
67
|
+
}
|
|
51
68
|
// Record this invocation before its first user message, including on leaf workers.
|
|
52
69
|
// Null clears the label on a resume that uses no preset. Do not rewrite earlier entries.
|
|
53
70
|
const runIntelligence = process.env[SUBAGENT_RUN_INTELLIGENCE_ENV];
|
|
@@ -210,14 +227,14 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
210
227
|
const resumeDisabled = parseBooleanEnv(configuredEnv(SUBAGENT_RESUME_DISABLE_ENV, state.settings)) === true;
|
|
211
228
|
if (!state.canDelegate || resumeDisabled || (event.reason !== "resume" && event.reason !== "startup")) return;
|
|
212
229
|
|
|
213
|
-
await maybeOfferSubagentResume(state, ctx
|
|
230
|
+
await maybeOfferSubagentResume(state, ctx);
|
|
214
231
|
} catch (err) {
|
|
215
232
|
console.error("[pi-subagent] Error in session_start:", err);
|
|
216
233
|
await restoreModelAfterResumeFailure(state, ctx);
|
|
217
234
|
}
|
|
218
235
|
});
|
|
219
236
|
|
|
220
|
-
state.pi.on("session_shutdown", async () => {
|
|
237
|
+
state.pi.on("session_shutdown", async (event) => {
|
|
221
238
|
const token = process.env[WORKER_TOKEN_ENV];
|
|
222
239
|
let parking = false;
|
|
223
240
|
try {
|
|
@@ -225,30 +242,56 @@ export function registerSessionLifecycle(state: ExtensionState): void {
|
|
|
225
242
|
} catch {
|
|
226
243
|
/* An unreadable ledger must not detach work without a confirmed parking request. */
|
|
227
244
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
await shutdownScheduler(state);
|
|
235
|
-
await stopBackgroundJobs(state);
|
|
245
|
+
if (!parking && event.reason === "reload" && hasLiveWork(state)) {
|
|
246
|
+
state.sessionActive = false;
|
|
247
|
+
clearSessionTasks(state, true);
|
|
248
|
+
unbindSession(state, false);
|
|
249
|
+
publishReloadHandoff(state, () => teardownSession(state, false));
|
|
250
|
+
return;
|
|
236
251
|
}
|
|
237
|
-
|
|
238
|
-
state.scheduledTasks.clear();
|
|
239
|
-
clearSyntheticResumeState(state);
|
|
240
|
-
state.pendingResumePlans = [];
|
|
241
|
-
state.pendingInteractiveResumePrompt = null;
|
|
242
|
-
state.modelToRestoreAfterResume = undefined;
|
|
243
|
-
state.latestSessionCtx = undefined;
|
|
244
|
-
state.resumeModelRegistry = undefined;
|
|
245
|
-
state.activeSubagentUsageSummaries.clear();
|
|
246
|
-
state.forcedErrorToolCallIds.clear();
|
|
247
|
-
state.activeSubagents.clear();
|
|
248
|
-
state.activeResumeNames.clear();
|
|
249
|
-
state.approvedProjectAgentDirsForSession.clear();
|
|
250
|
-
state.latestBroadcastTargets.all = [];
|
|
251
|
-
state.latestBroadcastTargets.youngest = [];
|
|
252
|
-
clearRenderCaches();
|
|
252
|
+
await teardownSession(state, parking);
|
|
253
253
|
});
|
|
254
254
|
}
|
|
255
|
+
|
|
256
|
+
/** Work a reload hands off. Worker processes keep running their old code; their next resume uses the new code. */
|
|
257
|
+
function hasLiveWork(state: ExtensionState): boolean {
|
|
258
|
+
return !!(
|
|
259
|
+
state.backgroundJobs.size ||
|
|
260
|
+
state.activeSubagents.size ||
|
|
261
|
+
state.pendingCompletionDeliveries.size ||
|
|
262
|
+
cachedSchedulerFor(state)?.snapshot().length
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function teardownSession(state: ExtensionState, parking: boolean): Promise<void> {
|
|
267
|
+
state.sessionActive = false;
|
|
268
|
+
state.lifecycleGeneration += 1;
|
|
269
|
+
state.pendingCompletionDeliveries.clear();
|
|
270
|
+
state.pendingCompletionInterrupts.clear();
|
|
271
|
+
if (parking) detachBrokerJobs(state);
|
|
272
|
+
else {
|
|
273
|
+
await shutdownScheduler(state);
|
|
274
|
+
await stopBackgroundJobs(state);
|
|
275
|
+
}
|
|
276
|
+
clearSessionTasks(state);
|
|
277
|
+
unbindSession(state, true);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Drop session bindings. A reload hand-off keeps the live worker records. */
|
|
281
|
+
function unbindSession(state: ExtensionState, dropWorkers: boolean): void {
|
|
282
|
+
clearSyntheticResumeState(state);
|
|
283
|
+
state.pendingResumePlans = [];
|
|
284
|
+
state.pendingInteractiveResumePrompt = null;
|
|
285
|
+
state.modelToRestoreAfterResume = undefined;
|
|
286
|
+
state.latestSessionCtx = undefined;
|
|
287
|
+
state.resumeModelRegistry = undefined;
|
|
288
|
+
state.forcedErrorToolCallIds.clear();
|
|
289
|
+
state.approvedProjectAgentDirsForSession.clear();
|
|
290
|
+
clearRenderCaches();
|
|
291
|
+
if (!dropWorkers) return;
|
|
292
|
+
state.activeSubagentUsageSummaries.clear();
|
|
293
|
+
state.activeSubagents.clear();
|
|
294
|
+
state.activeResumeNames.clear();
|
|
295
|
+
state.latestBroadcastTargets.all = [];
|
|
296
|
+
state.latestBroadcastTargets.youngest = [];
|
|
297
|
+
}
|
|
@@ -61,26 +61,15 @@ export const SESSION_CONTROLS: Control[] = [
|
|
|
61
61
|
{
|
|
62
62
|
name: "auto-resume",
|
|
63
63
|
env: "PI_SUBAGENT_DISABLE_RESUME",
|
|
64
|
-
description: "
|
|
64
|
+
description: "Offer to recover interrupted workers when opening a session, always after confirmation",
|
|
65
65
|
choiceHints: {
|
|
66
|
-
on: "
|
|
66
|
+
on: "Ask yes or no when opening a session; never recover on tree navigation",
|
|
67
67
|
off: "Do not automatically recover unfinished tasks; named resumes still work",
|
|
68
68
|
},
|
|
69
69
|
defaultValue: "false",
|
|
70
70
|
choices: ["on", "off"],
|
|
71
71
|
inverted: true,
|
|
72
72
|
},
|
|
73
|
-
{
|
|
74
|
-
name: "resume-prompt",
|
|
75
|
-
env: "PI_SUBAGENT_RESUME_PROMPT",
|
|
76
|
-
description: "Ask before recovering unfinished tasks; off continues without asking, not without recovery",
|
|
77
|
-
choiceHints: {
|
|
78
|
-
on: "Ask before recovery in the interactive terminal",
|
|
79
|
-
off: "Recover without asking; use auto-resume off to disable recovery",
|
|
80
|
-
},
|
|
81
|
-
defaultValue: "true",
|
|
82
|
-
choices: ["on", "off"],
|
|
83
|
-
},
|
|
84
73
|
{
|
|
85
74
|
name: "intelligence",
|
|
86
75
|
env: "PI_SUBAGENT_INTELLIGENCE",
|
|
@@ -154,15 +143,11 @@ function applySettings(state: ExtensionState, ctx: ExtensionCommandContext): voi
|
|
|
154
143
|
updateCombinedUsageStatus(state, ctx);
|
|
155
144
|
}
|
|
156
145
|
|
|
157
|
-
function editable(state: ExtensionState, ctx: ExtensionCommandContext
|
|
146
|
+
function editable(state: ExtensionState, ctx: ExtensionCommandContext): boolean {
|
|
158
147
|
if (state.currentDepth > 0) {
|
|
159
148
|
ctx.ui.notify("Change session settings in the main session, not in a child with an inherited grant.", "warning");
|
|
160
149
|
return false;
|
|
161
150
|
}
|
|
162
|
-
if (!allowBusy && !ctx.isIdle()) {
|
|
163
|
-
ctx.ui.notify("Wait for the current assistant turn to finish before changing settings.", "warning");
|
|
164
|
-
return false;
|
|
165
|
-
}
|
|
166
151
|
return true;
|
|
167
152
|
}
|
|
168
153
|
|
|
@@ -217,7 +202,12 @@ export function registerSettingsCommands(state: ExtensionState): void {
|
|
|
217
202
|
return;
|
|
218
203
|
}
|
|
219
204
|
const liveLimit = control.name === "max-concurency" || control.name === "max-total";
|
|
220
|
-
if (!editable(state, ctx
|
|
205
|
+
if (!editable(state, ctx)) return;
|
|
206
|
+
// In-flight calls retain the old schema but read the current preset settings.
|
|
207
|
+
if (control.name === "intelligence" && !ctx.isIdle()) {
|
|
208
|
+
ctx.ui.notify("Wait for the current assistant turn to finish before changing intelligence.", "warning");
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
221
211
|
const value = parseValue(control, raw);
|
|
222
212
|
if (control.name === "max-total" && state.currentBudget)
|
|
223
213
|
setSessionBudgetLimit(state.currentBudget, Number(value));
|
package/extension/state.ts
CHANGED
|
@@ -15,15 +15,29 @@ import { resolveDelegationDepthConfig, type DelegationDepthConfig } from "./poli
|
|
|
15
15
|
|
|
16
16
|
import type { BackgroundJob } from "./async-jobs.js";
|
|
17
17
|
|
|
18
|
+
/** Live work kept across a Pi reload until the reloaded extension instance adopts it. */
|
|
19
|
+
export interface ReloadHandoff {
|
|
20
|
+
sessionId: string;
|
|
21
|
+
/** Lead messages and completions raised while no session is bound, replayed in order on adoption. */
|
|
22
|
+
queue: Array<() => void>;
|
|
23
|
+
/** The handing-off instance's normal shutdown. Idempotent. */
|
|
24
|
+
stop: () => Promise<void>;
|
|
25
|
+
/** Cancel the adoption deadline once a session owns the work. */
|
|
26
|
+
release: () => void;
|
|
27
|
+
}
|
|
28
|
+
|
|
18
29
|
export interface ExtensionState extends DelegationDepthConfig {
|
|
30
|
+
reloadHandoff?: ReloadHandoff;
|
|
19
31
|
backgroundJobs: Map<string, BackgroundJob>;
|
|
20
32
|
onBackgroundChanged?: (messageQueued?: boolean) => void;
|
|
21
33
|
/** Delivery token -> session generation, retained until the completion is consumed. */
|
|
22
34
|
pendingCompletionDeliveries: Map<string, number>;
|
|
23
35
|
pendingCompletionInterrupts: Map<string, () => void>;
|
|
24
36
|
interruptEpoch: number;
|
|
37
|
+
/** Recovery-only cancellation; tree browsing must not interrupt live workers. */
|
|
38
|
+
resumeEpoch: number;
|
|
25
39
|
onSessionReadyForInterrupt?: (ctx: SessionContext) => void;
|
|
26
|
-
pendingAutomaticResume?: { prompt: string; interruptEpoch: number };
|
|
40
|
+
pendingAutomaticResume?: { prompt: string; interruptEpoch: number; resumeEpoch: number };
|
|
27
41
|
pi: ExtensionAPI;
|
|
28
42
|
settings?: SubagentSettings;
|
|
29
43
|
sessionSettings?: SubagentSettings;
|
|
@@ -95,6 +109,7 @@ export function createExtensionState(pi: ExtensionAPI): ExtensionState {
|
|
|
95
109
|
pendingCompletionDeliveries: new Map(),
|
|
96
110
|
pendingCompletionInterrupts: new Map(),
|
|
97
111
|
interruptEpoch: 0,
|
|
112
|
+
resumeEpoch: 0,
|
|
98
113
|
activeSubagents: new Map(),
|
|
99
114
|
activeResumeNames: new Set(),
|
|
100
115
|
forcedErrorToolCallIds: new Set(),
|
package/index.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { registerPromptHook } from "./extension/prompt-hook.js";
|
|
|
10
10
|
import { registerResumeProvider } from "./extension/provider.js";
|
|
11
11
|
import { registerSessionLifecycle } from "./extension/session-start.js";
|
|
12
12
|
import { createExtensionState } from "./extension/state.js";
|
|
13
|
+
import { claimReloadHandoff } from "./extension/reload-handoff.js";
|
|
13
14
|
import { registerTools } from "./extension/tool-registration.js";
|
|
14
15
|
|
|
15
16
|
export { selectParentModelForSubagent } from "./extension/models.js";
|
|
@@ -28,7 +29,8 @@ export default function (pi: ExtensionAPI): void {
|
|
|
28
29
|
description: "Block delegating to agents already in the current delegation stack (default: true).",
|
|
29
30
|
type: "boolean",
|
|
30
31
|
});
|
|
31
|
-
|
|
32
|
+
// After a Pi reload, adopt the previous instance's live workers instead of starting empty.
|
|
33
|
+
const state = claimReloadHandoff(pi) ?? createExtensionState(pi);
|
|
32
34
|
registerResumeProvider(state);
|
|
33
35
|
registerSessionLifecycle(state);
|
|
34
36
|
registerSessionEvents(state);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oira666_pi-subagent",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.16",
|
|
4
4
|
"description": "Subagent extension for Pi coding agent. Delegate tasks to specialized agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "startup.js",
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
"intelligence.ts",
|
|
17
17
|
"runner.ts",
|
|
18
18
|
"resume.ts",
|
|
19
|
+
"resume-slots.ts",
|
|
20
|
+
"resume-tail.ts",
|
|
19
21
|
"names.ts",
|
|
20
22
|
"agent-names.ts",
|
|
21
23
|
"shared.ts",
|