forked from ComposioHQ/agent-orchestrator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-manager.ts
More file actions
1168 lines (1053 loc) · 38.2 KB
/
session-manager.ts
File metadata and controls
1168 lines (1053 loc) · 38.2 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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Session Manager — CRUD for agent sessions.
*
* Orchestrates Runtime, Agent, and Workspace plugins to:
* - Spawn new sessions (create workspace → create runtime → launch agent)
* - List sessions (from metadata + live runtime checks)
* - Kill sessions (agent → runtime → workspace cleanup)
* - Cleanup completed sessions (PR merged / issue closed)
* - Send messages to running sessions
*
* Reference: scripts/claude-ao-session, scripts/send-to-session
*/
import { statSync, existsSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
import { join } from "node:path";
import {
isIssueNotFoundError,
isRestorable,
NON_RESTORABLE_STATUSES,
SessionNotRestorableError,
WorkspaceMissingError,
type SessionManager,
type Session,
type SessionId,
type SessionSpawnConfig,
type OrchestratorSpawnConfig,
type SessionStatus,
type CleanupResult,
type OrchestratorConfig,
type ProjectConfig,
type Runtime,
type Agent,
type Workspace,
type Tracker,
type SCM,
type PluginRegistry,
type RuntimeHandle,
type Issue,
PR_STATE,
} from "./types.js";
import {
readMetadataRaw,
readArchivedMetadataRaw,
writeMetadata,
updateMetadata,
deleteMetadata,
listMetadata,
reserveSessionId,
} from "./metadata.js";
import { buildPrompt } from "./prompt-builder.js";
import {
getSessionsDir,
getProjectBaseDir,
generateTmuxName,
generateConfigHash,
validateAndStoreOrigin,
} from "./paths.js";
/** Escape regex metacharacters in a string. */
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/** Get the next session number for a project. */
function getNextSessionNumber(existingSessions: string[], prefix: string): number {
let max = 0;
const pattern = new RegExp(`^${escapeRegex(prefix)}-(\\d+)$`);
for (const name of existingSessions) {
const match = name.match(pattern);
if (match) {
const num = parseInt(match[1], 10);
if (num > max) max = num;
}
}
return max + 1;
}
/** Safely parse JSON, returning null on failure. */
function safeJsonParse<T>(str: string): T | null {
try {
return JSON.parse(str) as T;
} catch {
return null;
}
}
/** Valid session statuses for validation. */
const VALID_STATUSES: ReadonlySet<string> = new Set([
"spawning",
"working",
"pr_open",
"ci_failed",
"review_pending",
"changes_requested",
"approved",
"mergeable",
"merged",
"cleanup",
"needs_input",
"stuck",
"errored",
"killed",
"done",
"terminated",
]);
/** Validate and normalize a status string. */
function validateStatus(raw: string | undefined): SessionStatus {
// Bash scripts write "starting" — treat as "working"
if (raw === "starting") return "working";
if (raw && VALID_STATUSES.has(raw)) return raw as SessionStatus;
return "spawning";
}
/** Reconstruct a Session object from raw metadata key=value pairs. */
function metadataToSession(
sessionId: SessionId,
meta: Record<string, string>,
createdAt?: Date,
modifiedAt?: Date,
): Session {
return {
id: sessionId,
projectId: meta["project"] ?? "",
status: validateStatus(meta["status"]),
activity: null,
branch: meta["branch"] || null,
issueId: meta["issue"] || null,
pr: meta["pr"]
? (() => {
// Parse owner/repo from GitHub PR URL: https://github.com/owner/repo/pull/123
const prUrl = meta["pr"];
const ghMatch = prUrl.match(/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/);
return {
number: ghMatch
? parseInt(ghMatch[3], 10)
: parseInt(prUrl.match(/\/(\d+)$/)?.[1] ?? "0", 10),
url: prUrl,
title: "",
owner: ghMatch?.[1] ?? "",
repo: ghMatch?.[2] ?? "",
branch: meta["branch"] ?? "",
baseBranch: "",
isDraft: false,
};
})()
: null,
workspacePath: meta["worktree"] || null,
runtimeHandle: meta["runtimeHandle"]
? safeJsonParse<RuntimeHandle>(meta["runtimeHandle"])
: null,
agentInfo: meta["summary"] ? { summary: meta["summary"], agentSessionId: null } : null,
createdAt: meta["createdAt"] ? new Date(meta["createdAt"]) : (createdAt ?? new Date()),
lastActivityAt: modifiedAt ?? new Date(),
restoredAt: meta["restoredAt"] ? new Date(meta["restoredAt"]) : undefined,
metadata: meta,
};
}
export interface SessionManagerDeps {
config: OrchestratorConfig;
registry: PluginRegistry;
}
/** Create a SessionManager instance. */
export function createSessionManager(deps: SessionManagerDeps): SessionManager {
const { config, registry } = deps;
/**
* Get the sessions directory for a project.
*/
function getProjectSessionsDir(project: ProjectConfig): string {
return getSessionsDir(config.configPath, project.path);
}
/**
* List all session files across all projects (or filtered by projectId).
* Scans project-specific directories under ~/.agent-orchestrator/{hash}-{projectId}/sessions/
*
* Note: projectId is the config key (e.g., "test-project"), not the path basename.
*/
function listAllSessions(projectIdFilter?: string): { sessionName: string; projectId: string }[] {
const results: { sessionName: string; projectId: string }[] = [];
// Scan each project's sessions directory
for (const [projectKey, project] of Object.entries(config.projects)) {
// Use config key as projectId for consistency with metadata
const projectId = projectKey;
// Filter by project if specified
if (projectIdFilter && projectId !== projectIdFilter) continue;
const sessionsDir = getSessionsDir(config.configPath, project.path);
if (!existsSync(sessionsDir)) continue;
const files = readdirSync(sessionsDir);
for (const file of files) {
if (file === "archive" || file.startsWith(".")) continue;
const fullPath = join(sessionsDir, file);
try {
if (statSync(fullPath).isFile()) {
results.push({ sessionName: file, projectId });
}
} catch {
// Skip files that can't be stat'd
}
}
}
return results;
}
/** Resolve which plugins to use for a project. */
function resolvePlugins(project: ProjectConfig, agentOverride?: string) {
const runtime = registry.get<Runtime>("runtime", project.runtime ?? config.defaults.runtime);
const agent = registry.get<Agent>("agent", agentOverride ?? project.agent ?? config.defaults.agent);
const workspace = registry.get<Workspace>(
"workspace",
project.workspace ?? config.defaults.workspace,
);
const tracker = project.tracker
? registry.get<Tracker>("tracker", project.tracker.plugin)
: null;
const scm = project.scm ? registry.get<SCM>("scm", project.scm.plugin) : null;
return { runtime, agent, workspace, tracker, scm };
}
/**
* Ensure session has a runtime handle (fabricate one if missing) and enrich
* with live runtime state + activity detection. Used by both list() and get().
*/
async function ensureHandleAndEnrich(
session: Session,
sessionName: string,
project: ProjectConfig,
plugins: ReturnType<typeof resolvePlugins>,
): Promise<void> {
const handleFromMetadata = session.runtimeHandle !== null;
if (!handleFromMetadata) {
session.runtimeHandle = {
id: sessionName,
runtimeName: project.runtime ?? config.defaults.runtime,
data: {},
};
}
await enrichSessionWithRuntimeState(session, plugins, handleFromMetadata);
}
/**
* Enrich session with live runtime state (alive/exited) and activity detection.
* Mutates the session object in place.
*/
const TERMINAL_SESSION_STATUSES = new Set([
"killed", "done", "merged", "terminated", "cleanup",
]);
async function enrichSessionWithRuntimeState(
session: Session,
plugins: ReturnType<typeof resolvePlugins>,
handleFromMetadata: boolean,
): Promise<void> {
// Skip all subprocess/IO work for sessions already known to be terminal.
if (TERMINAL_SESSION_STATUSES.has(session.status)) {
session.activity = "exited";
return;
}
// Check runtime liveness — but only if the handle came from metadata.
// Fabricated handles (constructed as fallback for external sessions) should
// NOT override status to "killed" — we don't know if the session ever had
// a tmux session, and we'd clobber meaningful statuses like "pr_open".
if (handleFromMetadata && session.runtimeHandle && plugins.runtime) {
try {
const alive = await plugins.runtime.isAlive(session.runtimeHandle);
if (!alive) {
session.status = "killed";
session.activity = "exited";
return;
}
} catch {
// Can't check liveness — continue to activity detection
}
}
// Detect activity independently of runtime handle.
// Activity detection reads JSONL files on disk — it only needs workspacePath,
// not a runtime handle. Gating on runtimeHandle caused sessions created by
// external scripts (which don't store runtimeHandle) to always show "unknown".
if (plugins.agent) {
try {
const detected = await plugins.agent.getActivityState(session, config.readyThresholdMs);
if (detected !== null) {
session.activity = detected.state;
if (detected.timestamp && detected.timestamp > session.lastActivityAt) {
session.lastActivityAt = detected.timestamp;
}
}
} catch {
// Can't detect activity — keep existing value
}
// Enrich with live agent session info (summary, cost).
try {
const info = await plugins.agent.getSessionInfo(session);
if (info) {
session.agentInfo = info;
}
} catch {
// Can't get session info — keep existing values
}
}
}
// Define methods as local functions so `this` is not needed
async function spawn(spawnConfig: SessionSpawnConfig): Promise<Session> {
const project = config.projects[spawnConfig.projectId];
if (!project) {
throw new Error(`Unknown project: ${spawnConfig.projectId}`);
}
const plugins = resolvePlugins(project);
if (!plugins.runtime) {
throw new Error(`Runtime plugin '${project.runtime ?? config.defaults.runtime}' not found`);
}
// Allow --agent override to swap the agent plugin for this session
if (spawnConfig.agent) {
const overrideAgent = registry.get<Agent>("agent", spawnConfig.agent);
if (!overrideAgent) {
throw new Error(`Agent plugin '${spawnConfig.agent}' not found`);
}
plugins.agent = overrideAgent;
}
if (!plugins.agent) {
throw new Error(`Agent plugin '${project.agent ?? config.defaults.agent}' not found`);
}
// Validate issue exists BEFORE creating any resources
let resolvedIssue: Issue | undefined;
if (spawnConfig.issueId && plugins.tracker) {
try {
// Fetch and validate the issue exists
resolvedIssue = await plugins.tracker.getIssue(spawnConfig.issueId, project);
} catch (err) {
// Issue fetch failed - determine why
if (isIssueNotFoundError(err)) {
// Ad-hoc issue string — proceed without tracker context.
// Branch will be generated as feat/{issueId} (line 329-331)
} else {
// Other error (auth, network, etc) - fail fast
throw new Error(`Failed to fetch issue ${spawnConfig.issueId}: ${err}`, { cause: err });
}
}
}
// Get the sessions directory for this project
const sessionsDir = getProjectSessionsDir(project);
// Validate and store .origin file (new architecture only)
if (config.configPath) {
validateAndStoreOrigin(config.configPath, project.path);
}
// Determine session ID — atomically reserve to prevent concurrent collisions
const existingSessions = listMetadata(sessionsDir);
let num = getNextSessionNumber(existingSessions, project.sessionPrefix);
let sessionId: string;
let tmuxName: string | undefined;
for (let attempts = 0; attempts < 10; attempts++) {
sessionId = `${project.sessionPrefix}-${num}`;
// Generate tmux name if using new architecture
if (config.configPath) {
tmuxName = generateTmuxName(config.configPath, project.sessionPrefix, num);
}
if (reserveSessionId(sessionsDir, sessionId)) break;
num++;
if (attempts === 9) {
throw new Error(
`Failed to reserve session ID after 10 attempts (prefix: ${project.sessionPrefix})`,
);
}
}
// Reassign to satisfy TypeScript's flow analysis (not redundant from compiler's perspective)
sessionId = `${project.sessionPrefix}-${num}`;
if (config.configPath) {
tmuxName = generateTmuxName(config.configPath, project.sessionPrefix, num);
}
// Determine branch name — explicit branch always takes priority
let branch: string;
if (spawnConfig.branch) {
branch = spawnConfig.branch;
} else if (spawnConfig.issueId && plugins.tracker && resolvedIssue) {
branch = plugins.tracker.branchName(spawnConfig.issueId, project);
} else if (spawnConfig.issueId) {
// If the issueId is already branch-safe (e.g. "INT-9999"), use as-is.
// Otherwise sanitize free-text (e.g. "fix login bug") into a valid slug.
const id = spawnConfig.issueId;
const isBranchSafe =
/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id) && !id.includes("..");
const slug = isBranchSafe
? id
: id
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.slice(0, 60)
.replace(/^-+|-+$/g, "");
branch = `feat/${slug || sessionId}`;
} else {
branch = `session/${sessionId}`;
}
// Create workspace (if workspace plugin is available)
let workspacePath = project.path;
if (plugins.workspace) {
try {
const wsInfo = await plugins.workspace.create({
projectId: spawnConfig.projectId,
project,
sessionId,
branch,
});
workspacePath = wsInfo.path;
// Run post-create hooks — clean up workspace on failure
if (plugins.workspace.postCreate) {
try {
await plugins.workspace.postCreate(wsInfo, project);
} catch (err) {
if (workspacePath !== project.path) {
try {
await plugins.workspace.destroy(workspacePath);
} catch {
/* best effort */
}
}
throw err;
}
}
} catch (err) {
// Clean up reserved session ID on workspace failure
try {
deleteMetadata(sessionsDir, sessionId, false);
} catch {
/* best effort */
}
throw err;
}
}
// Generate prompt with validated issue
let issueContext: string | undefined;
if (spawnConfig.issueId && plugins.tracker && resolvedIssue) {
try {
issueContext = await plugins.tracker.generatePrompt(spawnConfig.issueId, project);
} catch {
// Non-fatal: continue without detailed issue context
// Silently ignore errors - caller can check if issueContext is undefined
}
}
const composedPrompt = buildPrompt({
project,
projectId: spawnConfig.projectId,
issueId: spawnConfig.issueId,
issueContext,
userPrompt: spawnConfig.prompt,
});
// Get agent launch config and create runtime — clean up workspace on failure
const agentLaunchConfig = {
sessionId,
projectConfig: project,
issueId: spawnConfig.issueId,
prompt: composedPrompt ?? spawnConfig.prompt,
permissions: project.agentConfig?.permissions,
model: project.agentConfig?.model,
};
let handle: RuntimeHandle;
try {
const launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
const environment = plugins.agent.getEnvironment(agentLaunchConfig);
handle = await plugins.runtime.create({
sessionId: tmuxName ?? sessionId, // Use tmux name for runtime if available
workspacePath,
launchCommand,
environment: {
...environment,
AO_SESSION: sessionId,
AO_DATA_DIR: sessionsDir, // Pass sessions directory (not root dataDir)
AO_SESSION_NAME: sessionId, // User-facing session name
...(tmuxName && { AO_TMUX_NAME: tmuxName }), // Tmux session name if using new arch
},
});
} catch (err) {
// Clean up workspace and reserved ID if agent config or runtime creation failed
if (plugins.workspace && workspacePath !== project.path) {
try {
await plugins.workspace.destroy(workspacePath);
} catch {
/* best effort */
}
}
try {
deleteMetadata(sessionsDir, sessionId, false);
} catch {
/* best effort */
}
throw err;
}
// Write metadata and run post-launch setup — clean up on failure
const session: Session = {
id: sessionId,
projectId: spawnConfig.projectId,
status: "spawning",
activity: "active",
branch,
issueId: spawnConfig.issueId ?? null,
pr: null,
workspacePath,
runtimeHandle: handle,
agentInfo: null,
createdAt: new Date(),
lastActivityAt: new Date(),
metadata: {},
};
try {
writeMetadata(sessionsDir, sessionId, {
worktree: workspacePath,
branch,
status: "spawning",
tmuxName, // Store tmux name for mapping
issue: spawnConfig.issueId,
project: spawnConfig.projectId,
agent: plugins.agent.name, // Persist agent name for lifecycle manager
createdAt: new Date().toISOString(),
runtimeHandle: JSON.stringify(handle),
});
if (plugins.agent.postLaunchSetup) {
await plugins.agent.postLaunchSetup(session);
}
} catch (err) {
// Clean up runtime and workspace on post-launch failure
try {
await plugins.runtime.destroy(handle);
} catch {
/* best effort */
}
if (plugins.workspace && workspacePath !== project.path) {
try {
await plugins.workspace.destroy(workspacePath);
} catch {
/* best effort */
}
}
try {
deleteMetadata(sessionsDir, sessionId, false);
} catch {
/* best effort */
}
throw err;
}
// Send initial prompt post-launch for agents that need it (e.g. Claude Code
// exits after -p, so we send the prompt after it starts in interactive mode).
// This is intentionally outside the try/catch above — a prompt delivery failure
// should NOT destroy the session. The agent is running; user can retry with `ao send`.
if (plugins.agent.promptDelivery === "post-launch" && agentLaunchConfig.prompt) {
try {
// Wait for agent to start and be ready for input
await new Promise((resolve) => setTimeout(resolve, 5_000));
await plugins.runtime.sendMessage(handle, agentLaunchConfig.prompt);
} catch {
// Non-fatal: agent is running but didn't receive the initial prompt.
// User can retry with `ao send`.
}
}
return session;
}
async function spawnOrchestrator(orchestratorConfig: OrchestratorSpawnConfig): Promise<Session> {
const project = config.projects[orchestratorConfig.projectId];
if (!project) {
throw new Error(`Unknown project: ${orchestratorConfig.projectId}`);
}
const plugins = resolvePlugins(project);
if (!plugins.runtime) {
throw new Error(`Runtime plugin '${project.runtime ?? config.defaults.runtime}' not found`);
}
if (!plugins.agent) {
throw new Error(`Agent plugin '${project.agent ?? config.defaults.agent}' not found`);
}
const sessionId = `${project.sessionPrefix}-orchestrator`;
// Generate tmux name if using new architecture
let tmuxName: string | undefined;
if (config.configPath) {
const hash = generateConfigHash(config.configPath);
tmuxName = `${hash}-${sessionId}`;
}
// Get the sessions directory for this project
const sessionsDir = getProjectSessionsDir(project);
// Validate and store .origin file
if (config.configPath) {
validateAndStoreOrigin(config.configPath, project.path);
}
// Setup agent hooks for automatic metadata updates
if (plugins.agent.setupWorkspaceHooks) {
await plugins.agent.setupWorkspaceHooks(project.path, { dataDir: sessionsDir });
}
// Write system prompt to a file to avoid shell/tmux truncation.
// Long prompts (2000+ chars) get mangled when inlined in shell commands
// via tmux send-keys or paste-buffer. File-based approach is reliable.
let systemPromptFile: string | undefined;
if (orchestratorConfig.systemPrompt) {
const baseDir = getProjectBaseDir(config.configPath, project.path);
mkdirSync(baseDir, { recursive: true });
systemPromptFile = join(baseDir, "orchestrator-prompt.md");
writeFileSync(systemPromptFile, orchestratorConfig.systemPrompt, "utf-8");
}
// Get agent launch config — uses systemPromptFile, no issue/tracker interaction.
// Orchestrator ALWAYS gets skip permissions — it must run ao CLI commands autonomously.
const agentLaunchConfig = {
sessionId,
projectConfig: project,
permissions: "skip" as const,
model: project.agentConfig?.model,
systemPromptFile,
};
const launchCommand = plugins.agent.getLaunchCommand(agentLaunchConfig);
const environment = plugins.agent.getEnvironment(agentLaunchConfig);
const handle = await plugins.runtime.create({
sessionId: tmuxName ?? sessionId,
workspacePath: project.path,
launchCommand,
environment: {
...environment,
AO_SESSION: sessionId,
AO_DATA_DIR: sessionsDir,
AO_SESSION_NAME: sessionId,
...(tmuxName && { AO_TMUX_NAME: tmuxName }),
},
});
// Write metadata and run post-launch setup
const session: Session = {
id: sessionId,
projectId: orchestratorConfig.projectId,
status: "working",
activity: "active",
branch: project.defaultBranch,
issueId: null,
pr: null,
workspacePath: project.path,
runtimeHandle: handle,
agentInfo: null,
createdAt: new Date(),
lastActivityAt: new Date(),
metadata: {},
};
try {
writeMetadata(sessionsDir, sessionId, {
worktree: project.path,
branch: project.defaultBranch,
status: "working",
role: "orchestrator",
tmuxName,
project: orchestratorConfig.projectId,
createdAt: new Date().toISOString(),
runtimeHandle: JSON.stringify(handle),
});
if (plugins.agent.postLaunchSetup) {
await plugins.agent.postLaunchSetup(session);
}
} catch (err) {
// Clean up runtime on post-launch failure
try {
await plugins.runtime.destroy(handle);
} catch {
/* best effort */
}
try {
deleteMetadata(sessionsDir, sessionId, false);
} catch {
/* best effort */
}
throw err;
}
return session;
}
async function list(projectId?: string): Promise<Session[]> {
const allSessions = listAllSessions(projectId);
const sessionPromises = allSessions.map(async ({ sessionName, projectId: sessionProjectId }) => {
const project = config.projects[sessionProjectId];
if (!project) return null;
const sessionsDir = getProjectSessionsDir(project);
const raw = readMetadataRaw(sessionsDir, sessionName);
if (!raw) return null;
// Get file timestamps for createdAt/lastActivityAt
let createdAt: Date | undefined;
let modifiedAt: Date | undefined;
try {
const metaPath = join(sessionsDir, sessionName);
const stats = statSync(metaPath);
createdAt = stats.birthtime;
modifiedAt = stats.mtime;
} catch {
// If stat fails, timestamps will fall back to current time
}
const session = metadataToSession(sessionName, raw, createdAt, modifiedAt);
const plugins = resolvePlugins(project, raw["agent"]);
// Cap per-session enrichment at 2s — subprocess calls (tmux/ps) can be
// slow under load. If we time out, session keeps its metadata values.
const enrichTimeout = new Promise<void>((resolve) => setTimeout(resolve, 2_000));
await Promise.race([ensureHandleAndEnrich(session, sessionName, project, plugins), enrichTimeout]);
return session;
});
const results = await Promise.all(sessionPromises);
return results.filter((s): s is Session => s !== null);
}
async function get(sessionId: SessionId): Promise<Session | null> {
// Try to find the session in any project's sessions directory
for (const project of Object.values(config.projects)) {
const sessionsDir = getProjectSessionsDir(project);
const raw = readMetadataRaw(sessionsDir, sessionId);
if (!raw) continue;
// Get file timestamps for createdAt/lastActivityAt
let createdAt: Date | undefined;
let modifiedAt: Date | undefined;
try {
const metaPath = join(sessionsDir, sessionId);
const stats = statSync(metaPath);
createdAt = stats.birthtime;
modifiedAt = stats.mtime;
} catch {
// If stat fails, timestamps will fall back to current time
}
const session = metadataToSession(sessionId, raw, createdAt, modifiedAt);
const plugins = resolvePlugins(project, raw["agent"]);
await ensureHandleAndEnrich(session, sessionId, project, plugins);
return session;
}
return null;
}
async function kill(sessionId: SessionId): Promise<void> {
// Find the session in any project's sessions directory
let raw: Record<string, string> | null = null;
let sessionsDir: string | null = null;
let project: ProjectConfig | undefined;
for (const proj of Object.values(config.projects)) {
const dir = getProjectSessionsDir(proj);
const metadata = readMetadataRaw(dir, sessionId);
if (metadata) {
raw = metadata;
sessionsDir = dir;
project = proj;
break;
}
}
if (!raw || !sessionsDir) {
throw new Error(`Session ${sessionId} not found`);
}
// Destroy runtime — prefer handle.runtimeName to find the correct plugin
if (raw["runtimeHandle"]) {
const handle = safeJsonParse<RuntimeHandle>(raw["runtimeHandle"]);
if (handle) {
const runtimePlugin = registry.get<Runtime>(
"runtime",
handle.runtimeName ??
(project ? (project.runtime ?? config.defaults.runtime) : config.defaults.runtime),
);
if (runtimePlugin) {
try {
await runtimePlugin.destroy(handle);
} catch {
// Runtime might already be gone
}
}
}
}
// Destroy workspace — skip if worktree is the project path (no isolation was used)
const worktree = raw["worktree"];
const isProjectPath = project && worktree === project.path;
if (worktree && !isProjectPath) {
const workspacePlugin = project
? resolvePlugins(project).workspace
: registry.get<Workspace>("workspace", config.defaults.workspace);
if (workspacePlugin) {
try {
await workspacePlugin.destroy(worktree);
} catch {
// Workspace might already be gone
}
}
}
// Archive metadata
deleteMetadata(sessionsDir, sessionId, true);
}
async function cleanup(
projectId?: string,
options?: { dryRun?: boolean },
): Promise<CleanupResult> {
const result: CleanupResult = { killed: [], skipped: [], errors: [] };
const sessions = await list(projectId);
for (const session of sessions) {
try {
// Never clean up orchestrator sessions — they manage the lifecycle.
// Check explicit role metadata first, fall back to naming convention
// for pre-existing sessions spawned before the role field was added.
if (
session.metadata["role"] === "orchestrator" ||
session.id.endsWith("-orchestrator")
) {
result.skipped.push(session.id);
continue;
}
const project = config.projects[session.projectId];
if (!project) {
result.skipped.push(session.id);
continue;
}
const plugins = resolvePlugins(project);
let shouldKill = false;
// Check if PR is merged
if (session.pr && plugins.scm) {
try {
const prState = await plugins.scm.getPRState(session.pr);
if (prState === PR_STATE.MERGED || prState === PR_STATE.CLOSED) {
shouldKill = true;
}
} catch {
// Can't check PR — skip
}
}
// Check if issue is completed
if (!shouldKill && session.issueId && plugins.tracker) {
try {
const completed = await plugins.tracker.isCompleted(session.issueId, project);
if (completed) shouldKill = true;
} catch {
// Can't check issue — skip
}
}
// Check if runtime is dead — but never kill a session with an open PR.
// A dead runtime with an open PR means the session crashed or failed to
// start; the PR is orphaned and needs human attention, not silent removal.
// (fixes #146)
if (!shouldKill && session.runtimeHandle && plugins.runtime) {
try {
const alive = await plugins.runtime.isAlive(session.runtimeHandle);
if (!alive) {
// Guard: if session has an open PR, skip cleanup
let hasOpenPR = false;
if (session.pr && plugins.scm) {
try {
const prState = await plugins.scm.getPRState(session.pr);
if (prState === PR_STATE.OPEN) hasOpenPR = true;
} catch {
// Can't verify PR state — be conservative, assume open
hasOpenPR = true;
}
}
if (!hasOpenPR) shouldKill = true;
}
} catch {
// Can't check — skip
}
}
if (shouldKill) {
if (!options?.dryRun) {
await kill(session.id);
}
result.killed.push(session.id);
} else {
result.skipped.push(session.id);
}
} catch (err) {
result.errors.push({
sessionId: session.id,
error: err instanceof Error ? err.message : String(err),
});
}
}
return result;
}
async function send(sessionId: SessionId, message: string): Promise<void> {
// Find the session in any project's sessions directory
let raw: Record<string, string> | null = null;
for (const project of Object.values(config.projects)) {
const sessionsDir = getProjectSessionsDir(project);
const metadata = readMetadataRaw(sessionsDir, sessionId);
if (metadata) {
raw = metadata;
break;
}
}
if (!raw) throw new Error(`Session ${sessionId} not found`);
// Build handle: use stored runtimeHandle, or fall back to session ID as tmux session name
let handle: RuntimeHandle;
if (raw["runtimeHandle"]) {
const parsed = safeJsonParse<RuntimeHandle>(raw["runtimeHandle"]);
if (!parsed) {
throw new Error(`Corrupted runtime handle for session ${sessionId}`);
}
handle = parsed;
} else {
// Sessions created by bash scripts don't have runtimeHandle — use session ID as tmux handle
handle = { id: sessionId, runtimeName: config.defaults.runtime, data: {} };
}
// Prefer handle.runtimeName to find the correct plugin
const project = config.projects[raw["project"] ?? ""];
const runtimePlugin = registry.get<Runtime>(
"runtime",
handle.runtimeName ??
(project ? (project.runtime ?? config.defaults.runtime) : config.defaults.runtime),
);
if (!runtimePlugin) {
throw new Error(`No runtime plugin for session ${sessionId}`);
}
await runtimePlugin.sendMessage(handle, message);
}
async function restore(sessionId: SessionId): Promise<Session> {
// 1. Find session metadata across all projects (active first, then archive)
let raw: Record<string, string> | null = null;
let sessionsDir: string | null = null;
let project: ProjectConfig | undefined;
let projectId: string | undefined;
let fromArchive = false;
for (const [key, proj] of Object.entries(config.projects)) {
const dir = getProjectSessionsDir(proj);
const metadata = readMetadataRaw(dir, sessionId);
if (metadata) {
raw = metadata;
sessionsDir = dir;
project = proj;
projectId = key;
break;
}
}
// Fall back to archived metadata (killed/cleaned sessions)
if (!raw) {
for (const [key, proj] of Object.entries(config.projects)) {
const dir = getProjectSessionsDir(proj);