返回源码地图

packages/coding-agent/src/core/agent-session-runtime.ts

v1.3.0 · 71023aec1546 · 10/15:cwd-bound服务所有权与会话替换边界

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { constants, copyFileSync, existsSync, mkdirSync } from "node:fs";
2import { basename, join, parse, resolve } from "node:path";
3import { resolvePath } from "../utils/paths.ts";
4import type { AgentSession } from "./agent-session.ts";
5import type { AgentSessionRuntimeDiagnostic, AgentSessionServices } from "./agent-session-services.ts";
6import type {
7 ProjectTrustContext,
8 ReplacedSessionContext,
9 SessionShutdownEvent,
10 SessionStartEvent,
11} from "./extensions/index.ts";
12import { emitSessionShutdownEvent } from "./extensions/runner.ts";
13import type { CreateAgentSessionResult } from "./sdk.ts";
14import { assertSessionCwdExists } from "./session-cwd.ts";
15import { SessionManager } from "./session-manager.ts";
16
17/**
18 * Result returned by runtime creation.
19 *
20 * The caller gets the created session, its cwd-bound services, and all
21 * diagnostics collected during setup.
22 */
23export interface CreateAgentSessionRuntimeResult extends CreateAgentSessionResult {
24 services: AgentSessionServices;
25 diagnostics: AgentSessionRuntimeDiagnostic[];
26}
27
28/**
29 * Creates a full runtime for a target cwd and session manager.
30 *
31 * The factory closes over process-global fixed inputs, recreates cwd-bound
32 * services for the effective cwd, resolves session options against those
33 * services, and finally creates the AgentSession.
34 */
35export type CreateAgentSessionRuntimeFactory = (options: {
36 cwd: string;
37 agentDir: string;
38 sessionManager: SessionManager;
39 sessionStartEvent?: SessionStartEvent;
40 projectTrustContext?: ProjectTrustContext;
41}) => Promise<CreateAgentSessionRuntimeResult>;
42
43/**
44 * Thrown when /import references a JSONL file path that does not exist.
45 */
46export class SessionImportFileNotFoundError extends Error {
47 readonly filePath: string;
48
49 constructor(filePath: string) {
50 super(`File not found: ${filePath}`);
51 this.name = "SessionImportFileNotFoundError";
52 this.filePath = filePath;
53 }
54}
55
56function extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {
57 if (typeof content === "string") {
58 return content;
59 }
60
61 return content
62 .filter((part): part is { type: "text"; text: string } => part.type === "text" && typeof part.text === "string")
63 .map((part) => part.text)
64 .join("");
65}
66
67/**
68 * Owns the current AgentSession plus its cwd-bound services.
69 *
70 * Session replacement methods tear down the current runtime first, then create
71 * and apply the next runtime. If creation fails, the error is propagated to the
72 * caller. The caller is responsible for user-facing error handling.
73 */
74export class AgentSessionRuntime {
75 private rebindSession?: (session: AgentSession) => Promise<void>;
76 private beforeSessionInvalidate?: () => void;
77 private _session: AgentSession;
78 private _services: AgentSessionServices;
79 private readonly createRuntime: CreateAgentSessionRuntimeFactory;
80 private _diagnostics: AgentSessionRuntimeDiagnostic[];
81 private _modelFallbackMessage?: string;
82
83 constructor(
84 _session: AgentSession,
85 _services: AgentSessionServices,
86 createRuntime: CreateAgentSessionRuntimeFactory,
87 _diagnostics: AgentSessionRuntimeDiagnostic[] = [],
88 _modelFallbackMessage?: string,
89 ) {
90 this._session = _session;
91 this._services = _services;
92 this.createRuntime = createRuntime;
93 this._diagnostics = _diagnostics;
94 this._modelFallbackMessage = _modelFallbackMessage;
95 }
96
97 get services(): AgentSessionServices {
98 return this._services;
99 }
100
101 get session(): AgentSession {
102 return this._session;
103 }
104
105 get cwd(): string {
106 return this._services.cwd;
107 }
108
109 get diagnostics(): readonly AgentSessionRuntimeDiagnostic[] {
110 return this._diagnostics;
111 }
112
113 get modelFallbackMessage(): string | undefined {
114 return this._modelFallbackMessage;
115 }
116
117 setRebindSession(rebindSession?: (session: AgentSession) => Promise<void>): void {
118 this.rebindSession = rebindSession;
119 }
120
121 /**
122 * Set a synchronous callback that runs after `session_shutdown` handlers finish
123 * but before the current session is invalidated.
124 *
125 * This is for host-owned UI teardown that must not yield to the event loop,
126 * such as detaching extension-provided TUI components before the old extension
127 * context becomes stale.
128 */
129 setBeforeSessionInvalidate(beforeSessionInvalidate?: () => void): void {
130 this.beforeSessionInvalidate = beforeSessionInvalidate;
131 }
132
133 private async emitBeforeSwitch(
134 reason: "new" | "resume",
135 targetSessionFile?: string,
136 ): Promise<{ cancelled: boolean }> {
137 const runner = this.session.extensionRunner;
138 if (!runner.hasHandlers("session_before_switch")) {
139 return { cancelled: false };
140 }
141
142 const result = await runner.emit({
143 type: "session_before_switch",
144 reason,
145 targetSessionFile,
146 });
147 return { cancelled: result?.cancel === true };
148 }
149
150 private async emitBeforeFork(
151 entryId: string,
152 options: { position: "before" | "at" },
153 ): Promise<{ cancelled: boolean }> {
154 const runner = this.session.extensionRunner;
155 if (!runner.hasHandlers("session_before_fork")) {
156 return { cancelled: false };
157 }
158
159 const result = await runner.emit({
160 type: "session_before_fork",
161 entryId,
162 ...options,
163 });
164 return { cancelled: result?.cancel === true };
165 }
166
167 private async teardownCurrent(reason: SessionShutdownEvent["reason"], targetSessionFile?: string): Promise<void> {
168 // Settle any active response first so the aborted turn (including tool
169 // results) is persisted to the outgoing session before it is replaced.
170 await this.session.abort();
171 await emitSessionShutdownEvent(this.session.extensionRunner, {
172 type: "session_shutdown",
173 reason,
174 targetSessionFile,
175 });
176 this.beforeSessionInvalidate?.();
177 this.session.dispose();
178 }
179
180 private apply(result: CreateAgentSessionRuntimeResult): void {
181 this._session = result.session;
182 this._services = result.services;
183 this._diagnostics = result.diagnostics;
184 this._modelFallbackMessage = result.modelFallbackMessage;
185 }
186
187 private async finishSessionReplacement(withSession?: (ctx: ReplacedSessionContext) => Promise<void>): Promise<void> {
188 if (this.rebindSession) {
189 await this.rebindSession(this.session);
190 }
191 if (withSession) {
192 await withSession(this.session.createReplacedSessionContext());
193 }
194 }
195
196 async switchSession(
197 sessionPath: string,
198 options?: {
199 cwdOverride?: string;
200 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
201 projectTrustContextFactory?: (cwd: string) => ProjectTrustContext;
202 },
203 ): Promise<{ cancelled: boolean }> {
204 const beforeResult = await this.emitBeforeSwitch("resume", sessionPath);
205 if (beforeResult.cancelled) {
206 return beforeResult;
207 }
208
209 const previousSessionFile = this.session.sessionFile;
210 const sessionManager = SessionManager.open(sessionPath, undefined, options?.cwdOverride);
211 assertSessionCwdExists(sessionManager, this.cwd);
212 await this.teardownCurrent("resume", sessionManager.getSessionFile());
213 this.apply(
214 await this.createRuntime({
215 cwd: sessionManager.getCwd(),
216 agentDir: this.services.agentDir,
217 sessionManager,
218 sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
219 projectTrustContext: options?.projectTrustContextFactory?.(sessionManager.getCwd()),
220 }),
221 );
222 await this.finishSessionReplacement(options?.withSession);
223 return { cancelled: false };
224 }
225
226 async newSession(options?: {
227 parentSession?: string;
228 setup?: (sessionManager: SessionManager) => Promise<void>;
229 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
230 }): Promise<{ cancelled: boolean }> {
231 const beforeResult = await this.emitBeforeSwitch("new");
232 if (beforeResult.cancelled) {
233 return beforeResult;
234 }
235
236 const previousSessionFile = this.session.sessionFile;
237 const sessionDir = this.session.sessionManager.getSessionDir();
238 const sessionManager = this.session.sessionManager.isPersisted()
239 ? SessionManager.create(this.cwd, sessionDir)
240 : SessionManager.inMemory(this.cwd);
241 if (options?.parentSession) {
242 sessionManager.newSession({ parentSession: options.parentSession });
243 }
244
245 await this.teardownCurrent("new", sessionManager.getSessionFile());
246 this.apply(
247 await this.createRuntime({
248 cwd: this.cwd,
249 agentDir: this.services.agentDir,
250 sessionManager,
251 sessionStartEvent: { type: "session_start", reason: "new", previousSessionFile },
252 }),
253 );
254 if (options?.setup) {
255 await options.setup(this.session.sessionManager);
256 this.session.refreshContext();
257 }
258 await this.finishSessionReplacement(options?.withSession);
259 return { cancelled: false };
260 }
261
262 async fork(
263 entryId: string,
264 options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
265 ): Promise<{ cancelled: boolean; selectedText?: string }> {
266 const position = options?.position ?? "before";
267 const beforeResult = await this.emitBeforeFork(entryId, { position });
268 if (beforeResult.cancelled) {
269 return { cancelled: true };
270 }
271 let targetLeafId: string | null;
272 let selectedText: string | undefined;
273
274 const selectedEntry = this.session.sessionManager.getEntry(entryId);
275 if (!selectedEntry) {
276 throw new Error("Invalid entry ID for forking");
277 }
278
279 if (position === "at") {
280 targetLeafId = selectedEntry.id;
281 } else {
282 if (selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
283 throw new Error("Invalid entry ID for forking");
284 }
285 targetLeafId = selectedEntry.parentId;
286 selectedText = extractUserMessageText(selectedEntry.message.content);
287 }
288
289 const previousSessionFile = this.session.sessionFile;
290 if (this.session.sessionManager.isPersisted()) {
291 const currentSessionFile = this.session.sessionFile;
292 if (!currentSessionFile) {
293 throw new Error("Persisted session is missing a session file");
294 }
295 const sessionDir = this.session.sessionManager.getSessionDir();
296 if (!targetLeafId) {
297 const sessionManager = SessionManager.create(this.cwd, sessionDir);
298 sessionManager.newSession({ parentSession: currentSessionFile });
299 await this.teardownCurrent("fork", sessionManager.getSessionFile());
300 this.apply(
301 await this.createRuntime({
302 cwd: this.cwd,
303 agentDir: this.services.agentDir,
304 sessionManager,
305 sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
306 }),
307 );
308 await this.finishSessionReplacement(options?.withSession);
309 return { cancelled: false, selectedText };
310 }
311
312 if (!existsSync(currentSessionFile)) {
313 throw new Error("This session has not been saved yet. Send a message before cloning or forking it.");
314 }
315 const sessionManager = SessionManager.open(currentSessionFile, sessionDir);
316 const forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);
317 if (!forkedSessionPath) {
318 throw new Error("Failed to create forked session");
319 }
320 await this.teardownCurrent("fork", sessionManager.getSessionFile());
321 this.apply(
322 await this.createRuntime({
323 cwd: sessionManager.getCwd(),
324 agentDir: this.services.agentDir,
325 sessionManager,
326 sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
327 }),
328 );
329 await this.finishSessionReplacement(options?.withSession);
330 return { cancelled: false, selectedText };
331 }
332
333 const sessionManager = this.session.sessionManager;
334 await this.teardownCurrent("fork", sessionManager.getSessionFile());
335 if (!targetLeafId) {
336 sessionManager.newSession({ parentSession: previousSessionFile });
337 } else {
338 sessionManager.createBranchedSession(targetLeafId);
339 }
340 this.apply(
341 await this.createRuntime({
342 cwd: this.cwd,
343 agentDir: this.services.agentDir,
344 sessionManager,
345 sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
346 }),
347 );
348 await this.finishSessionReplacement(options?.withSession);
349 return { cancelled: false, selectedText };
350 }
351
352 /**
353 * Import a session JSONL file and switch runtime state to the imported session.
354 *
355 * @returns `{ cancelled: true }` when cancelled by `session_before_switch`, otherwise `{ cancelled: false }`.
356 * @throws {SessionImportFileNotFoundError} When the input path does not exist.
357 * @throws {MissingSessionCwdError} When the imported session cwd cannot be resolved and no override is provided.
358 */
359 async importFromJsonl(inputPath: string, cwdOverride?: string): Promise<{ cancelled: boolean }> {
360 const resolvedPath = resolvePath(inputPath);
361 if (!existsSync(resolvedPath)) {
362 throw new SessionImportFileNotFoundError(resolvedPath);
363 }
364
365 const sessionDir = this.session.sessionManager.getSessionDir();
366 if (!existsSync(sessionDir)) {
367 mkdirSync(sessionDir, { recursive: true });
368 }
369
370 let destinationPath = join(sessionDir, basename(resolvedPath));
371 const sourceAlreadyStored = resolve(destinationPath) === resolvedPath;
372 if (!sourceAlreadyStored) {
373 const { name, ext } = parse(destinationPath);
374 let suffix = 1;
375 while (existsSync(destinationPath)) {
376 destinationPath = join(sessionDir, `${name}-${suffix++}${ext}`);
377 }
378 }
379 const beforeResult = await this.emitBeforeSwitch("resume", destinationPath);
380 if (beforeResult.cancelled) {
381 return beforeResult;
382 }
383
384 const previousSessionFile = this.session.sessionFile;
385 if (!sourceAlreadyStored) {
386 copyFileSync(resolvedPath, destinationPath, constants.COPYFILE_EXCL);
387 }
388
389 const sessionManager = SessionManager.open(destinationPath, sessionDir, cwdOverride);
390 assertSessionCwdExists(sessionManager, this.cwd);
391 await this.teardownCurrent("resume", sessionManager.getSessionFile());
392 this.apply(
393 await this.createRuntime({
394 cwd: sessionManager.getCwd(),
395 agentDir: this.services.agentDir,
396 sessionManager,
397 sessionStartEvent: { type: "session_start", reason: "resume", previousSessionFile },
398 }),
399 );
400 await this.finishSessionReplacement();
401 return { cancelled: false };
402 }
403
404 async dispose(): Promise<void> {
405 await emitSessionShutdownEvent(this.session.extensionRunner, {
406 type: "session_shutdown",
407 reason: "quit",
408 });
409 this.beforeSessionInvalidate?.();
410 this.session.dispose();
411 }
412}
413
414/**
415 * Create the initial runtime from a runtime factory and initial session target.
416 *
417 * The same factory is stored on the returned AgentSessionRuntime and reused for
418 * later /new, /resume, /fork, and import flows.
419 */
420export async function createAgentSessionRuntime(
421 createRuntime: CreateAgentSessionRuntimeFactory,
422 options: {
423 cwd: string;
424 agentDir: string;
425 sessionManager: SessionManager;
426 sessionStartEvent?: SessionStartEvent;
427 },
428): Promise<AgentSessionRuntime> {
429 assertSessionCwdExists(options.sessionManager, options.cwd);
430 const result = await createRuntime(options);
431 return new AgentSessionRuntime(
432 result.session,
433 result.services,
434 createRuntime,
435 result.diagnostics,
436 result.modelFallbackMessage,
437 );
438}
439
440export {
441 type AgentSessionRuntimeDiagnostic,
442 type AgentSessionServices,
443 type CreateAgentSessionFromServicesOptions,
444 type CreateAgentSessionServicesOptions,
445 createAgentSessionFromServices,
446 createAgentSessionServices,
447} from "./agent-session-services.ts";