Repository navigation
Expand file tree
/
Copy pathserverRuntimeStartup.ts
More file actions
716 lines (665 loc) · 26.2 KB
/
Copy pathserverRuntimeStartup.ts
File metadata and controls
716 lines (665 loc) · 26.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
import {
CommandId,
DEFAULT_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_SERVER_SETTINGS,
isListedThreadLineage,
type ModelSelection,
type Project,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { formatHostForUrl, isWildcardHost } from "@t3tools/shared/hostClassification";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as ServerConfig from "./config.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import { flushCompileCache } from "./compileCache.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "./project/ProjectService.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerSettings from "./serverSettings.ts";
import { forkParked, forkParkedFiber } from "./serverActivation.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
import { getServerOwners } from "./telemetry/Identify.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { formatHeadlessServeOutput, issueHeadlessServeAccessInfo } from "./startupAccess.ts";
export class ServerRuntimeStartupError extends Schema.TaggedError<ServerRuntimeStartupError>()(
"ServerRuntimeStartupError",
{
mode: ServerConfig.RuntimeMode,
host: Schema.NullOr(Schema.String),
port: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Server runtime startup failed before command readiness.";
}
}
export class ServerRuntimeStartup extends Context.Service<
ServerRuntimeStartup,
{
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
readonly markHttpListening: Effect.Effect<void>;
readonly enqueueCommand: <A, E>(
effect: Effect.Effect<A, E>,
) => Effect.Effect<A, E | ServerRuntimeStartupError>;
}
>()("t3/serverRuntimeStartup") {}
interface QueuedCommand {
readonly run: Effect.Effect<void, never>;
}
type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
interface CommandGate {
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
readonly signalCommandReady: Effect.Effect<void>;
readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
readonly enqueueCommand: <A, E>(
effect: Effect.Effect<A, E>,
) => Effect.Effect<A, E | ServerRuntimeStartupError>;
}
const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
Exit.isSuccess(exit)
? Deferred.succeed(deferred, exit.value)
: Deferred.failCause(deferred, exit.cause);
export const makeCommandGate = Effect.gen(function* () {
const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
const commandQueue = yield* Queue.unbounded<QueuedCommand>();
const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
const commandWorker = Effect.forever(
Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
);
yield* Effect.forkScoped(commandWorker);
const enqueueCommand = Effect.fn("serverRuntimeStartup.enqueueCommand")(function* <A, E>(
effect: Effect.Effect<A, E>,
): Effect.fn.Return<A, E | ServerRuntimeStartupError> {
const readinessState = yield* Ref.get(commandReadinessState);
if (readinessState === "ready") {
return yield* effect;
}
if (readinessState !== "pending") {
return yield* readinessState;
}
const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
yield* Queue.offer(commandQueue, {
run: Deferred.await(commandReady).pipe(
Effect.flatMap(() => effect),
Effect.exit,
Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
),
});
return yield* Deferred.await(result);
});
return {
awaitCommandReady: Deferred.await(commandReady),
signalCommandReady: Effect.gen(function* () {
yield* Ref.set(commandReadinessState, "ready");
yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
}),
failCommandReady: Effect.fn("serverRuntimeStartup.failCommandReady")(function* (error) {
yield* Ref.set(commandReadinessState, error);
yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
}),
enqueueCommand,
} satisfies CommandGate;
});
const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService.AnalyticsService;
const projects = yield* ProjectService.ProjectService;
const threads = yield* ThreadManagement.ThreadManagementService;
const { threadCount, projectCount } = yield* Effect.all({
projects: projects.snapshot,
threadCount: threads.countThreads(),
}).pipe(
Effect.map(({ projects: projectSnapshot, threadCount }) => ({
projectCount: projectSnapshot.projects.length,
threadCount,
})),
Effect.catch((cause) =>
Effect.logWarning("failed to gather V2 startup counts for telemetry", {
cause,
}).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
}),
),
),
);
yield* analytics.record("server.boot.heartbeat", {
threadCount,
projectCount,
});
yield* analytics.recordOwners(yield* getServerOwners, "server");
});
const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({
instanceId: ProviderInstanceId.make("codex"),
model: DEFAULT_MODEL,
});
interface AutoBootstrapWelcomeTargets {
readonly bootstrapProjectId?: ProjectId;
readonly bootstrapThreadId?: ThreadId;
}
export const autoPullProjects = Effect.fn("autoPullProjects")(function* (
projects: ReadonlyArray<Pick<Project, "id" | "workspaceRoot" | "autoPull">>,
settings = DEFAULT_SERVER_SETTINGS,
) {
const git = yield* GitVcsDriver.GitVcsDriver;
const workspaceRoots = [
...new Set(
projects
.filter((project) => resolveProjectSettings(settings, project.id).settings.defaultAutoPull)
.map((project) => project.workspaceRoot),
),
];
yield* Effect.forEach(
workspaceRoots,
(cwd) =>
Effect.gen(function* () {
const status = yield* git.statusDetails(cwd);
if (
!status.isRepo ||
!status.isDefaultBranch ||
!status.hasUpstream ||
status.hasWorkingTreeChanges ||
status.aheadCount > 0
) {
yield* Effect.logDebug("Skipped automatic project pull", {
cwd,
reason: !status.isRepo
? "not-a-repository"
: !status.isDefaultBranch
? "not-on-default-branch"
: !status.hasUpstream
? "no-upstream"
: status.hasWorkingTreeChanges
? "working-tree-changes"
: "local-commits",
});
return;
}
if (status.behindCount <= 0) return;
const result = yield* git.pullCurrentBranch(cwd);
yield* Effect.logDebug("Automatic project pull completed", {
cwd,
status: result.status,
refName: result.refName,
});
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("Automatic project pull failed", {
cwd,
cause,
}),
),
),
{ concurrency: 4, discard: true },
);
});
const resolveWelcomeBase = Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
return {
cwd: serverConfig.cwd,
projectName,
} as const;
});
const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
const random = yield* SecureRandom.SecureRandom;
const randomUUID = random.uuidV4();
const serverConfig = yield* ServerConfig.ServerConfig;
const projects = yield* ProjectService.ProjectService;
const threads = yield* ThreadManagement.ThreadManagementService;
const threadLaunch = yield* ThreadLaunch.ThreadLaunchService;
const path = yield* Path.Path;
let bootstrapProjectId: ProjectId | undefined;
let bootstrapThreadId: ThreadId | undefined;
if (serverConfig.autoBootstrapProjectFromCwd) {
const threadModelSelection = getAutoBootstrapThreadModelSelection();
const { project } = yield* projects.bootstrap({
commandId: CommandId.make(yield* randomUUID),
projectId: ProjectId.make(yield* randomUUID),
title: path.basename(serverConfig.cwd) || "project",
workspaceRoot: serverConfig.cwd,
});
const existingThread = (yield* threads.listActiveShellIndex()).find(
(thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage),
);
if (existingThread === undefined) {
const serverSettings = yield* ServerSettings.ServerSettingsService;
const settings = yield* serverSettings.getSettings;
const launched = yield* threadLaunch
.launch({
commandId: CommandId.make(yield* randomUUID),
projectId: project.id,
title: "New thread",
modelSelection:
resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
threadModelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: resolveProjectSettings(settings, project.id, project).settings
.defaultRuntimeMode,
workspaceStrategy: { type: "root" },
createdBy: "system",
creationSource: "server",
})
.pipe(
// The bootstrap thread is optional; its launch must not prevent opening the app.
Effect.catchTags({
ThreadManagementProviderInstanceDisabledError: (error) =>
Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
projectId: project.id,
instanceId: error.instanceId,
}).pipe(Effect.as(undefined)),
ThreadLaunchError: (error) =>
Effect.logWarning("Failed to launch bootstrap thread", {
projectId: project.id,
operation: error.operation,
}).pipe(Effect.as(undefined)),
}),
);
bootstrapProjectId = project.id;
bootstrapThreadId = launched?.threadId;
} else {
bootstrapProjectId = project.id;
bootstrapThreadId = existingThread.id;
}
}
return {
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
} satisfies AutoBootstrapWelcomeTargets;
});
const resolveStartupBrowserTarget = Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const localUrl = `http://localhost:${serverConfig.port}`;
const bindUrl =
serverConfig.host && !isWildcardHost(serverConfig.host)
? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
: localUrl;
const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
return serverConfig.mode === "desktop"
? baseTarget
: yield* serverAuth.issueStartupPairingUrl(baseTarget);
});
/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */
export const announceStartupPairingUrl = (pairingUrl: string) =>
Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)),
);
// Pairing tokens belong only in announceStartupPairingUrl's stdout output.
export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", {
hint: "Open the pairing URL above in your browser.",
});
export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* (
target: string,
) {
const serverConfig = yield* ServerConfig.ServerConfig;
if (serverConfig.noBrowser) {
return;
}
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
yield* externalLauncher.launchBrowser(target).pipe(
// The target carries the pairing token, and a failed launch records its
// command line on the span, so this call stays out of traces.
Effect.withTracerEnabled(false),
Effect.catch(() => logBrowserAutoOpenUnavailable),
);
});
const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
effect.pipe(
// Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime.
Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }),
);
interface StartupOptions {
readonly activate?: Effect.Effect<void>;
readonly awaitAuxiliaryParked?: Effect.Effect<void>;
readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
}
export const startEffectWorkerWithRelay = Effect.fn(
"ServerRuntimeStartup.startEffectWorkerWithRelay",
)(function* <WorkerContext, RelayContext>(input: {
readonly runWorker: Effect.Effect<void, never, WorkerContext>;
readonly startRelay: Effect.Effect<void, never, RelayContext>;
readonly workerFiberRef: Ref.Ref<Fiber.Fiber<void, never> | null>;
}) {
const workerFiber = yield* forkParkedFiber(input.runWorker);
yield* Ref.set(input.workerFiberRef, workerFiber);
yield* input.startRelay.pipe(
Effect.onExit((exit) => {
if (Exit.isSuccess(exit)) {
return Effect.void;
}
return Ref.getAndSet(input.workerFiberRef, null).pipe(
Effect.flatMap((ownedWorkerFiber) =>
ownedWorkerFiber === null
? Effect.void
: Fiber.interrupt(ownedWorkerFiber).pipe(Effect.asVoid),
),
);
}),
);
});
const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")(
function* <
Import,
Recovery,
Bootstrap,
ImportError,
RecoveryError,
DelegationError,
WorkerError,
BootstrapError,
ImportContext,
RecoveryContext,
DelegationContext,
WorkerContext,
BootstrapContext,
>(input: {
readonly importLegacyShells: Effect.Effect<Import, ImportError, ImportContext>;
readonly recover: Effect.Effect<Recovery, RecoveryError, RecoveryContext>;
readonly recoverDelegatedTasks: Effect.Effect<void, DelegationError, DelegationContext>;
readonly startEffectWorker: Effect.Effect<void, WorkerError, WorkerContext>;
readonly autoBootstrap: Effect.Effect<Bootstrap, BootstrapError, BootstrapContext>;
}) {
yield* input.importLegacyShells;
const recovery = yield* input.recover;
yield* input.recoverDelegatedTasks;
yield* input.startEffectWorker;
const bootstrap = yield* input.autoBootstrap;
return { recovery, bootstrap } as const;
},
);
const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) {
const serverConfig = yield* ServerConfig.ServerConfig;
const keybindings = yield* Keybindings.Keybindings;
const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
const orchestrator = yield* Orchestrator.OrchestratorV2;
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const random = yield* SecureRandom.SecureRandom;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
const commandGate = yield* makeCommandGate;
const httpListening = yield* Deferred.make<void>();
const effectWorkerFiber = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
yield* commandGate.failCommandReady(
new ServerRuntimeStartupError({
mode: serverConfig.mode,
host: serverConfig.host ?? null,
port: serverConfig.port,
cause: "Server runtime is shutting down.",
}),
);
const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null);
if (workerFiber !== null) {
yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore);
}
yield* providerRuntimeRecovery.prepareForShutdown.pipe(
Effect.ensuring(providerSessions.shutdown),
);
const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown");
yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation);
}).pipe(
Effect.withSpan("server.shutdown"),
Effect.catchCause((cause) =>
Effect.logWarning("V2 orchestration shutdown reconciliation failed", {
cause: Cause.pretty(cause),
}),
),
),
);
const startup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: starting keybindings runtime");
yield* runStartupPhase(
"keybindings.start",
keybindings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start keybindings runtime", {
path: error.configPath,
detail: error.detail,
cause: error.cause,
}),
),
),
);
yield* Effect.logDebug("startup phase: starting server settings runtime");
yield* runStartupPhase(
"settings.start",
serverSettings.start.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to start server settings runtime", {
path: error.settingsPath,
operation: error.operation,
providerInstanceId: error.providerInstanceId,
environmentVariable: error.environmentVariable,
cause: error.cause,
}),
),
),
);
const welcomeBase = yield* resolveWelcomeBase;
const environment = yield* serverEnvironment.getDescriptor;
const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount;
if (legacyMigrationThreadCount > 0) {
yield* lifecycleEvents.publish({
version: 1,
type: "legacyThreadMigration",
payload: {
status: "running",
totalThreadCount: legacyMigrationThreadCount,
},
});
}
const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({
importLegacyShells: runStartupPhase(
"orchestration-v2.legacy-v1.import-shells",
legacyV1ThreadImporter.reconcileShells.pipe(
Effect.tap((summary) =>
summary.importedThreadCount === 0
? Effect.void
: Effect.logInfo("Imported legacy v1 thread shells", summary),
),
),
),
recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
recoverDelegatedTasks: runStartupPhase(
"orchestration-v2.delegated-tasks.recover",
orchestrator.recoverDelegatedTasks,
),
startEffectWorker: runStartupPhase(
"orchestration-v2.effect-worker.start",
startEffectWorkerWithRelay({
runWorker: EffectWorker.runDaemon,
startRelay: agentAwarenessRelay.start(),
workerFiberRef: effectWorkerFiber,
}),
),
autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
? runStartupPhase(
"welcome.autobootstrap",
resolveAutoBootstrapWelcomeTargets.pipe(
Effect.provideService(SecureRandom.SecureRandom, random),
),
)
: Effect.succeed({})
).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)),
});
yield* Effect.logInfo("V2 orchestration recovery completed", recovery);
// Runs after activation: the status check fetches every enabled project's
// remote, and awaiting it here held command readiness for that long.
yield* runStartupPhase(
"projects.auto-pull",
Effect.gen(function* () {
const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells();
const settings = yield* serverSettings.getSettings;
yield* autoPullProjects(projects, settings);
}),
).pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to load projects for automatic pull", { cause }),
),
forkParked,
);
const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe(
Effect.tap((summary) =>
summary.importedThreadCount === 0
? Effect.void
: Effect.logInfo("Hydrated legacy v1 thread transcripts", summary),
),
);
yield* (
legacyMigrationThreadCount > 0
? importPendingTranscripts.pipe(
Effect.tap(() =>
lifecycleEvents.publish({
version: 1,
type: "legacyThreadMigration",
payload: {
status: "complete",
totalThreadCount: legacyMigrationThreadCount,
},
}),
),
)
: importPendingTranscripts
).pipe(forkParked);
yield* forkParked(
Effect.gen(function* () {
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* recordStartupHeartbeat.pipe(
Effect.withSpan("server.startup.heartbeat.record", {
attributes: { "startup.phase": "heartbeat.record" },
}),
Effect.ignoreCause({ log: true }),
);
if (serverConfig.startupPresentation === "headless") {
yield* Effect.logDebug("startup phase: headless access info");
const accessInfo = yield* issueHeadlessServeAccessInfo();
yield* runStartupPhase(
"headless.output",
Console.log(formatHeadlessServeOutput(accessInfo)),
);
} else {
yield* Effect.logDebug("startup phase: browser open check");
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
yield* announceStartupPairingUrl(startupBrowserTarget);
}
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
}
}),
);
yield* Effect.logDebug("startup phase: waiting for http listener");
yield* runStartupPhase("http.wait", Deferred.await(httpListening));
yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void);
const updateOutcome = yield* launcher.prepareTrial;
yield* Effect.logDebug("startup phase: publishing welcome event", {
environmentId: environment.environmentId,
cwd: welcomeBase.cwd,
projectName: welcomeBase.projectName,
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
});
yield* runStartupPhase(
"welcome.publish",
lifecycleEvents.publish({
version: 1,
type: "welcome",
payload: {
environment,
...welcomeBase,
...bootstrapTargets,
},
}),
);
yield* options?.activate ?? Effect.void;
yield* Effect.logDebug("Accepting commands");
yield* commandGate.signalCommandReady;
yield* Effect.logDebug("startup phase: publishing ready event");
yield* runStartupPhase(
"ready.publish",
lifecycleEvents.publish({
version: 1,
type: "ready",
payload: {
at: DateTime.formatIso(yield* DateTime.now),
environment,
...(updateOutcome === undefined ? {} : { updateOutcome }),
},
}),
);
yield* Effect.logDebug("startup phase: complete");
yield* flushCompileCache;
}).pipe(
Effect.withSpan("server.startup", {
kind: "server",
root: true,
attributes: {
"server.mode": serverConfig.mode,
"server.port": serverConfig.port,
"server.host": serverConfig.host ?? "default",
},
}),
);
yield* Effect.forkScoped(
Effect.exit(startup).pipe(
Effect.flatMap((startupExit) => {
if (Exit.isSuccess(startupExit)) return Effect.void;
const error = new ServerRuntimeStartupError({
mode: serverConfig.mode,
host: serverConfig.host ?? null,
port: serverConfig.port,
cause: startupExit.cause,
});
return Effect.logError("server runtime startup failed", {
cause: Cause.pretty(startupExit.cause),
}).pipe(
Effect.andThen(commandGate.failCommandReady(error)),
Effect.andThen(options?.abort?.(error) ?? Effect.void),
);
}),
),
);
return {
awaitCommandReady: commandGate.awaitCommandReady,
markHttpListening: Deferred.succeed(httpListening, undefined),
enqueueCommand: commandGate.enqueueCommand,
} satisfies ServerRuntimeStartup["Service"];
});
export const layerWithOptions = (options?: StartupOptions) =>
Layer.effect(ServerRuntimeStartup, make(options));