@ferris1225/pi-subagents 0.31.0 → 1.0.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/README.md +144 -74
- package/package.json +2 -2
- package/src/agents.ts +8 -13
- package/src/announcements.ts +59 -0
- package/src/background.ts +59 -6
- package/src/config.ts +14 -2
- package/src/dispatch.ts +1833 -845
- package/src/fixloop.ts +1 -1
- package/src/format.ts +30 -4
- package/src/index.ts +9 -10
- package/src/models.ts +184 -54
- package/src/monitor.ts +141 -93
- package/src/prompt.ts +3 -2
- package/src/recovery.ts +145 -0
- package/src/rpc-run.ts +991 -0
- package/src/runtime.ts +284 -145
- package/src/session-fork.ts +84 -0
- package/src/setup.ts +271 -184
- package/src/spawn.ts +557 -977
- package/src/tools.ts +730 -409
- package/src/trajectory.ts +312 -0
- package/src/ui.ts +32 -16
- package/src/worktree.ts +687 -0
- package/src/widget.ts +0 -182
package/src/runtime.ts
CHANGED
|
@@ -1,145 +1,284 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared per-session runtime state for pi-subagents.
|
|
3
|
-
*
|
|
4
|
-
* The extension registers several tools (subagent, subagent_wait/status/stop)
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* `createRuntime` builds those once per extension load and hands the same object
|
|
8
|
-
* to every registration site, so state stays in one place without globals.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
12
|
-
import { rmSync } from "node:fs";
|
|
13
|
-
import { BackgroundTaskQueue } from "./background.ts";
|
|
14
|
-
import {
|
|
15
|
-
completionGroupTriggersTurn,
|
|
16
|
-
createCompletionBatcher,
|
|
17
|
-
formatActiveRunsFooter,
|
|
18
|
-
formatCompletionMessage,
|
|
19
|
-
type CompletionBatcher,
|
|
20
|
-
type CompletionMessageItem,
|
|
21
|
-
} from "./completion.ts";
|
|
22
|
-
import { loadConfigSync } from "./config.ts";
|
|
23
|
-
import { monitor } from "./monitor.ts";
|
|
24
|
-
import
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
vision: boolean;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Shared per-session runtime state for pi-subagents.
|
|
3
|
+
*
|
|
4
|
+
* The extension registers several tools (subagent, subagent_wait/status/stop)
|
|
5
|
+
* that share the background queue, completion batcher, abort controllers per
|
|
6
|
+
* run, and settled-results store.
|
|
7
|
+
* `createRuntime` builds those once per extension load and hands the same object
|
|
8
|
+
* to every registration site, so state stays in one place without globals.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { rmSync } from "node:fs";
|
|
13
|
+
import { BackgroundTaskQueue } from "./background.ts";
|
|
14
|
+
import {
|
|
15
|
+
completionGroupTriggersTurn,
|
|
16
|
+
createCompletionBatcher,
|
|
17
|
+
formatActiveRunsFooter,
|
|
18
|
+
formatCompletionMessage,
|
|
19
|
+
type CompletionBatcher,
|
|
20
|
+
type CompletionMessageItem,
|
|
21
|
+
} from "./completion.ts";
|
|
22
|
+
import { loadConfigSync, type ThinkingLevel } from "./config.ts";
|
|
23
|
+
import { isRunActiveStatus, monitor } from "./monitor.ts";
|
|
24
|
+
import {
|
|
25
|
+
persistRecoveryRecords,
|
|
26
|
+
recoveryRecordFromFinalization,
|
|
27
|
+
type RecoveryRecord,
|
|
28
|
+
} from "./recovery.ts";
|
|
29
|
+
import type { RpcRunControl } from "./rpc-run.ts";
|
|
30
|
+
import { trajectoryStore } from "./trajectory.ts";
|
|
31
|
+
import type { SingleResult } from "./spawn.ts";
|
|
32
|
+
import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "./worktree.ts";
|
|
33
|
+
|
|
34
|
+
export type ThreadState =
|
|
35
|
+
| "queued"
|
|
36
|
+
| "resuming"
|
|
37
|
+
| "running"
|
|
38
|
+
| "steering"
|
|
39
|
+
| "interrupting"
|
|
40
|
+
| "parked"
|
|
41
|
+
| "completed"
|
|
42
|
+
| "failed"
|
|
43
|
+
| "stopped";
|
|
44
|
+
|
|
45
|
+
export type ThreadLifecycleOperation = "park" | "resume" | "fork" | "stop" | "settle";
|
|
46
|
+
|
|
47
|
+
export interface SubagentThread {
|
|
48
|
+
id: number;
|
|
49
|
+
generation: number;
|
|
50
|
+
agentName: string;
|
|
51
|
+
task: string;
|
|
52
|
+
/** Caller-facing cwd in the original worktree. */
|
|
53
|
+
cwd: string;
|
|
54
|
+
/** Actual child cwd (the equivalent path inside an isolated worktree). */
|
|
55
|
+
executionCwd: string;
|
|
56
|
+
vision: boolean;
|
|
57
|
+
/** Exact primary→fallback refs inherited by a session fork. */
|
|
58
|
+
modelPool: string[];
|
|
59
|
+
thinkingLevel?: ThinkingLevel;
|
|
60
|
+
isolation: IsolationMode;
|
|
61
|
+
worktree?: WorktreeIsolation;
|
|
62
|
+
state: ThreadState;
|
|
63
|
+
control: RpcRunControl;
|
|
64
|
+
queueController?: AbortController;
|
|
65
|
+
/** Resolves only after the current generation's queue work has fully
|
|
66
|
+
* quiesced and released its concurrency slot. Auto-fix orchestration is part
|
|
67
|
+
* of the parent generation and replaces/extends this promise. */
|
|
68
|
+
generationCompletion: Promise<void>;
|
|
69
|
+
/** Synchronous CAS used by lifecycle controls across their async preflight. */
|
|
70
|
+
lifecycleVersion: number;
|
|
71
|
+
lifecycleOperation?: ThreadLifecycleOperation;
|
|
72
|
+
sessionId?: string;
|
|
73
|
+
sessionDir?: string;
|
|
74
|
+
/** Most recent generation result, retained for parked destructive-stop output. */
|
|
75
|
+
lastResult?: SingleResult;
|
|
76
|
+
/** A destructive stop retires context even if the active child settles later. */
|
|
77
|
+
retireOnSettle?: boolean;
|
|
78
|
+
retired?: boolean;
|
|
79
|
+
/** Abort the active generation to a stable checkpoint and wait until its
|
|
80
|
+
* queue work has published that checkpoint and released its slot. */
|
|
81
|
+
park: () => Promise<"queued" | "active">;
|
|
82
|
+
/** Installed by dispatch so the control tool can restart the same logical id. */
|
|
83
|
+
resume: (objective?: string, ctx?: ExtensionContext) => Promise<SingleResult>;
|
|
84
|
+
/** Create a new logical thread from this thread's retained Pi session branch. */
|
|
85
|
+
fork: (objective?: string, ctx?: ExtensionContext) => Promise<SingleResult>;
|
|
86
|
+
forkedFromRunId?: number;
|
|
87
|
+
forkChildRunIds: number[];
|
|
88
|
+
/** Dispatch-owned, generation-guarded worktree settlement hook. */
|
|
89
|
+
finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
|
|
90
|
+
/** Best-effort shutdown notification for retained integration artifacts. */
|
|
91
|
+
notifyIsolationFailure?: (finalization: WorktreeFinalization) => void;
|
|
92
|
+
isolationFailureNotified?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface SubagentRuntime {
|
|
96
|
+
configPath: string;
|
|
97
|
+
backgroundQueue: BackgroundTaskQueue;
|
|
98
|
+
/** False after session_shutdown; guards delivery and queue work. */
|
|
99
|
+
sessionActive: boolean;
|
|
100
|
+
/** Deliver a batch of completion messages to the main window, waking it only
|
|
101
|
+
* when the batch needs a turn. */
|
|
102
|
+
sendCompletionGroup: (items: CompletionMessageItem[]) => void;
|
|
103
|
+
completionBatcher: CompletionBatcher<CompletionMessageItem>;
|
|
104
|
+
/** Abort controllers per active run, so subagent_stop can cancel a run in-turn. */
|
|
105
|
+
runControllers: Map<number, AbortController>;
|
|
106
|
+
/** Final results keyed by run id, so subagent_wait can hand the model the
|
|
107
|
+
* actual result in-turn instead of it sleeping/polling for a wake-up message. */
|
|
108
|
+
settledRuns: Map<number, SingleResult>;
|
|
109
|
+
settledListeners: Map<number, Set<(result: SingleResult) => void>>;
|
|
110
|
+
registerRunResult: (runId: number, result: SingleResult) => void;
|
|
111
|
+
/** Logical threads outlive process attempts and completed generations. */
|
|
112
|
+
threads: Map<number, SubagentThread>;
|
|
113
|
+
/** Resume/fork setup that has claimed a thread but has not yet enqueued its
|
|
114
|
+
* next generation. Shutdown invalidates these claims and waits for cleanup. */
|
|
115
|
+
preflightOperations: Set<Promise<void>>;
|
|
116
|
+
/** Every session directory retained for this parent session, including
|
|
117
|
+
* auto-fix internals that are not directly controllable. */
|
|
118
|
+
sessionDirs: Set<string>;
|
|
119
|
+
retainSession: (result: Pick<SingleResult, "sessionDir">) => void;
|
|
120
|
+
retireThreadSession: (thread: SubagentThread) => void;
|
|
121
|
+
/** Worktree/patch paths intentionally retained after a failed integration. */
|
|
122
|
+
retainedArtifactPaths: Set<string>;
|
|
123
|
+
retainWorktreeArtifacts: (finalization: WorktreeFinalization) => void;
|
|
124
|
+
/** Flip sessionActive off and release all session-scoped resources. */
|
|
125
|
+
shutdown: () => Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
|
|
129
|
+
// Init-time decisions need the config synchronously; the full (migrating)
|
|
130
|
+
// async load runs per tool call.
|
|
131
|
+
const initialConfig = loadConfigSync(configPath);
|
|
132
|
+
const backgroundQueue = new BackgroundTaskQueue(initialConfig.maxConcurrency);
|
|
133
|
+
|
|
134
|
+
const runtime: SubagentRuntime = {
|
|
135
|
+
configPath,
|
|
136
|
+
backgroundQueue,
|
|
137
|
+
sessionActive: true,
|
|
138
|
+
sendCompletionGroup: (items) => {
|
|
139
|
+
if (!runtime.sessionActive || items.length === 0) return;
|
|
140
|
+
// A result arriving for one run does not mean sibling runs are done.
|
|
141
|
+
// Computing this at delivery (emit) time — not when the item was
|
|
142
|
+
// pushed — reflects the current monitor state, since finishing runs
|
|
143
|
+
// are removed from the monitor before their completion is pushed.
|
|
144
|
+
const active = monitor
|
|
145
|
+
.getRuns()
|
|
146
|
+
.filter((run) => isRunActiveStatus(run.status) || run.retained)
|
|
147
|
+
.map((run) => ({ id: run.id, agent: run.agent, label: run.label }));
|
|
148
|
+
const message = {
|
|
149
|
+
customType: "subagent-result",
|
|
150
|
+
content: formatCompletionMessage(items) + formatActiveRunsFooter(active),
|
|
151
|
+
display: true,
|
|
152
|
+
};
|
|
153
|
+
if (completionGroupTriggersTurn(items)) {
|
|
154
|
+
// steer: the result is injected after the current tool call even mid-turn,
|
|
155
|
+
// or starts a new turn when idle. followUp would sit in the queue until the
|
|
156
|
+
// whole turn ends — a main agent waiting for the result (sleep/poll) would
|
|
157
|
+
// never see it delivered, which is exactly the "returned but never woken"
|
|
158
|
+
// failure mode.
|
|
159
|
+
pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
|
|
160
|
+
} else {
|
|
161
|
+
// No-wake delivery: nextTurn rides along with the next user turn and can
|
|
162
|
+
// never start a continuation by itself. followUp would auto-continue
|
|
163
|
+
// whenever pi is already streaming, defeating the opt-out.
|
|
164
|
+
pi.sendMessage(message, { deliverAs: "nextTurn" });
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
completionBatcher: undefined as unknown as CompletionBatcher<CompletionMessageItem>,
|
|
168
|
+
runControllers: new Map<number, AbortController>(),
|
|
169
|
+
settledRuns: new Map<number, SingleResult>(),
|
|
170
|
+
settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
|
|
171
|
+
threads: new Map<number, SubagentThread>(),
|
|
172
|
+
preflightOperations: new Set<Promise<void>>(),
|
|
173
|
+
sessionDirs: new Set<string>(),
|
|
174
|
+
retainedArtifactPaths: new Set<string>(),
|
|
175
|
+
retainWorktreeArtifacts: (finalization) => {
|
|
176
|
+
if (finalization.worktreePath) runtime.retainedArtifactPaths.add(finalization.worktreePath);
|
|
177
|
+
if (finalization.patchPath) runtime.retainedArtifactPaths.add(finalization.patchPath);
|
|
178
|
+
},
|
|
179
|
+
retainSession: (result) => {
|
|
180
|
+
if (result.sessionDir) runtime.sessionDirs.add(result.sessionDir);
|
|
181
|
+
},
|
|
182
|
+
retireThreadSession: (thread) => {
|
|
183
|
+
thread.retired = true;
|
|
184
|
+
if (!thread.sessionDir) return;
|
|
185
|
+
const sessionDir = thread.sessionDir;
|
|
186
|
+
try {
|
|
187
|
+
rmSync(sessionDir, { recursive: true, force: true });
|
|
188
|
+
runtime.sessionDirs.delete(sessionDir);
|
|
189
|
+
thread.sessionDir = undefined;
|
|
190
|
+
thread.sessionId = undefined;
|
|
191
|
+
} catch {
|
|
192
|
+
/* best-effort; shutdown retries the still-retained directory */
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
registerRunResult: (runId, result) => {
|
|
196
|
+
runtime.settledRuns.set(runId, result);
|
|
197
|
+
const listeners = runtime.settledListeners.get(runId);
|
|
198
|
+
if (listeners) {
|
|
199
|
+
runtime.settledListeners.delete(runId);
|
|
200
|
+
for (const listener of listeners) {
|
|
201
|
+
try {
|
|
202
|
+
listener(result);
|
|
203
|
+
} catch {
|
|
204
|
+
/* listener errors must never break settling */
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
shutdown: async () => {
|
|
210
|
+
if (!runtime.sessionActive) return;
|
|
211
|
+
runtime.sessionActive = false;
|
|
212
|
+
const shutdownThreads = [...runtime.threads.values()];
|
|
213
|
+
// Invalidate every lifecycle claim synchronously before the first await.
|
|
214
|
+
// Resume/fork preflight checks both this version and sessionActive, then
|
|
215
|
+
// cleans any worktree/session it created before resolving its tracker.
|
|
216
|
+
for (const thread of shutdownThreads) {
|
|
217
|
+
thread.lifecycleVersion++;
|
|
218
|
+
thread.lifecycleOperation = "stop";
|
|
219
|
+
thread.retired = true;
|
|
220
|
+
thread.retireOnSettle = true;
|
|
221
|
+
thread.state = "stopped";
|
|
222
|
+
}
|
|
223
|
+
const preflights = [...runtime.preflightOperations];
|
|
224
|
+
runtime.completionBatcher.dispose();
|
|
225
|
+
runtime.backgroundQueue.cancelAll();
|
|
226
|
+
// Await live RPC process-tree cleanup and continuation preflight rollback
|
|
227
|
+
// before removing sessions/worktrees or clearing ownership maps.
|
|
228
|
+
await Promise.all([
|
|
229
|
+
Promise.all(
|
|
230
|
+
shutdownThreads.map((thread) =>
|
|
231
|
+
thread.control.stop("Parent session shut down").catch(() => undefined),
|
|
232
|
+
),
|
|
233
|
+
),
|
|
234
|
+
Promise.allSettled(preflights),
|
|
235
|
+
runtime.backgroundQueue.waitForIdle(),
|
|
236
|
+
]);
|
|
237
|
+
// Parked work owns no queue task, so shutdown is its final settlement.
|
|
238
|
+
// Active/stopped tasks may already have finalized; the handle and callback
|
|
239
|
+
// are idempotent and generation-guarded.
|
|
240
|
+
const recoveryRecords: RecoveryRecord[] = [];
|
|
241
|
+
for (const thread of runtime.threads.values()) {
|
|
242
|
+
const finalization = await thread.finalizeIsolation(thread.generation).catch(() => undefined);
|
|
243
|
+
if (finalization?.status === "retained") {
|
|
244
|
+
runtime.retainWorktreeArtifacts(finalization);
|
|
245
|
+
recoveryRecords.push(recoveryRecordFromFinalization(thread.id, finalization));
|
|
246
|
+
if (!thread.isolationFailureNotified) {
|
|
247
|
+
thread.isolationFailureNotified = true;
|
|
248
|
+
try {
|
|
249
|
+
thread.notifyIsolationFailure?.(finalization);
|
|
250
|
+
} catch {
|
|
251
|
+
/* the parent UI may already be shutting down */
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// Persist before tearing down the old runtime. A /new, /resume, or quit
|
|
257
|
+
// must not make the only recovery paths unreachable.
|
|
258
|
+
await persistRecoveryRecords(runtime.configPath, recoveryRecords).catch(() => undefined);
|
|
259
|
+
runtime.settledRuns.clear();
|
|
260
|
+
runtime.settledListeners.clear();
|
|
261
|
+
runtime.runControllers.clear();
|
|
262
|
+
for (const sessionDir of runtime.sessionDirs) {
|
|
263
|
+
try {
|
|
264
|
+
rmSync(sessionDir, { recursive: true, force: true });
|
|
265
|
+
} catch {
|
|
266
|
+
/* best-effort */
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
runtime.sessionDirs.clear();
|
|
270
|
+
runtime.preflightOperations.clear();
|
|
271
|
+
// Deliberately do not remove retainedArtifactPaths: they are the recovery
|
|
272
|
+
// path after a failed patch apply/cleanup.
|
|
273
|
+
runtime.threads.clear();
|
|
274
|
+
monitor.clear();
|
|
275
|
+
// Lifecycle trajectories are parent-session scoped.
|
|
276
|
+
trajectoryStore.clearAll();
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
runtime.completionBatcher = createCompletionBatcher<CompletionMessageItem>({
|
|
281
|
+
emit: runtime.sendCompletionGroup,
|
|
282
|
+
});
|
|
283
|
+
return runtime;
|
|
284
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** Pi SessionManager-backed cloning of a retained sub-agent session branch. */
|
|
2
|
+
|
|
3
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
|
|
9
|
+
export interface ForkedSession {
|
|
10
|
+
sourceSessionFile: string;
|
|
11
|
+
sessionDir: string;
|
|
12
|
+
sessionId: string;
|
|
13
|
+
sessionFile: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Locate one retained session by its authoritative header id. */
|
|
17
|
+
export async function findRetainedSessionFile(
|
|
18
|
+
cwd: string,
|
|
19
|
+
sessionDir: string,
|
|
20
|
+
sessionId: string,
|
|
21
|
+
): Promise<string> {
|
|
22
|
+
// The retained header may point at a worktree that has since been removed.
|
|
23
|
+
// The session id is authoritative inside this explicit private directory;
|
|
24
|
+
// listing the directory directly avoids a stale-cwd filter rejecting it.
|
|
25
|
+
const sessions = await SessionManager.listAll(sessionDir);
|
|
26
|
+
const matches = sessions.filter((session) => session.id === sessionId);
|
|
27
|
+
if (matches.length === 0) {
|
|
28
|
+
throw new Error(`Retained session ${sessionId} was not found in ${sessionDir}.`);
|
|
29
|
+
}
|
|
30
|
+
if (matches.length > 1) {
|
|
31
|
+
throw new Error(`Retained session id ${sessionId} is ambiguous in ${sessionDir}.`);
|
|
32
|
+
}
|
|
33
|
+
return matches[0].path;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Copy only the source file's active branch into a new isolated temp session
|
|
38
|
+
* directory. SessionManager performs all JSONL/tree handling; source state is
|
|
39
|
+
* never mutated.
|
|
40
|
+
*/
|
|
41
|
+
export async function forkRetainedSession(options: {
|
|
42
|
+
/** Cwd stored in the source session header (used for exact lookup). */
|
|
43
|
+
cwd: string;
|
|
44
|
+
/** Optional cwd for the cloned session header and future child tools. */
|
|
45
|
+
targetCwd?: string;
|
|
46
|
+
sessionDir: string;
|
|
47
|
+
sessionId: string;
|
|
48
|
+
}): Promise<ForkedSession> {
|
|
49
|
+
const sourceSessionFile = await findRetainedSessionFile(
|
|
50
|
+
options.cwd,
|
|
51
|
+
options.sessionDir,
|
|
52
|
+
options.sessionId,
|
|
53
|
+
);
|
|
54
|
+
const sessionDir = await mkdtemp(join(tmpdir(), "pi-subagent-session-fork-"));
|
|
55
|
+
try {
|
|
56
|
+
// Supplying the new directory makes createBranchedSession write there.
|
|
57
|
+
// cwdOverride rewrites the cloned header so a settled isolated session can
|
|
58
|
+
// safely continue in its fresh worktree instead of a removed old path.
|
|
59
|
+
const manager = SessionManager.open(
|
|
60
|
+
sourceSessionFile,
|
|
61
|
+
sessionDir,
|
|
62
|
+
options.targetCwd ?? options.cwd,
|
|
63
|
+
);
|
|
64
|
+
const leafId = manager.getLeafId();
|
|
65
|
+
if (!leafId) throw new Error(`Retained session ${options.sessionId} has no active branch to fork.`);
|
|
66
|
+
const sessionFile = manager.createBranchedSession(leafId);
|
|
67
|
+
if (!sessionFile) throw new Error("Pi SessionManager did not create a persistent fork.");
|
|
68
|
+
// Pi defers branch files that contain no assistant response. Such a file
|
|
69
|
+
// cannot be resumed by RPC without creating a blank session, so reject
|
|
70
|
+
// rather than pretending context was preserved.
|
|
71
|
+
if (!existsSync(sessionFile)) {
|
|
72
|
+
throw new Error(`Forked session branch has no persisted assistant checkpoint at ${sessionFile}.`);
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
sourceSessionFile,
|
|
76
|
+
sessionDir,
|
|
77
|
+
sessionId: manager.getSessionId(),
|
|
78
|
+
sessionFile,
|
|
79
|
+
};
|
|
80
|
+
} catch (error) {
|
|
81
|
+
await rm(sessionDir, { recursive: true, force: true }).catch(() => undefined);
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|