-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsession-manager.ts
More file actions
5011 lines (4787 loc) · 198 KB
/
Copy pathsession-manager.ts
File metadata and controls
5011 lines (4787 loc) · 198 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
/**
* SessionManager — orchestrates multiple concurrent agent sessions.
*
* Production-grade patterns:
* - Per-user rate limiting on session creation
* - Session resume from transcript on daemon restart
* - Scope enforcement on every operation
* - Graceful drain on shutdown
*/
import { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve, sep } from "node:path";
import { Session, type AttachedClient } from "./session.js";
import type { SessionProvider } from "./providers/interface.js";
import {
createDefaultProviderRegistry,
type ProviderRegistry,
} from "./providers/registry.js";
import type { HookBus } from "./hooks/bus.js";
import type { Store } from "./store.js";
import { createPushTransport, PushService } from "./push/index.js";
import { hasScope, SCOPES } from "../protocol/scopes.js";
import { applyPatches, getManifest, getSnapshot } from "./settings/store.js";
import { RateLimiter } from "./rate-limit.js";
import type { TranscriptMeta, TranscriptStore } from "./transcript.js";
import {
FsAccessError,
handleFsBrowseDir,
handleFsList,
handleFsRead,
isProtectedPath,
} from "./fs.js";
import { readClaudeConfig } from "./claude-config.js";
import {
CLAUDE_PROVIDER_ID,
fallbackModelInfos,
resolveAgainstList,
resolveModelIdForProvider,
} from "./models.js";
import { Blackboard, type OwnerBlackboard } from "./blackboard/service.js";
import { BlackboardStore, type GoalScope } from "./blackboard/store.js";
import { BlackboardMcpHttp } from "./blackboard/mcp-http.js";
import {
adoptPackRoles,
childBrief,
childSessionName,
compileGoalPack,
orchestratorRole,
goalIdFromCreatedBy,
orchestratorCreatedBy,
orphanedChildBrief,
planChildren,
plannedChildFor,
roleChildPosture,
validateCollaboration,
type PlannedChild,
} from "./collaboration.js";
import {
packSession,
unpackBundle,
validateBundle,
writeBundleToFile,
type ImportedSessionInit,
} from "./share/index.js";
import type { AgentIdentityManager } from "./agent-identity.js";
import {
buildFleetMcpServer,
ORCHESTRATOR_FLEET_TOOLS,
type FleetDeps,
type FleetDispatchDeps,
type FleetSessionView,
type FleetTaskView,
} from "./fleet.js";
import {
Dispatcher,
NonRetryableDispatchError,
TERMINAL_TASK_STATUS,
type DispatcherHost,
} from "./dispatch.js";
import { createPipelineManagerFromConfig } from "./pipeline/wiring.js";
import type { PipelineManager } from "./pipeline/manager.js";
import { resolveBinding, type ModelBindingConfig } from "./pipeline/binding.js";
import type { RoleDef } from "./pipeline/pack.js";
import {
PackService,
resolvePhaseActivation,
type PackActivation,
type PackServiceConfig,
} from "./pipeline/pack-service.js";
import { SessionPhaseRunner, type PhaseTurnResult } from "./pipeline/runner.js";
import {
isNeedInput,
isPhaseComplete,
MAX_PHASE_NUDGES,
MAX_SPURIOUS_RESTS,
PHASE_COMPLETION_CONTRACT,
PHASE_CONTINUE_NUDGE,
PHASE_NO_INPUT_NUDGE,
stripNeedInputMarker,
stripPhaseCompleteMarker,
} from "./pipeline/phase-completion.js";
import { roleEnforcement } from "./providers/tool-safety.js";
import type { DispatchEventRow, DispatchTaskRow } from "./store.js";
import { type MemoryEngine, type MemoryMcpMount, workspaceIdFromPath } from "./memory/index.js";
import type { McpRegistry } from "./mcp/registry.js";
import type { McpHub } from "./mcp/hub.js";
import { type CodeoidConfig, mutateConfigFile } from "../config.js";
import type { CompressionRegistry } from "./compress/index.js";
import { ORCHESTRATOR_ROLE } from "../protocol/types.js";
import type {
AuthContext,
ClientMessage,
CollaborationConfig,
CollaborationCost,
CollaborationPanel,
CollaborationRole,
DaemonMessage,
McpServerStatus,
ModelInfo,
PipelinePhaseWire,
PipelineWire,
SessionInfo,
SessionMode,
SessionWorktree,
} from "../protocol/types.js";
import type { Scope } from "../protocol/scopes.js";
import type { PipelineState } from "./pipeline/interface.js";
/** Per-phase autonomous turn budget for a pipeline run. A phase runs the model
* to completion within its role (the human gate is the phase boundary, not each
* tool), so this is a generous safety cap, refreshed at the start of every
* phase. There is no wall-clock timeout: the run session is attended, so the
* user watches + can interrupt — nothing hangs headless. */
const PIPELINE_PHASE_MAX_TURNS = 200;
import { randomUUID } from "node:crypto";
import {
createForkWorktree,
currentBranch,
isGitRepo,
removeForkWorktree,
} from "./git-worktree.js";
import type { DailyUsageBucket, LifetimeUsageTotals } from "./memory/store.js";
/**
* Optional safe-root for session workdirs. When `CODEOID_FS_BROWSE_ROOT` is set
* (the same knob `fs.browse_dir` uses), a session's workdir must resolve inside
* it — so a scoped token can't create a session rooted anywhere on the host.
* Unset = no root constraint (workdirs are still barred from protected dirs).
*/
function workdirSafeRoot(): string | null {
const override = process.env.CODEOID_FS_BROWSE_ROOT;
if (!override || override.trim().length === 0) return null;
try {
return realpathSync(override.trim());
} catch {
return resolve(override.trim());
}
}
/**
* Resolve a user-supplied workdir to an absolute, existing directory.
* Expands a leading `~`, resolves relative paths against the daemon cwd, and
* returns null if the path doesn't exist, isn't a directory, lands inside a
* protected directory (the daemon's own secret store / host credential dirs),
* or escapes the configured safe-root.
*
* The containment check is the session-creation half of GHSA-38vh vector 2:
* `fs.read` is already bounded to the session workdir, so refusing a workdir
* that IS (or is an ancestor of) the daemon config dir stops a scoped token
* from rooting a session at `~` and reading `~/.codeoid/config.json` — the root
* ZeroID key. `fs.resolveSafe` enforces the same deny-list as defence in depth.
*/
function normalizeWorkdir(input: string): string | null {
const raw = (input ?? "").trim();
if (!raw) return null;
let p: string;
if (raw === "~") p = homedir();
else if (raw.startsWith("~/")) p = resolve(homedir(), raw.slice(2));
else p = resolve(raw);
try {
if (!existsSync(p) || !statSync(p).isDirectory()) return null;
// Canonicalise so a symlinked workdir can't smuggle the resolved path
// into a protected dir or outside the safe-root.
const canonical = realpathSync(p);
if (isProtectedPath(canonical)) return null;
const root = workdirSafeRoot();
if (root && canonical !== root && !canonical.startsWith(root + sep)) {
return null;
}
return canonical;
} catch {
return null;
}
}
/** Eager-resume bounds. Resume runs before the daemon listens — so an
* unbounded resume can block startup or OOM. Cap to the newest-N sessions and
* stop past a deadline (applied WITHIN each transcript parse too, not just
* between sessions); the rest stay on disk (loadable on a future restart). */
/**
* Recent fan-outs a client is shown per goal. A sidebar needs the live one plus
* a little history for context, not an orchestrator's whole dispatch career.
*/
const PANEL_HISTORY_LIMIT = 5;
const RESUME_MAX_SESSIONS = 50;
const RESUME_DEADLINE_MS = 20_000;
/** Per-session transcript read budget on resume. Scrollback keeps at most
* 20 MiB / 5000 messages — parsing history past that would be evicted on
* arrival, so cap the read slightly above the scrollback byte cap. */
const RESUME_TRANSCRIPT_MAX_BYTES = 24 * 1024 * 1024;
/** Provider assumed when a client doesn't say which catalog it wants.
* Re-exported from models.ts so the id that gates Claude-only alias
* expansion (`resolveModelIdForProvider`) and the id used for catalog
* defaults can never drift apart. */
export const DEFAULT_PROVIDER_ID = CLAUDE_PROVIDER_ID;
/** Sort key for resume ordering: most-recently-active first. Falls back to
* createdAt, then 0, so a malformed timestamp never throws. */
function resumeSortKey(m: { lastActivityAt?: string; createdAt?: string }): number {
const t = m.lastActivityAt ?? m.createdAt ?? "";
const n = Date.parse(t);
return Number.isFinite(n) ? n : 0;
}
export class SessionManager {
#sessions = new Map<string, Session>();
#store: Store;
#transcriptStore: TranscriptStore;
#identityManager?: AgentIdentityManager;
#rateLimiter: RateLimiter;
#memory?: MemoryEngine;
#memoryMcp?: MemoryMcpMount;
/** Goal-blackboard MCP endpoint + the loopback URL children mount it from.
* Always constructed: with no minted tokens every request fails closed. */
readonly #blackboardMcp = new BlackboardMcpHttp();
#blackboardUrl?: string;
/** Per-goal artifact store, lazily built on the shared DB connection. */
#blackboard?: Blackboard;
/** child session id → its blackboard bearer token, revoked on teardown. */
readonly #blackboardTokens = new Map<string, string>();
#mcpRegistry?: McpRegistry;
#mcpHub?: McpHub;
/** Live model catalogs by provider id (via each backend's supportedModels
* equivalent), cached daemon-wide once any session of that provider
* initializes. Empty until then. */
#modelsCache = new Map<string, ModelInfo[]>();
#config?: CodeoidConfig;
#compressionRegistry?: CompressionRegistry;
#dispatcher: Dispatcher;
/** Content-blind push notifications — resolves a blocked session's owner to
* their registered devices. Noop transport when push is disabled (default). */
#pushService: PushService;
/** SDLC pipeline manager — undefined when the pipeline is disabled (default). */
#pipelines?: PipelineManager;
/** Pack curation surface (registries + install/trust/select) — always present,
* so packs can be managed even before the pipeline runtime is enabled. */
#packs: PackService;
/** The daemon's provider catalog — one registry, shared by every session. */
#providers: ProviderRegistry;
/** The daemon's hook bus — one instance, shared by every session. */
#hooks?: HookBus;
#testProviderFactory?: () => SessionProvider;
/** Bound run-sessions awaiting a phase turn to rest, keyed by session id. A
* pipeline run drives phases on a live session; the phase resolves when that
* session next reaches a resting status (see #statusObserver). */
#phaseWaiters = new Map<string, (status: PhaseTurnResult["finalStatus"]) => void>();
/** Stable observer identity — every Session reports status transitions here. */
#statusObserver = (sessionId: string, status: SessionInfo["status"]): void => {
this.#dispatcher.onSessionStatus(sessionId, status);
// Content-blind push: a session that just blocked on approval alerts its
// owner's registered devices off-LAN. Fire-and-forget — a push hiccup must
// never touch the status path (the emit itself only ever sees an opaque
// session id, never the tool's args/description).
if (status === "waiting_approval" && this.#pushService.enabled) {
const session = this.#sessions.get(sessionId);
if (session) {
void this.#pushService
.notifyApproval(sessionId, {
sub: session.createdBy,
accountId: session.accountId,
projectId: session.projectId,
})
.catch((err) => console.error("[codeoid/push] notify failed:", err));
}
}
// A pipeline phase driving this session awaits its next rest; resolve it.
// (Non-run sessions never have a waiter, so this is a no-op for them.)
//
// `waiting_approval` is deliberately NOT a rest: the SDK turn is still ALIVE
// (session.ts) — the model called a tool that needs a decision. Ending the
// phase there would guillotine it mid-work (the bug this used to cause).
// A tool approval is a tool-level interaction; the phase resumes once the
// tool is approved and the turn goes on to actually rest (idle).
if (status === "idle" || status === "error") {
const waiter = this.#phaseWaiters.get(sessionId);
if (waiter) {
this.#phaseWaiters.delete(sessionId);
waiter(status);
}
}
};
constructor(
store: Store,
transcriptStore: TranscriptStore,
identityManager?: AgentIdentityManager,
rateLimiter?: RateLimiter,
memory?: MemoryEngine,
opts?: {
config?: CodeoidConfig;
compressionRegistry?: CompressionRegistry;
/**
* Provider registry override (tests / embedders adding backends).
* Absent = the built-in catalog (claude, gemini, openai).
*/
providers?: ProviderRegistry;
/**
* The daemon's hook bus (built once at startup from config.hooks).
* Absent = no hooks; sessions pay zero overhead.
*/
hooks?: HookBus;
/**
* Test-only: provider factory injected into every Session this manager
* constructs, so manager-level integration tests (conductor injection,
* worker spawn, dispatch host) run without the Claude Agent SDK
* subprocess. Mirrors SessionCreateOptions._testProvider.
*/
_testProviderFactory?: () => SessionProvider;
},
) {
this.#store = store;
this.#transcriptStore = transcriptStore;
this.#identityManager = identityManager;
this.#rateLimiter = rateLimiter ?? new RateLimiter();
this.#memory = memory;
this.#config = opts?.config;
this.#compressionRegistry = opts?.compressionRegistry;
this.#providers = opts?.providers ?? createDefaultProviderRegistry(opts?.config);
this.#hooks = opts?.hooks;
this.#testProviderFactory = opts?._testProviderFactory;
this.#dispatcher = new Dispatcher(
store,
this.#makeDispatcherHost(),
opts?.config?.dispatch,
);
this.#pushService = new PushService(
store,
createPushTransport(opts?.config?.push, (token) => store.pruneDeadToken(token)),
);
// SDLC pipeline (docs/sdlc-pipeline.md) — off by default; when enabled, the
// manager shares the daemon DB (one connection) and rehydrates non-terminal
// pipelines on construction (resume). The runner drives prompt/slash phases
// on worker turns; the `() => this` thunk is only dereferenced at run time,
// after construction. Undefined when disabled ⇒ the daemon stays dark.
this.#pipelines = createPipelineManagerFromConfig(opts?.config, {
runner: new SessionPhaseRunner(() => this),
db: store.database,
});
// Pack curation surface (docs/pack-loading.md) — always constructed (cheap:
// no DB / runner). Reads the boot pack config; each mutation persists to
// config.json AND (if the pipeline is enabled) registers into the manager.
const p = opts?.config?.pipeline;
this.#packs = new PackService({
config: {
defaultPack: p?.defaultPack ?? null,
packs: p?.packs ?? [],
registries: p?.registries ?? [],
},
manager: () => this.#pipelines,
persist: (state) => this.#persistPackConfig(state),
// The operator's model maps, for the pre-flight `pack show --resolve`
// view (docs/role-model-binding.md §4) — same maps pipeline.create reads.
modelConfig: { modelTiers: p?.modelTiers, modelRoles: p?.modelRoles },
});
}
/** Persist the pack state (registries + installed packs + selection) back into
* config.json under `pipeline`, preserving any other pipeline fields. */
#persistPackConfig(state: PackServiceConfig): void {
mutateConfigFile((raw) => {
const existing = raw.pipeline;
const pipeline: Record<string, unknown> =
existing && typeof existing === "object" && !Array.isArray(existing)
? (existing as Record<string, unknown>)
: {};
pipeline.packs = state.packs;
pipeline.registries = state.registries;
pipeline.defaultPack = state.defaultPack;
raw.pipeline = pipeline;
});
}
/** The dispatch queue driver (P4). Exposed for server lifecycle + tests. */
get dispatcher(): Dispatcher {
return this.#dispatcher;
}
/** The SDLC pipeline manager, or undefined when the pipeline is disabled
* (the default). Exposed for the pipeline control surface + tests. */
get pipelines(): PipelineManager | undefined {
return this.#pipelines;
}
/** The pack curation service (registries + install/trust/select). Exposed for
* the CLI + tests. */
get packs(): PackService {
return this.#packs;
}
/** The operator's model maps (docs/role-model-binding.md §2.2) — the same
* `pipeline.modelTiers`/`modelRoles` slice pipeline.create resolves with,
* read here for the collab-adoption and single-session (§6.2) chains. */
#modelBindingConfig(): ModelBindingConfig | undefined {
const p = this.#config?.pipeline;
if (!p) return undefined;
return { modelTiers: p.modelTiers, modelRoles: p.modelRoles };
}
/**
* How many sessions this subject currently has alive.
*
* The authoritative source for the concurrent-session limit. Derived from the
* live map on every check rather than tracked in a counter, because a counter
* got both of its edges wrong: resumed sessions never re-registered (so a
* restart reset the allowance) and three of the four session-removal paths
* never decremented (so it drifted upward until restart). Reading the map
* cannot do either. O(sessions) on a session-create — negligible next to
* spawning an agent, and skipped entirely when limits are off (the default).
*/
#liveSessionCountFor(sub: string): number {
if (this.#rateLimiter.disabled) return 0;
let n = 0;
for (const session of this.#sessions.values()) {
if (session.createdBy === sub) n++;
}
return n;
}
/**
* Registered provider ids, default first — advertised on `auth.ok` so
* clients can populate the new-session provider picker.
*/
providerIds(): string[] {
const ids = this.#providers.ids();
const def = this.#providers.defaultId;
return [def, ...ids.filter((id) => id !== def)];
}
/** Supported backends that couldn't activate at startup (diagnostics). */
unavailableProviders(): Array<{ id: string; hint: string }> {
return this.#providers.unavailableEntries();
}
/** Start the dispatcher loop. Call AFTER resumeSessions so surviving
* workers are back in #sessions before the boot-time reclaim pass runs. */
startDispatcher(): void {
this.#dispatcher.start();
}
stopDispatcher(): void {
this.#dispatcher.stop();
}
/** Re-drive SDLC pipelines interrupted mid-run at a restart (no-op when the
* pipeline is disabled). Fire-and-forget: a failure is logged, not thrown.
* Call after resumeSessions on boot. */
startPipelines(): void {
const pm = this.#pipelines;
if (!pm) return;
void pm.driveResumable().catch((err) => {
console.error("[pipeline] driveResumable failed on boot:", err);
});
}
/**
* Resume sessions from persisted transcripts (called on daemon restart).
* Rebuilds in-memory session objects and scrollback buffers.
*/
async resumeSessions(): Promise<number> {
// Reload the durable conductor identity first (design R2): the persisted
// {identityId, wimseUri, apiKey} row is reused instead of re-registering,
// so the conductor keeps ONE stable WIMSE URI across daemon restarts.
// Best-effort and null-safe — a missing or stale row just means the next
// registerConductor() starts fresh.
const conductor = await this.#identityManager?.resumeConductor();
if (conductor) {
console.log(
`[codeoid] resumed conductor identity ${conductor.wimseUri}`,
);
}
const allMetas = await this.#transcriptStore.loadAllMeta();
// Newest-first by last activity so the cap keeps the most relevant
// sessions when there are more than RESUME_MAX_SESSIONS on disk.
const sorted = [...allMetas].sort(
(a, b) => resumeSortKey(b) - resumeSortKey(a),
);
const capped = sorted.slice(0, RESUME_MAX_SESSIONS);
// Goal config by orchestrator session id, built from EVERY meta on disk
// rather than from `capped`. A child inside this boot's resume window whose
// orchestrator fell outside it still needs its restrictions and its brief,
// and the blackboard is keyed on (tenant, goal id) in SQLite — so the
// child's mount works whether or not the orchestrator object is resident.
const goalConfigs = new Map<string, CollaborationConfig>();
for (const m of allMetas) {
if (m.collaboration) goalConfigs.set(m.sessionId, m.collaboration);
}
const deadline = Date.now() + RESUME_DEADLINE_MS;
let resumed = 0;
let skippedDeadline = 0;
let resumedChildren = 0;
let orphanedChildren = 0;
for (let i = 0; i < capped.length; i++) {
// Time-box: a few huge transcripts shouldn't wedge startup. Stop and
// leave the remainder on disk rather than blocking the daemon listen.
if (Date.now() > deadline) {
skippedDeadline = capped.length - i;
break;
}
const meta = capped[i]!;
try {
// Role-children need their restrictions rebuilt BEFORE construction —
// worker shape and capability role are constructor inputs, not things
// that can be attached afterwards.
const child = this.#resumeRoleChild(meta, goalConfigs);
if (child) {
if (child.orphaned) orphanedChildren++;
else resumedChildren++;
}
const session = new Session({
name: meta.sessionName,
// Heal a workdir persisted with a literal `~` or one that has since
// moved — expand/validate it so the SDK can launch. Falls back to
// the raw value if it can't be resolved (surfaces a clear error on
// first send rather than crashing resume).
workdir: normalizeWorkdir(meta.workdir) ?? meta.workdir,
auth: {
sub: meta.createdBy,
scopes: [],
delegationDepth: 0,
accountId: meta.accountId,
projectId: meta.projectId,
},
store: this.#store,
transcriptStore: this.#transcriptStore,
providers: this.#providers,
hooks: this.#hooks,
identityManager: this.#identityManager,
existingId: meta.sessionId,
memory: this.#memory,
memoryMcp: this.#memoryMcp,
mcpRegistry: this.#mcpRegistry,
mcpHub: this.#mcpHub,
config: this.#config,
compressionRegistry: this.#compressionRegistry,
// The conductor self-persists (design R2): its role, provider
// selection, and fleet tools all come back across a restart.
role: meta.role,
providerId: meta.providerId,
forkedFrom: meta.forkedFrom,
worktree: meta.worktree,
// A collaboration is durable state, not turn state: the goal and
// its role→backend bindings must come back after a restart or the
// orchestrator resumes with no idea what it was coordinating.
collaboration: meta.collaboration,
// ...and the same is true of a CHILD's restrictions. Spread after
// `role` so the worker role from the posture wins over `meta.role`
// (they agree — both are "worker" — but the posture is the authority).
...(child?.options ?? {}),
// Conductor: the config override. Role-child: the roster's resolved
// model from the posture options — an unconditional `undefined` here
// would clobber the spread above and resume a bound child on the
// provider default (the regression the resume tests pin).
defaultModel:
meta.role === "conductor"
? this.#config?.conductor?.model
: child?.options.defaultModel,
// Conductor gets the tenant-wide surface; a collaboration
// orchestrator gets the role-aware one scoped to its own children.
// Its id is already known here, so the thunk is trivial.
fleet:
meta.role === "conductor"
? this.#buildFleetServer(meta.accountId, meta.projectId)
: meta.collaboration
? this.#buildOrchestratorFleetServer(
() => meta.sessionId,
meta.accountId,
meta.projectId,
)
: undefined,
collaborationCost: meta.collaboration
? () => this.#collaborationCostRollup(meta.sessionId)
: undefined,
_testProvider: this.#testProviderFactory?.(),
onStatusChange: this.#statusObserver,
onModels: (providerId, m) => this._cacheModels(providerId, m),
});
// Restore scrollback from transcript, seeding the seq counter past
// the persisted tail so new appends continue the monotonic sequence.
// Byte-budgeted + deadline-aware: one huge transcript can neither
// OOM the daemon nor eat the whole resume window by itself.
const loadStats: { truncated?: boolean } = {};
const entries = await this.#transcriptStore.loadTranscript(meta.sessionId, {
maxBytes: RESUME_TRANSCRIPT_MAX_BYTES,
deadlineAt: deadline,
stats: loadStats,
});
const messages = entries.map((e) => e.message);
const maxSeq = entries.reduce((max, e) => Math.max(max, e.seq), -1);
session.restoreScrollback(messages, maxSeq + 1, entries.map((e) => e.bytes), {
partialHistory: loadStats.truncated === true,
});
this.#sessions.set(session.id, session);
// Track a resumed child's mount so teardown revokes it. Without this a
// restart leaks one still-valid blackboard credential per child on
// every boot, and destroying the goal would not revoke them.
if (child?.options.blackboardMcp) {
this.#blackboardTokens.set(session.id, child.options.blackboardMcp.token);
}
// An orchestrator's own mount is scoped to its own id, so it can only
// be attached now — exactly as on the create path.
if (meta.collaboration) {
this.#attachOrchestratorBlackboard(session, meta.collaboration);
}
// Resume is NOT a creation — don't burn a slot in the
// per-user concurrency cap. Otherwise restarting with N
// persisted sessions saturates the limit on the spot and the
// next legitimate `session.create` fails with
// "Concurrent session limit reached" until the user
// /destroys some.
resumed++;
} catch {
// Skip sessions that fail to resume
}
}
const droppedCap = sorted.length - capped.length;
if (droppedCap > 0 || skippedDeadline > 0) {
console.warn(
`[codeoid] resume: restored ${resumed} of ${sorted.length} session(s); ${droppedCap} left over the ${RESUME_MAX_SESSIONS}-session cap, ${skippedDeadline} skipped past the ${RESUME_DEADLINE_MS}ms deadline (still on disk; loadable on a future restart).`,
);
}
if (resumedChildren > 0) {
console.log(
`[codeoid] resume: ${resumedChildren} collaboration role-child(ren) restored with their role scoping + goal blackboard`,
);
}
// Loud, because it is the one path where a role-child comes back WITHOUT
// its goal: its restrictions hold, but it cannot coordinate, and a silent
// degrade would look identical to a healthy fleet in the session list.
if (orphanedChildren > 0) {
console.warn(
`[codeoid] resume: ${orphanedChildren} role-child(ren) had no recoverable goal config — restored read-only-as-configured, with no blackboard mount and no autonomous budget`,
);
}
return resumed;
}
/**
* Rebuild a role-child's restrictions from disk, or `undefined` when this
* meta isn't a role-child at all.
*
* Why this exists: `collaborationRole` was persisted from the first day of
* P1b, and resume read `meta.collaboration` while silently ignoring it. The
* visible symptom was cosmetic (children detached from their parent in the
* session list). The real one was not — a resumed child came back with:
*
* - no `workerShape`, so its next turn registered a FULL session agent
* instead of a scope-capped `scout` leaf (`#ensureAgentIdentity`);
* - no capability role, so `roleDeniesTool` had nothing to deny with and a
* read-only reviewer's write tools degraded from denied to merely asked;
* - no blackboard mount, so it could not publish a handoff; and
* - no autonomous budget, so it came back `guarded` — which, with nobody
* ever attached to a child, parks it at `waiting_approval` forever on its
* first non-safe tool call. The fleet looked alive and was dead.
*
* Nothing about a child needs a new persisted field: its identity
* (`collaborationRole`) plus its goal's config reproduces the plan it spawned
* under, via `plannedChildFor`.
*/
#resumeRoleChild(
meta: TranscriptMeta,
goalConfigs: ReadonlyMap<string, CollaborationConfig>,
):
| {
orphaned: boolean;
options: {
role: "worker";
workerShape: "ship" | "scout";
pack: ReturnType<typeof roleChildPosture>["pack"];
collaborationRole: ReturnType<typeof roleChildPosture>["collaborationRole"];
initialMode?: { mode: SessionMode; maxTurns?: number };
blackboardMcp?: { url: string; token: string };
/** The roster's resolved model for this child (docs/role-model-binding.md
* §6.1) — without it a bound child resumes on the provider default
* while SessionInfo still claims the resolved model. */
defaultModel?: string;
};
}
| undefined {
const role = meta.collaborationRole;
if (!role) return undefined;
const collaboration = goalConfigs.get(role.parentSessionId);
const planned = collaboration
? plannedChildFor(collaboration, role.roleName, role.ordinal)
: undefined;
if (!collaboration || !planned) {
// Torn state: the child's transcript survived while its orchestrator's
// did not (teardown removes both). Restore the FENCE from what the child
// itself carries — `write` is on `collaborationRole` — and nothing else.
// Deliberately no autonomous budget: an agent that cannot coordinate
// should not be able to burn turns unattended.
return {
orphaned: true,
options: roleChildPosture(
{
roleName: role.roleName,
ordinal: role.ordinal,
providerId: meta.providerId ?? "claude",
shape: role.write ? "ship" : "scout",
write: role.write,
},
role.parentSessionId,
orphanedChildBrief(role.roleName, role.write),
),
};
}
return {
orphaned: false,
options: {
...roleChildPosture(planned, role.parentSessionId, childBrief(collaboration, planned)),
// The roster's resolved model comes back with the child — same source
// (`plannedChildFor`) as the spawn path, so they can't drift.
...(planned.model !== undefined ? { defaultModel: planned.model } : {}),
// Re-armed per boot, not persisted: the budget is a per-stretch-of-work
// allowance, and carrying a spent one across a restart would resume a
// child with zero turns left.
initialMode: {
mode: "autonomous",
maxTurns: this.#dispatcher.config.workerToolBudget,
},
// Scoped to the child's OWN tenant plus its goal id. Same authorSub the
// pre-restart versions carry, so its history stays one contributor.
...(() => {
const mount = this.#blackboardMountFor(
{
accountId: meta.accountId,
projectId: meta.projectId,
goalSessionId: role.parentSessionId,
},
planned,
collaboration.roles.find((r) => r.name === role.roleName),
);
return mount ? { blackboardMcp: mount } : {};
})(),
},
};
}
/**
* Resolve a session by id, gated on tenancy. Returns null when:
*
* - the id doesn't exist, OR
* - the requester's `(accountId, projectId)` doesn't match the
* session's owner.
*
* Both cases collapse to the same "not found" response at the
* caller, so we don't leak session-id existence across tenants —
* an account-A user trying to attach to an account-B sessionId
* gets the same shape they'd get for a typo. Sessions whose
* owner has empty tenancy (e.g. a malformed resume) only match
* an auth context with empty tenancy, which doesn't happen in
* normal flows; those sessions remain only visible to system /
* resume paths.
*/
#getOwnedSession(sessionId: string, auth: AuthContext): Session | null {
const session = this.#sessions.get(sessionId);
if (!session) return null;
if (
session.accountId !== auth.accountId ||
session.projectId !== auth.projectId
) {
return null;
}
return session;
}
/**
* Handle an inbound client message, enforce scopes, and return a response.
*/
async handle(
msg: ClientMessage,
auth: AuthContext,
client: AttachedClient,
opts?: {
/**
* The caller's raw bearer token, retained by the transport for flows
* that need the owner as an RFC 8693 delegation SUBJECT — today only
* conductor creation (owner → conductor token exchange). Never logged,
* never persisted.
*/
rawToken?: string;
},
): Promise<DaemonMessage> {
switch (msg.type) {
case "ping":
// Liveness heartbeat — lets a client detect a half-open/zombie
// socket (suspended webview, slept laptop) that never fired a close
// event, by noticing the pong never arrives.
return { type: "response.ok", requestId: msg.id, data: { pong: true } };
case "session.create":
if (msg.role === "conductor") {
return this.#createConductor(msg, auth, opts?.rawToken);
}
if (msg.role) {
// A role this daemon doesn't implement (newer client / future
// worker role). Fail closed rather than silently downgrading to a
// normal session — a caller asking for a constrained role must not
// get an unconstrained one.
return {
type: "response.error",
requestId: msg.id,
error: `Unsupported session role: "${msg.role}"`,
code: "invalid_request",
};
}
return this.#create(msg, auth);
case "session.list":
return this.#list(msg, auth);
case "session.attach":
return this.#attach(msg, auth, client);
case "scrollback.page":
return this.#pageScrollback(msg, auth);
case "session.detach":
return this.#detach(msg, client);
case "session.send":
return this.#send(msg, auth);
case "session.interrupt":
return this.#interrupt(msg, auth);
case "session.approve":
return this.#approve(msg, auth);
case "session.ui_response":
return this.#uiResponse(msg, auth);
case "session.part_action":
return this.#partAction(msg, auth);
case "session.commands":
return this.#sessionCommands(msg, auth);
case "session.destroy":
return this.#destroySession(msg, auth);
case "session.set_mode":
return this.#setMode(msg, auth);
case "session.pin":
return this.#pin(msg, auth);
case "session.unpin":
return this.#unpin(msg, auth);
case "session.rotate":
return this.#rotate(msg, auth);
case "session.search":
return this.#search(msg, auth);
case "session.set_model":
return this.#setModel(msg, auth);
case "session.set_provider":
return this.#setProvider(msg, auth);
case "session.fork":
return this.#fork(msg, auth);
case "session.rename":
return this.#rename(msg, auth);
case "fs.list":
return this.#fsList(msg, auth);
case "fs.read":
return this.#fsRead(msg, auth);
case "fs.browse_dir":
return this.#fsBrowseDir(msg, auth);
case "claude.config":
return this.#claudeConfig(msg, auth);
case "blackboard.index":
return this.#blackboardIndex(msg, auth);
case "blackboard.read":
return this.#blackboardRead(msg, auth);
case "collaboration.panels":
return this.#collaborationPanels(msg, auth);
case "models.list":
return this.#modelsList(msg);
case "session.export":
return this.#sessionExport(msg, auth);
case "session.import":
return this.#sessionImport(msg, auth);
case "settings.schema":
return this.#settingsSchema(msg, auth);
case "settings.get":
return this.#settingsGet(msg, auth);
case "settings.set":
return this.#settingsSet(msg, auth);
case "usage.daily":
return this.#usageDaily(msg, auth);
case "pipeline.create":
return this.#pipelineCreate(msg, auth);
case "pipeline.list":
return this.#pipelineList(msg, auth);
case "pipeline.get":
return this.#pipelineGet(msg, auth);
case "pipeline.advance":
return this.#pipelineAdvance(msg, auth);
case "pipeline.answer":
return this.#pipelineAnswer(msg, auth);
case "pipeline.abort":
return this.#pipelineAbort(msg, auth);
case "pipeline.revise":
return this.#pipelineRevise(msg, auth);
case "pipeline.pack.list":
return this.#packList(msg, auth);
case "pipeline.registry.add":
return this.#registryAdd(msg, auth);
case "pipeline.registry.refresh":
return this.#registryRefresh(msg, auth);
case "pipeline.pack.install":
return this.#packInstall(msg, auth);
case "pipeline.pack.remove":
return this.#packRemove(msg, auth);
case "pipeline.pack.trust":
return this.#packTrust(msg, auth);
case "pipeline.pack.select":
return this.#packSelect(msg, auth);
case "push.register":
return this.#pushRegister(msg, auth);
case "push.unregister":
return this.#pushUnregister(msg, auth);
default: {
// Inbound messages are cast from raw JSON at the transport, so an
// unknown/malformed `type` reaches here. Without this the function
// returned undefined → the daemon sent nothing → the client's request
// never resolved until its 30s timeout. Resolve it explicitly.
const m = msg as { id?: unknown; type?: unknown };
return {
type: "response.error",
requestId: typeof m.id === "string" ? m.id : "",
error: `Unknown message type: ${typeof m.type === "string" ? m.type : "(none)"}`,
code: "invalid_request",
};
}
}
}
async #sessionExport(
msg: Extract<ClientMessage, { type: "session.export" }>,
auth: AuthContext,
): Promise<DaemonMessage> {
if (!hasScope(auth.scopes as string[], SCOPES.SESSION_LIST)) {
return {
type: "response.error",
requestId: msg.id,
error: "Missing scope: session:list",
code: "forbidden",
};
}
const session = this.#getOwnedSession(msg.sessionId, auth);
if (!session) {
return {
type: "response.error",
requestId: msg.id,
error: "Session not found",
code: "not_found",
};
}
try {
const info = session.toInfo();
const bundle = await packSession(
{
session: {
id: info.id,
name: info.name,
workdir: info.workdir,
createdAt: info.createdAt,
...(info.model ? { model: info.model } : {}),
...(info.fallbackModel ? { fallbackModel: info.fallbackModel } : {}),
...(info.mode ? { mode: info.mode } : {}),
...(info.rotation ? { rotation: { count: info.rotation.count } } : {}),
...(info.pinnedFiles ? { pinnedFiles: info.pinnedFiles } : {}),
},
exporter: auth,
includeMemory: msg.includeMemory ?? true,
includePinnedFiles: msg.includePinnedFiles ?? false,
...(msg.aliasOverride ? { aliasOverride: msg.aliasOverride } : {}),
},
{
transcript: this.#transcriptStore,
store: this.#store,
memory: this.#memory ?? null,
// Bind the exporter's tenant so the derived workspace id matches the
// tenant-scoped ids episodes were written under.