-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsessionLifecycleService.ts
More file actions
874 lines (814 loc) · 36.6 KB
/
Copy pathsessionLifecycleService.ts
File metadata and controls
874 lines (814 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
/**
* `sessionLifecycle` domain — `ISessionLifecycleService` implementation.
*
* Owns the registry of THIS handler's open Session child scopes, creating
* them through the DI scope tree (children of the handler's Workspace
* scope) and seeding each with its identity, storage addressing derived
* from the handler's persistence scope, and a per-session lifecycle-hooks
* slots instance it runs around create/close,
* tearing sessions down on close/archive — archiving flags the session's
* metadata, removes its agents, restoring clears
* the archived flag, and broadcasts the transition; deleting closes a live
* session through the same flow, then removes the session directory
* (metadata, agent wire records, plans, logs), evicts the index read-model
* entry, and appends a `deleted` tombstone to the shared
* `session_index.jsonl`, raising `session.not_found` for ids this handler
* never persisted. Pending metadata writes and the index mirror are
* drained before any teardown, so a listing right after close/archive/delete
* never reads a stale outcome. Session start and
* resume failures are reported through telemetry. Each Session scope
* receives a telemetry view bound to its session id, while failures before
* a scope is available use an ephemeral context view. Closing a session
* never touches the handler itself.
* Every Session scope is also seeded with the handler's shared workspace
* resources as pure-data read views (the injection contracts) — discovery,
* watching and connecting all live on the Workspace-scope services; session
* consumers read the seeds and refresh off their change events. The five
* workspace-projection seeds are provided by the seed-adapter units
* installed with the scope (`installSessionSeedAdapters`), not by `extra`.
* Materializes the session's initial metadata on
* creation. Bound at Workspace scope.
* Persisted sessions are discovered through the session-index read model.
* On create / fork the
* session is also appended to the shared `session_index.jsonl` so v1 clients
* (TUI, export) can discover sessions created by the v2 engine; the entry is
* indexed under the handler's workspace id — the same id seeding the
* session's storage scope — so an alias spelling of the workDir cannot split
* the session into a bucket v1 readers never look in. Fork flushes
* live Agent wire journals, normalizes a missing protocol envelope, and
* appends the fork boundary before restoring the target Agent; fork is
* confined to this handler (source and target share the workspace bucket).
* Fork rejects a LIVE source with an active turn
* (`session.fork_active_turn`, read off the agents' `activityView`); a
* closed source forks from disk unchecked. The copied file set drops the
* v1-only `upcoming-goals.json` goal queue on every fork. A fork carrying
* a `turnIndex` truncates the copy through the addressed user-visible turn
* (the slicing itself lives in `internal/forkTurnSlice.ts`, with the
* `prompt` domain's metadata-text normalization deriving the fork's
* `lastPrompt` from the addressed turn): the main wire is sliced at the
* turn boundary keeping only matched turn inputs, subagent wires time-cut
* at the main slice's latest record time and subagents left empty are
* dropped with their copied files, retained agents' `tasks/` and `cron/`
* dirs are cleared, and cron duplication is skipped. The slice runs before
* any target artifact exists, so an out-of-range index fails without a
* cleanup pass. v1's missing-parent sweep has no counterpart: v2 agent metas
* parent `main` by construction, so a retained agent's chain cannot dangle
* outside fabricated wires.
* Fork restores the source's recency onto the target: the metadata write
* carries an explicit `updatedAt` and runs after agent recreation as the
* fork's final metadata write (agent registration is non-touching), ahead
* of cron duplication, so a mid-fork failure never leaves cloned cron
* records behind.
* On
* materialize, the agent-profile loaders' `ready` is awaited
* before the handle is published — agent-file discovery is local-
* fs and cheap, and a resumed session's first turn must see file-defined
* agent types in the `Agent` tool description; only the `fatal` explicit
* loader rejects, exactly the case that should
* fail fast, and on that failure the half-materialized handle is disposed
* instead of poisoning the session cache, and the explicit loader is re-armed
* with a fire-and-forget `reload()` so a fixed agent file unblocks later
* creates
* (the workspace skill catalog, by contrast, is kicked fire-and-forget).
* The handler's shared MCP manager is NOT awaited before create/resume
* returns — it connects fire-and-forget at Workspace scope, and the seeded
* handle's `ready` promise lets the agent's LLM steps wait on it instead
* (see `AgentMcpService`). A session created with ephemeral `mcpServers`
* gets them seeded verbatim (`ISessionEphemeralMcpServers`); connecting
* them is the MCP domain's own concern — `workspaceMcp` subscribes to this
* service's `onWillCreateSession`, reads the session's seeds through the
* event's session-domain surface (`readSeed` / `contributeSeed` /
* `onSessionDispose`), contributes its session overlay handle, and attaches
* the overlay's shutdown to the session's teardown, so this service never
* depends on MCP.
* The session-level services whose subscriptions
* must exist before the first agent / turn (external hooks, cron, the
* subagent model-pool startup validation) opt into `OnScopeCreated` activation.
* The subagent model pool itself is validated even earlier — at
* the top of `materializeSession`, before the MCP overlay, the session scope,
* and any persisted artifact come into existence, and again at the top of
* `fork` before the source session's files are copied — so a broken pool
* (or invalid `force` configuration) fails create/resume/fork without
* leaving orphaned session dirs or leaked
* overlay connections behind; the Session-scope validation service
* (`session/subagent/subagentModelsValidationService.ts`) repeats the same
* check at scope activation as a backstop for paths that bypass this service.
* That pre-flight awaits the kosong model/provider registries' `ready`
* alongside `config.ready` first: the catalog resolves aliases through those
* registries rather than the config document, so a cold bootstrap that
* creates a session before hydration completes must not fail a valid pool
* with `CONFIG_INVALID`.
* The pool is gated behind the `secondary-model` experiment, so with the
* experiment off these validations are no-ops and the section stays inert.
*/
import { randomUUID } from 'node:crypto';
import { join } from 'pathe';
import { ulid } from 'ulid';
import type { IInstantiationService } from '#/_base/di/instantiation';
import { Disposable } from '#/_base/di/lifecycle';
import {
createScopedChildHandle,
type ISessionScopeHandle,
} from '#/_base/di/scope';
import { unwrapErrorCause } from '#/_base/errors/errors';
import { AsyncEmitter, Emitter, type Event, type IWaitUntil } from '#/_base/event';
import { DEFAULT_PLAN_MODE_SECTION } from '#/features/plan/configSection';
import { IAgentPlanService } from '#/features/plan/plan';
import { LifecycleScope } from '#/app/scopes';
import { IBootstrapService } from '#/app/bootstrap/bootstrap';
import { CRON_SESSION_TAG, type CronTask } from '#/app/cron/cronTask';
import { ICronTaskPersistence } from '#/app/cron/cronTaskPersistence';
import { IConfigService } from '#/app/config/config';
import { IEventService } from '#/app/event/event';
import {
CHILD_SESSION_KIND,
CHILD_SESSION_KIND_KEY,
ISessionIndex,
ISessionIndexMirror,
PARENT_SESSION_ID_KEY,
} from '#/app/sessionIndex/sessionIndex';
import { ITelemetryService } from '#/app/telemetry/telemetry';
import { ErrorCodes, Error2, isError2 } from '#/errors';
import { IHostFileSystem, type HostDirEntry } from '#/os/interface/hostFileSystem';
import { IAppendLogStore } from '#/persistence/interface/appendLogStore';
import { IAtomicDocumentStore } from '#/persistence/interface/atomicDocumentStore';
import { IAgentLifecycleService, MAIN_AGENT_ID } from '#/session/agentLifecycle/agentLifecycle';
import { ensureMainAgent } from '#/session/agentLifecycle/mainAgent';
import { labelsFromAgentMeta } from '#/session/agentLifecycle/subagentMetadata';
import { ISessionContext, sessionContextSeed } from '#/session/sessionContext/sessionContext';
import { sessionEphemeralMcpServersSeed } from '#/session/mcp/ephemeralMcpServers';
import { sessionAgentProfileCatalogSeed } from '#/session/sessionAgentProfileCatalog/agentProfileCatalogSeed';
import { ISessionMetadata, type SessionMeta } from '#/session/sessionMetadata/sessionMetadata';
import { ISessionSkillCatalogData } from '#/session/sessionSkillCatalog/skillCatalogData';
import { ISessionInstructionsProvider } from '#/session/sessionInstructions/instructionsProvider';
import { ISessionMcpHandle } from '#/session/mcp/sessionMcpHandle';
import { ISessionWorkspaceInfo } from '#/session/workspaceInfo/workspaceInfo';
import { drainSessionMetadataWrites, toEpochMs } from '#/session/sessionMetadata/sessionMetadataService';
import { ISessionToolPolicy } from '#/session/sessionToolPolicy/sessionToolPolicy';
import { IEventDispatcher } from '#/state/eventDispatcher';
import {
AGENT_WIRE_RECORD_KEY,
createWireMetadataRecord,
type WireRecord,
} from '#/wire/record';
import { IModelCatalog } from '#/kosong/model/catalog';
import { IModelService } from '#/kosong/model/model';
import { IProviderService } from '#/kosong/provider/provider';
import { IFlagService } from '#/app/flag/flag';
import { assertValidSubagentModelConfig } from '#/session/subagent/configSection';
import { IWorkspaceContext } from '#/workspace/workspaceContext/workspaceContext';
import { IUserAgentProfileLoader } from '#/workspace/workspaceAgentProfileLoader/userAgentProfileLoader';
import { IPluginAgentProfileLoader } from '#/workspace/workspaceAgentProfileLoader/pluginAgentProfileLoader';
import {
IExplicitAgentProfileLoader,
} from '#/workspace/workspaceAgentProfileLoader/explicitAgentProfileLoader';
import {
IExtraAgentProfileLoader,
} from '#/workspace/workspaceAgentProfileLoader/extraAgentProfileLoader';
import {
IWorkspaceAgentProfileLoader,
} from '#/workspace/workspaceAgentProfileLoader/workspaceAgentProfileLoader';
import { IWorkspaceDirs } from '#/workspace/workspaceDirs/workspaceDirs';
import { IAgentActivityView } from '#/agent/activityView/activityView';
import { IWorkspaceSkillCatalog } from '#/workspace/workspaceSkillCatalog/workspaceSkillCatalog';
import { IWorkspaceInstructionsService } from '#/workspace/workspaceInstructions/workspaceInstructions';
import { IWorkspaceMcpService } from '#/workspace/workspaceMcp/workspaceMcp';
import { PLUGIN_SKILL_SOURCE_ID } from '#/app/skillCatalog/skillSource';
import { agentScopeOf, sessionDirOf, sessionScopeOf } from './internal/addressing';
import { SessionArchived } from './sessionLifecycleEvents';
import {
assertForkTurnIndex,
sliceMainRecordsAtTurn,
sliceSubagentRecordsAtTime,
} from './internal/forkTurnSlice';
import {
type CreateChildSessionOptions,
type CreateSessionOptions,
type ForkSessionOptions,
type ResumeSessionOptions,
type SessionArchivedEvent,
type SessionClosedEvent,
type SessionCreatedEvent,
type SessionForkedEvent,
type SessionWillCloseEvent,
type SessionWillCreateEvent,
ISessionLifecycleService,
} from './sessionLifecycle';
type MaterializeSessionOptions = Omit<CreateSessionOptions, 'sessionId'> & {
readonly sessionId: string;
};
const NO_ABORT = new AbortController().signal;
const SESSION_CREATE_RELOAD_SKILL_SOURCES: readonly string[] = [
'user',
'explicit',
'extra',
PLUGIN_SKILL_SOURCE_ID,
];
// NOTE: stays Disposable — its own 'get' and 'config' collide with the Fiber
export class SessionLifecycleService extends Disposable implements ISessionLifecycleService {
declare readonly _serviceBrand: undefined;
private readonly sessions = new Map<string, ISessionScopeHandle>();
private readonly _onWillCreateSession = this._register(
new Emitter<SessionWillCreateEvent>(),
);
readonly onWillCreateSession: Event<SessionWillCreateEvent> =
this._onWillCreateSession.event;
private readonly _onDidCreateSession = this._register(
new AsyncEmitter<SessionCreatedEvent & IWaitUntil>(),
);
readonly onDidCreateSession: Event<SessionCreatedEvent & IWaitUntil> =
this._onDidCreateSession.event;
private readonly _onWillCloseSession = this._register(
new AsyncEmitter<SessionWillCloseEvent & IWaitUntil>(),
);
readonly onWillCloseSession: Event<SessionWillCloseEvent & IWaitUntil> =
this._onWillCloseSession.event;
private readonly _onDidCloseSession = this._register(new Emitter<SessionClosedEvent>());
readonly onDidCloseSession: Event<SessionClosedEvent> = this._onDidCloseSession.event;
private readonly _onDidArchiveSession = this._register(new Emitter<SessionArchivedEvent>());
readonly onDidArchiveSession: Event<SessionArchivedEvent> = this._onDidArchiveSession.event;
private readonly _onDidForkSession = this._register(new Emitter<SessionForkedEvent>());
readonly onDidForkSession: Event<SessionForkedEvent> = this._onDidForkSession.event;
private readonly resuming = new Map<string, Promise<ISessionScopeHandle | undefined>>();
constructor(
private readonly instantiation: IInstantiationService,
@IWorkspaceContext private readonly workspaceContext: IWorkspaceContext,
@IBootstrapService private readonly bootstrap: IBootstrapService,
@IConfigService private readonly config: IConfigService,
@ISessionIndex private readonly index: ISessionIndex,
@ISessionIndexMirror private readonly indexMirror: ISessionIndexMirror,
@IAppendLogStore private readonly appendLogStore: IAppendLogStore,
@IAtomicDocumentStore private readonly docs: IAtomicDocumentStore,
@IHostFileSystem private readonly hostFs: IHostFileSystem,
@ICronTaskPersistence private readonly cronStore: ICronTaskPersistence,
@IEventService private readonly event: IEventService,
@ITelemetryService private readonly telemetry: ITelemetryService,
@IWorkspaceAgentProfileLoader
private readonly workspaceAgentProfileLoader: IWorkspaceAgentProfileLoader,
@IExtraAgentProfileLoader
private readonly extraAgentProfileLoader: IExtraAgentProfileLoader,
@IExplicitAgentProfileLoader
private readonly explicitAgentProfileLoader: IExplicitAgentProfileLoader,
@IUserAgentProfileLoader
private readonly userAgentProfileLoader: IUserAgentProfileLoader,
@IPluginAgentProfileLoader
private readonly pluginAgentProfileLoader: IPluginAgentProfileLoader,
@IWorkspaceDirs private readonly workspaceDirs: IWorkspaceDirs,
@IWorkspaceSkillCatalog private readonly workspaceSkillCatalog: IWorkspaceSkillCatalog,
@IWorkspaceInstructionsService private readonly workspaceInstructions: IWorkspaceInstructionsService,
@IWorkspaceMcpService private readonly workspaceMcp: IWorkspaceMcpService,
@IModelCatalog private readonly modelCatalog: IModelCatalog,
@IModelService private readonly models: IModelService,
@IProviderService private readonly providers: IProviderService,
@IFlagService private readonly flags: IFlagService,
onDispose?: () => void,
) {
super();
if (onDispose !== undefined) this._register({ dispose: onDispose });
}
private get workspaceId(): string {
return this.workspaceContext.workspaceId;
}
private get handlerScope(): string {
return this.workspaceContext.persistenceScope;
}
async create(opts: CreateSessionOptions): Promise<ISessionScopeHandle> {
const sessionId = opts.sessionId ?? createSessionId();
await this.workspaceSkillCatalog
.reloadSources(SESSION_CREATE_RELOAD_SKILL_SOURCES)
.catch(() => undefined);
const handle = await this.materializeSession({ ...opts, sessionId });
try {
const main =
opts.mainAgentBinding === undefined
? undefined
: await handle.accessor.get(IAgentLifecycleService).create({
agentId: MAIN_AGENT_ID,
binding: opts.mainAgentBinding,
});
if (this.config.get<boolean>(DEFAULT_PLAN_MODE_SECTION) === true) {
const planAgent = main ?? (await ensureMainAgent(handle));
await planAgent.accessor.get(IAgentPlanService).enter();
}
await this.appendSessionIndexEntry(sessionId, opts.workDir);
} catch (error) {
const sessionDir = handle.accessor.get(ISessionContext).sessionDir;
this.sessions.delete(sessionId);
await this.drainAgents(handle).catch(() => {});
handle.dispose();
await this.hostFs.remove(sessionDir).catch(() => {});
throw error;
}
await this.announceCreated({ sessionId, handle, source: 'startup' });
return handle;
}
private async assertSubagentModelPoolPreFlight(): Promise<void> {
await Promise.all([this.config.ready, this.models.ready, this.providers.ready]);
assertValidSubagentModelConfig(this.config, this.flags, this.modelCatalog);
}
private async materializeSession(opts: MaterializeSessionOptions): Promise<ISessionScopeHandle> {
const workspaceId = this.workspaceId;
const sessionScope = sessionScopeOf(this.handlerScope, opts.sessionId);
const sessionDir = sessionDirOf(this.bootstrap.homeDir, this.handlerScope, opts.sessionId);
const metaScope = sessionScope;
await this.assertSubagentModelPoolPreFlight();
await this.workspaceDirs.ready;
await this.workspaceDirs.mergeAdditionalDirs(opts.workDir, opts.additionalDirs ?? []);
const ctx: ISessionContext = {
_serviceBrand: undefined,
sessionId: opts.sessionId,
workspaceId,
sessionDir,
metaScope,
cwd: opts.workDir,
scope: (subKey?: string): string =>
subKey === undefined || subKey === '' ? sessionScope : `${sessionScope}/${subKey}`,
};
const handle = createScopedChildHandle(
this.instantiation,
LifecycleScope.Session,
opts.sessionId,
{
seeds: [
...sessionContextSeed(ctx),
[ITelemetryService, this.telemetry.withContext({ sessionId: opts.sessionId })],
...sessionAgentProfileCatalogSeed({
_serviceBrand: undefined,
workspaceKey: workspaceId,
}),
[ISessionSkillCatalogData, this.workspaceSkillCatalog.sessionData()],
[ISessionInstructionsProvider, this.workspaceInstructions.sessionProvider()],
[ISessionMcpHandle, this.workspaceMcp.sessionHandle()],
[ISessionWorkspaceInfo, this.workspaceDirs.sessionInfo()],
...sessionEphemeralMcpServersSeed(opts.mcpServers ?? {}),
],
configureContainer: (container) => {
this._onWillCreateSession.fire({
sessionId: opts.sessionId,
readSeed: (id) => container.invokeFunction((accessor) => accessor.get(id)),
contributeSeed: (id, value) => {
container.provide(id, value);
},
onSessionDispose: (dispose) => {
container.anchorKernelEntry(dispose, 'sessionLifecycle:willCreateParticipant');
},
});
},
},
) as ISessionScopeHandle;
try {
await handle.accessor.get(ISessionMetadata).ready;
await handle.accessor.get(ISessionToolPolicy).ready;
await Promise.all([
this.workspaceAgentProfileLoader.ready,
this.extraAgentProfileLoader.ready,
this.explicitAgentProfileLoader.ready,
this.userAgentProfileLoader.ready,
this.pluginAgentProfileLoader.ready,
]);
} catch (error) {
handle.dispose();
void this.explicitAgentProfileLoader.reload().catch(() => undefined);
throw error;
}
this.sessions.set(opts.sessionId, handle);
return handle;
}
private async appendSessionIndexEntry(sessionId: string, workDir: string): Promise<void> {
const sessionDir = sessionDirOf(this.bootstrap.homeDir, this.handlerScope, sessionId);
this.appendLogStore.append('', 'session_index.jsonl', {
sessionId,
sessionDir,
workDir,
});
await this.appendLogStore.flush();
}
private async announceCreated(event: SessionCreatedEvent): Promise<void> {
await this._onDidCreateSession.fireAsync(event, NO_ABORT);
event.handle.accessor
.get(ITelemetryService)
.track2('session_started', { resumed: event.source === 'resume' });
}
get(sessionId: string): ISessionScopeHandle | undefined {
if (this.resuming.has(sessionId)) return undefined;
return this.sessions.get(sessionId);
}
resume(sessionId: string, opts?: ResumeSessionOptions): Promise<ISessionScopeHandle | undefined> {
const inflight = this.resuming.get(sessionId);
if (inflight !== undefined) return inflight;
const live = this.sessions.get(sessionId);
if (live !== undefined) return Promise.resolve(live);
const promise = this.doResume(sessionId, opts)
.catch((error: unknown) => {
this.telemetry
.withContext({ sessionId })
.track2('session_load_failed', {
reason: isError2(error) ? error.code : error instanceof Error ? error.name : 'unknown',
});
throw error;
})
.finally(() => this.resuming.delete(sessionId));
this.resuming.set(sessionId, promise);
return promise;
}
async whenResumeSettled(sessionId: string): Promise<void> {
await this.resuming.get(sessionId)?.catch(() => undefined);
}
private async doResume(
sessionId: string,
opts?: ResumeSessionOptions,
): Promise<ISessionScopeHandle | undefined> {
const live = this.sessions.get(sessionId);
if (live !== undefined) return live;
const summary = await this.index.get(sessionId);
if (summary === undefined || summary.workspaceId !== this.workspaceId) return undefined;
const workDir = summary.cwd ?? this.workspaceContext.cwd;
const handle = await this.materializeSession({
sessionId,
workDir,
additionalDirs: opts?.additionalDirs,
mcpServers: opts?.mcpServers,
});
const agents = handle.accessor.get(IAgentLifecycleService);
if (agents.get(MAIN_AGENT_ID) === undefined) {
await agents.create({ agentId: MAIN_AGENT_ID });
}
await this.announceCreated({ sessionId, handle, source: 'resume' });
return handle;
}
list(): readonly ISessionScopeHandle[] {
const ready: ISessionScopeHandle[] = [];
for (const [id, handle] of this.sessions) {
if (!this.resuming.has(id)) ready.push(handle);
}
return ready;
}
async close(sessionId: string): Promise<void> {
const handle = this.sessions.get(sessionId);
if (handle === undefined) return;
await this.announceWillClose({ sessionId, handle, reason: 'exit' });
this.sessions.delete(sessionId);
await this.drainAgents(handle);
await drainSessionMetadataWrites();
await this.indexMirror.drain();
handle.dispose();
this._onDidCloseSession.fire({ sessionId });
}
async archive(sessionId: string): Promise<void> {
const handle = this.sessions.get(sessionId);
if (handle === undefined) return;
const meta = handle.accessor.get(ISessionMetadata);
await meta.setArchived(true);
await this.drainAgents(handle);
this.event.publish(new SessionArchived({ payload: { sessionId } }));
await this.announceWillClose({ sessionId, handle, reason: 'archive' });
this.sessions.delete(sessionId);
await drainSessionMetadataWrites();
await this.indexMirror.drain();
handle.dispose();
this._onDidArchiveSession.fire({ sessionId });
}
async restore(
sessionId: string,
opts?: ResumeSessionOptions,
): Promise<ISessionScopeHandle | undefined> {
const handle = await this.resume(sessionId, opts);
if (handle === undefined) return undefined;
await handle.accessor.get(ISessionMetadata).setArchived(false);
return handle;
}
async delete(sessionId: string): Promise<void> {
const inflight = this.resuming.get(sessionId);
if (inflight !== undefined) {
await inflight.catch(() => undefined);
}
const handle = this.sessions.get(sessionId);
const summary = await this.index.get(sessionId);
const persistedHere = summary !== undefined && summary.workspaceId === this.workspaceId;
if (handle === undefined && !persistedHere) {
throw new Error2(ErrorCodes.SESSION_NOT_FOUND, `session ${sessionId} does not exist`);
}
if (handle !== undefined) {
await this.close(sessionId);
}
await this.hostFs.remove(sessionDirOf(this.bootstrap.homeDir, this.handlerScope, sessionId));
await this.index.remove(sessionId);
this.appendLogStore.append('', 'session_index.jsonl', { sessionId, deleted: true });
await this.appendLogStore.flush();
}
private async announceWillClose(event: SessionWillCloseEvent): Promise<void> {
await this._onWillCloseSession.fireAsync(event, NO_ABORT);
}
private async drainAgents(handle: ISessionScopeHandle): Promise<void> {
const agentLifecycle = handle.accessor.get(IAgentLifecycleService);
for (const agent of agentLifecycle.list()) {
await agentLifecycle.remove(agent.id);
}
}
async fork(opts: ForkSessionOptions): Promise<ISessionScopeHandle> {
const sourceId = opts.sourceSessionId;
const sourceHandle = this.sessions.get(sourceId);
const indexSummary = await this.index.get(sourceId);
if (
(sourceHandle === undefined && indexSummary === undefined) ||
(indexSummary !== undefined && indexSummary.workspaceId !== this.workspaceId)
) {
throw new Error2(ErrorCodes.SESSION_NOT_FOUND, `session ${sourceId} does not exist`);
}
if (sourceHandle !== undefined) {
for (const agent of sourceHandle.accessor.get(IAgentLifecycleService).list()) {
if (agent.accessor.get(IAgentActivityView).state().turn !== undefined) {
throw new Error2(
ErrorCodes.SESSION_FORK_ACTIVE_TURN,
`Session "${sourceId}" cannot be forked while a turn is running`,
{ details: { sessionId: sourceId } },
);
}
}
}
assertForkTurnIndex(opts.turnIndex);
let targetId: string | undefined;
let target: ISessionScopeHandle | undefined;
let targetSessionDir: string | undefined;
try {
await this.assertSubagentModelPoolPreFlight();
// A turn that just ended may still have its outcome write queued;
// settle pending metadata writes before reading the source for
// inheritance, or the fork could copy a stale (or absent) outcome.
await drainSessionMetadataWrites();
const sourceMeta =
sourceHandle !== undefined
? await sourceHandle.accessor.get(ISessionMetadata).read()
: await this.readMetaFromDisk(sourceId);
targetId = opts.newSessionId ?? createSessionId();
if (this.sessions.has(targetId) || (await this.index.get(targetId)) !== undefined) {
throw new Error2(
ErrorCodes.SESSION_ALREADY_EXISTS,
`Session "${targetId}" already exists`,
);
}
const turnSlice =
opts.turnIndex === undefined
? undefined
: sliceMainRecordsAtTurn(
await this.readSourceWireRecords(sourceHandle, sourceId, MAIN_AGENT_ID),
sourceId,
opts.turnIndex,
);
targetSessionDir = sessionDirOf(this.bootstrap.homeDir, this.handlerScope, targetId);
await this.copySessionFiles(
sessionDirOf(this.bootstrap.homeDir, this.handlerScope, sourceId),
targetSessionDir,
);
target = await this.materializeSession({
sessionId: targetId,
workDir: this.workspaceContext.cwd,
});
const targetCtx = target.accessor.get(ISessionContext);
const targetMeta = target.accessor.get(ISessionMetadata);
const sourceAgents = sourceMeta?.agents ?? {};
const agentIds = Object.keys(sourceAgents);
const retainedAgentIds: string[] = [];
for (const agentId of agentIds) {
let slicedRecords: readonly WireRecord[] | undefined;
if (turnSlice !== undefined) {
if (agentId === MAIN_AGENT_ID) {
slicedRecords = turnSlice.records;
} else {
const subagentRecords = sliceSubagentRecordsAtTime(
await this.readSourceWireRecords(sourceHandle, sourceId, agentId),
turnSlice.cutoffTime,
);
if (subagentRecords.length === 0) continue;
slicedRecords = subagentRecords;
}
}
await this.copyAgentWire({
sourceHandle,
sourceSessionId: sourceId,
agentId,
targetSessionId: targetCtx.sessionId,
records: slicedRecords,
});
retainedAgentIds.push(agentId);
}
if (turnSlice !== undefined) {
await this.pruneTruncatedForkFiles(targetSessionDir, agentIds, retainedAgentIds);
}
const title = opts.title ?? `Fork: ${sourceMeta?.title || sourceId}`;
for (const agentId of retainedAgentIds) {
const sourceAgent = sourceAgents[agentId]!;
await target.accessor.get(IAgentLifecycleService).create({
agentId,
forkedFrom: sourceAgent.forkedFrom,
labels: labelsFromAgentMeta(sourceAgent),
});
}
await targetMeta.update({
title,
titleKind: opts.title !== undefined ? 'custom' : 'replaceable',
forkedFrom: sourceId,
archived: false,
updatedAt: toEpochMs(sourceMeta?.updatedAt) || Date.now(),
lastPrompt: turnSlice === undefined ? sourceMeta?.lastPrompt : turnSlice.lastPrompt,
// The fork continues the source's conversation, so it inherits the
// last turn's outcome too — otherwise a restart would drop a failure
// the warm fork was still reporting.
lastTurnReason: sourceMeta?.lastTurnReason,
custom: forkCustomMetadata(sourceMeta?.custom, opts.metadata),
});
if (turnSlice === undefined) {
await this.duplicateCronTasks(sourceId, targetId);
}
await this.appendSessionIndexEntry(targetId, this.workspaceContext.cwd);
this._onDidForkSession.fire({
sourceSessionId: sourceId,
sessionId: targetId,
handle: target,
});
await this.announceCreated({ sessionId: targetId, handle: target, source: 'fork' });
return target;
} catch (error) {
if (targetId !== undefined) {
this.sessions.delete(targetId);
}
if (target !== undefined) {
try {
target.dispose();
} catch {
}
}
if (targetSessionDir !== undefined) {
await this.hostFs.remove(targetSessionDir).catch(() => {});
}
throw error;
}
}
async createChild(opts: CreateChildSessionOptions): Promise<ISessionScopeHandle> {
const title =
opts.title ??
`Child: ${(await this.resolveSourceTitle(opts.sourceSessionId)) ?? opts.sourceSessionId}`;
const metadata = {
...opts.metadata,
[PARENT_SESSION_ID_KEY]: opts.sourceSessionId,
[CHILD_SESSION_KIND_KEY]: CHILD_SESSION_KIND,
};
return this.fork({
sourceSessionId: opts.sourceSessionId,
newSessionId: opts.newSessionId,
title,
metadata,
});
}
private async resolveSourceTitle(sourceId: string): Promise<string | undefined> {
const live = this.sessions.get(sourceId);
if (live !== undefined) {
return (await live.accessor.get(ISessionMetadata).read()).title;
}
return (await this.index.get(sourceId))?.title;
}
private async copyAgentWire(args: {
readonly sourceHandle: ISessionScopeHandle | undefined;
readonly sourceSessionId: string;
readonly agentId: string;
readonly targetSessionId: string;
readonly records?: readonly WireRecord[];
}): Promise<void> {
const records = [
...(args.records ??
(await this.readSourceWireRecords(args.sourceHandle, args.sourceSessionId, args.agentId))),
];
if (records.length === 0) {
records.push(createWireMetadataRecord());
} else if (records[0]?.type !== 'metadata') {
records.unshift(createWireMetadataRecord());
}
records.push(forkedRecord());
await this.appendLogStore.rewrite(
agentScopeOf(sessionScopeOf(this.handlerScope, args.targetSessionId), args.agentId),
AGENT_WIRE_RECORD_KEY,
records,
);
}
private async readSourceWireRecords(
sourceHandle: ISessionScopeHandle | undefined,
sourceSessionId: string,
agentId: string,
): Promise<WireRecord[]> {
if (sourceHandle !== undefined) {
const agentHandle = sourceHandle.accessor.get(IAgentLifecycleService).get(agentId);
if (agentHandle !== undefined) {
await agentHandle.accessor.get(IEventDispatcher).flush();
}
}
return collect(
this.appendLogStore.read<WireRecord>(
agentScopeOf(sessionScopeOf(this.handlerScope, sourceSessionId), agentId),
AGENT_WIRE_RECORD_KEY,
),
);
}
private async pruneTruncatedForkFiles(
targetSessionDir: string,
agentIds: readonly string[],
retainedAgentIds: readonly string[],
): Promise<void> {
const retained = new Set(retainedAgentIds);
const removals: Promise<void>[] = [];
for (const agentId of agentIds) {
if (retained.has(agentId)) continue;
removals.push(this.hostFs.remove(join(targetSessionDir, 'agents', agentId)));
}
for (const agentId of retainedAgentIds) {
const agentDir = join(targetSessionDir, 'agents', agentId);
removals.push(this.hostFs.remove(join(agentDir, 'tasks')));
removals.push(this.hostFs.remove(join(agentDir, 'cron')));
}
await Promise.all(removals);
}
private async copySessionFiles(sourceDir: string, targetDir: string): Promise<void> {
let entries: readonly HostDirEntry[];
try {
entries = await this.hostFs.readdir(sourceDir);
} catch (error) {
if (isMissingFileError(error)) return;
throw error;
}
await this.copySessionDirEntries(sourceDir, targetDir, entries, '');
}
private async copySessionDirEntries(
sourceDir: string,
targetDir: string,
entries: readonly HostDirEntry[],
relBase: string,
): Promise<void> {
for (const entry of entries) {
const rel = relBase === '' ? entry.name : `${relBase}/${entry.name}`;
if (rel === 'state.json' || rel === 'logs' || rel === 'upcoming-goals.json' || entry.name === AGENT_WIRE_RECORD_KEY) {
continue;
}
if (entry.isSymbolicLink === true) continue;
const sourcePath = join(sourceDir, entry.name);
const targetPath = join(targetDir, entry.name);
if (entry.isDirectory) {
let children: readonly HostDirEntry[];
try {
children = await this.hostFs.readdir(sourcePath);
} catch (error) {
if (isMissingFileError(error)) continue;
throw error;
}
await this.hostFs.mkdir(targetPath, { recursive: true });
await this.copySessionDirEntries(sourcePath, targetPath, children, rel);
} else if (entry.isFile) {
const data = await this.hostFs.readBytes(sourcePath);
await this.hostFs.mkdir(targetDir, { recursive: true });
await this.hostFs.writeBytes(targetPath, data);
}
}
}
private async duplicateCronTasks(sourceId: string, targetId: string): Promise<void> {
const tasks = await this.cronStore.list({ workspaceId: this.workspaceId });
for (const task of tasks) {
if (task.tags?.[CRON_SESSION_TAG] !== sourceId) continue;
const clone: CronTask = {
...task,
id: ulid(),
tags: { ...task.tags, [CRON_SESSION_TAG]: targetId },
};
await this.cronStore.save(this.workspaceId, clone);
}
}
private async readMetaFromDisk(sessionId: string): Promise<SessionMeta | undefined> {
return this.docs.get<SessionMeta>(sessionScopeOf(this.handlerScope, sessionId), 'state.json');
}
}
async function collect<T>(iterable: AsyncIterable<T>): Promise<T[]> {
const items: T[] = [];
for await (const item of iterable) items.push(item);
return items;
}
function isMissingFileError(error: unknown): boolean {
const unwrapped = unwrapErrorCause(error);
if (unwrapped === null || typeof unwrapped !== 'object') return false;
const code = (unwrapped as { readonly code?: unknown }).code;
return code === 'ENOENT';
}
function createSessionId(): string {
return `session_${randomUUID()}`;
}
function forkedRecord(): WireRecord {
return { type: 'forked', time: Date.now() };
}
function forkCustomMetadata(
source: Record<string, unknown> | undefined,
input: Record<string, unknown> | undefined,
): Record<string, unknown> | undefined {
const merged = { ...withoutGoal(source), ...withoutGoal(input) };
return Object.keys(merged).length === 0 ? undefined : merged;
}
function withoutGoal(value: Record<string, unknown> | undefined): Record<string, unknown> {
if (value === undefined) return {};
const { goal: _drop, ...rest } = value as { goal?: unknown; [key: string]: unknown };
return rest;
}