Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 type ServerLifecycleStreamReadyEvent,
7 type ServerSelfUpdateProgressEvent,
8 type ServerSelfUpdateResult,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Duration from "effect/Duration";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Equal from "effect/Equal";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24import * as SubscriptionRef from "effect/SubscriptionRef";
25import { AsyncResult, Atom } from "effect/reactivity";
26
27import {
28 createAtomCommandScheduler,
29 createEnvironmentRpcCommand,
30 createEnvironmentQueryAtomFamily,
31 createEnvironmentRpcQueryAtomFamily,
32 createEnvironmentRpcSubscriptionAtomFamily,
33 createEnvironmentSubscriptionAtomFamily,
34 createRuntimeCommand,
35 scheduleAtomCommandEffect,
36} from "./runtime.ts";
37import * as EnvironmentRegistry from "../connection/registry.ts";
38import * as EnvironmentSupervisor from "../connection/supervisor.ts";
39import { safeErrorLogAttributes } from "../errors/safeLog.ts";
40import * as Persistence from "../platform/persistence.ts";
41import { runCachePersistence } from "./cachePersistence.ts";
42import {
43 isRpcClientError,
44 request,
45 runStream,
46 subscribe,
47 subscribeDynamicWithSession,
48 type EnvironmentRpcInput,
49} from "../rpc/client.ts";
50import type { RpcSession } from "../rpc/session.ts";
51import { followStreamInEnvironment } from "./runtime.ts";
52import {
53 applyServerConfigProjection,
54 type ServerConfigProjection,
55 withoutEnvironmentThemes,
56} from "./serverConfigProjection.ts";
57
58export type { ServerConfigProjection } from "./serverConfigProjection.ts";
59
60export type ServerUpdateStage = "downloading" | "installing" | "resuming";
61
62export type ServerUpdateState =
63 | { readonly status: "idle" }
64 | {
65 readonly status: "running";
66 readonly stage: ServerUpdateStage;
67 readonly fromVersion: string;
68 readonly targetVersion: string;
69 }
70 | {
71 readonly status: "failed";
72 readonly stage: ServerUpdateStage;
73 readonly fromVersion: string;
74 readonly targetVersion: string;
75 readonly message: string;
76 };
77
78export interface ServerUpdateTarget {
79 readonly environmentId: EnvironmentId;
80 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
81}
82
83const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
84const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
85 Atom.withLabel("environment-data:server:update-state:empty"),
86);
87export const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
88 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
89 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
90 ),
91);
92
93export class ServerUpdateResumeTimeoutError extends Schema.TaggedError<ServerUpdateResumeTimeoutError>()(
94 "ServerUpdateResumeTimeoutError",
95 {
96 environmentId: Schema.String,
97 targetVersion: Schema.String,
98 },
99) {
100 override get message(): string {
101 return `The server did not resume on t3@${this.targetVersion}.`;
102 }
103}
104
105export class ServerUpdateProgressIncompleteError extends Schema.TaggedError<ServerUpdateProgressIncompleteError>()(
106 "ServerUpdateProgressIncompleteError",
107 {
108 targetVersion: Schema.String,
109 },
110) {
111 override get message(): string {
112 return `The t3@${this.targetVersion} update ended before the server accepted the restart.`;
113 }
114}
115
116export class ServerUpdateTerminalError extends Schema.TaggedError<ServerUpdateTerminalError>()(
117 "ServerUpdateTerminalError",
118 {
119 targetVersion: Schema.String,
120 status: Schema.Literals(["committed", "rolled-back", "failed"]),
121 reason: Schema.optional(Schema.String),
122 },
123) {
124 override get message(): string {
125 return this.reason ?? `The t3@${this.targetVersion} update ${this.status}.`;
126 }
127}
128
129// Covers the service launcher's 30-minute trial deadline (PREPARED_TIMEOUT_MS)
130// and a final restart of the previous version when the trial rolls back.
131const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(32);
132
133export function matchesServerUpdateReadyEvent(
134 result: ServerSelfUpdateResult,
135 event: ServerLifecycleStreamReadyEvent,
136): boolean {
137 return result.updateId === undefined
138 ? event.payload.environment.serverVersion === result.targetVersion
139 : event.payload.updateOutcome?.id === result.updateId;
140}
141
142export function matchesServerUpdateResumeEvent(
143 result: ServerSelfUpdateResult,
144 event: ServerLifecycleStreamReadyEvent,
145): boolean {
146 return (
147 (result.method === "desktop-app" && result.desktopUpdateToken !== undefined) ||
148 matchesServerUpdateReadyEvent(result, event)
149 );
150}
151
152export function validateServerUpdateReadyEvent(
153 result: ServerSelfUpdateResult,
154 event: ServerLifecycleStreamReadyEvent,
155): Effect.Effect<void, ServerUpdateTerminalError> {
156 if (result.updateId === undefined) return Effect.void;
157 const outcome = event.payload.updateOutcome;
158 if (
159 outcome?.id === result.updateId &&
160 outcome.status === "committed" &&
161 outcome.targetVersion === result.targetVersion &&
162 event.payload.environment.serverVersion === result.targetVersion
163 ) {
164 return Effect.void;
165 }
166 return Effect.fail(
167 new ServerUpdateTerminalError({
168 targetVersion: result.targetVersion,
169 status: outcome?.status ?? "failed",
170 reason:
171 outcome?.reason ??
172 "The service launcher resumed without committing the requested server version.",
173 }),
174 );
175}
176
177/**
178 * The sleep before each nudge is the pacer: a connection that fails instantly
179 * re-enters backoff immediately and would otherwise spin a tight retry loop.
180 *
181 * Callers fork this as a child of the update command so it is interrupted as
182 * soon as the update settles, whether it succeeds, fails, or times out.
183 */
184export function nudgeReconnectDuringUpdateRestart(input: {
185 readonly stateChanges: Stream.Stream<
186 {
187 readonly phase: string;
188 readonly lastFailure?: { readonly reason: string } | null;
189 },
190 unknown
191 >;
192 readonly retryNow: Effect.Effect<void>;
193 readonly interval?: Duration.Duration;
194}): Effect.Effect<void> {
195 return input.stateChanges.pipe(
196 Stream.filter(
197 (state) =>
198 state.phase === "backoff" ||
199 (state.phase === "blocked" && state.lastFailure?.reason === "authentication"),
200 ),
201 Stream.runForEach(() =>
202 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
203 ),
204 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
205 Effect.ignore,
206 );
207}
208
209export function waitForNextEnvironmentReconnect<E>(
210 stateChanges: Stream.Stream<{ readonly phase: string }, E>,
211): Effect.Effect<void, E> {
212 return stateChanges.pipe(
213 Stream.dropWhile((state) => state.phase === "connected"),
214 Stream.filter((state) => state.phase === "connected"),
215 Stream.runHead,
216 Effect.asVoid,
217 );
218}
219
220export const runDesktopCommitWithReconnectObserver = Effect.fn(
221 "runDesktopCommitWithReconnectObserver",
222)(function* <EState, ECommit>(
223 stateChanges: Stream.Stream<{ readonly phase: string }, EState>,
224 commit: Effect.Effect<void, ECommit>,
225) {
226 const armed = yield* Deferred.make<void>();
227 const reconnected = yield* Deferred.make<void>();
228 const observer = yield* stateChanges.pipe(
229 Stream.tap(() => Deferred.succeed(armed, undefined)),
230 waitForNextEnvironmentReconnect,
231 Effect.andThen(Deferred.succeed(reconnected, undefined)),
232 Effect.forkChild,
233 );
234 yield* Deferred.await(armed);
235 const commitExit = yield* commit.pipe(Effect.exit);
236 if (Exit.isSuccess(commitExit)) {
237 yield* Fiber.interrupt(observer);
238 return;
239 }
240 if (!isLegacyUpdateHandoffLoss(commitExit.cause)) {
241 yield* Fiber.interrupt(observer);
242 return yield* Effect.failCause(commitExit.cause);
243 }
244 yield* Deferred.await(reconnected).pipe(Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT));
245 return yield* Effect.failCause(commitExit.cause);
246});
247
248export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget")(function* <
249 EReady,
250 ECommit,
251>(
252 targetVersion: string,
253 nextReady: Effect.Effect<ServerLifecycleStreamReadyEvent, EReady>,
254 retryCommit: Effect.Effect<void, ECommit>,
255 maxCommitAttempts = 3,
256): Effect.fn.Return<ServerLifecycleStreamReadyEvent, EReady | ECommit | ServerUpdateTerminalError> {
257 for (let attempt = 1; attempt <= maxCommitAttempts; attempt += 1) {
258 const ready = yield* nextReady;
259 if (ready.payload.environment.serverVersion === targetVersion) return ready;
260 if (attempt === maxCommitAttempts) break;
261 const retryExit = yield* retryCommit.pipe(Effect.exit);
262 if (Exit.isSuccess(retryExit)) break;
263 if (!isLegacyUpdateHandoffLoss(retryExit.cause)) {
264 return yield* Effect.failCause(retryExit.cause);
265 }
266 }
267 return yield* new ServerUpdateTerminalError({
268 targetVersion,
269 status: "failed",
270 reason: "The desktop app resumed without installing the prepared update.",
271 });
272});
273
274export function serverUpdateStateForProgressEvent(
275 fromVersion: string,
276 targetVersion: string,
277 event: ServerSelfUpdateProgressEvent,
278): Extract<ServerUpdateState, { status: "running" }> {
279 return {
280 status: "running",
281 stage:
282 event.type !== "complete"
283 ? event.stage
284 : event.result.method === "desktop-app" && event.result.desktopUpdateToken !== undefined
285 ? "installing"
286 : "resuming",
287 fromVersion,
288 targetVersion,
289 };
290}
291
292export function serverUpdateStateForServerVersion(
293 state: ServerUpdateState,
294 serverVersion: string | null,
295): ServerUpdateState {
296 return state.status === "idle" ||
297 state.status === "running" ||
298 serverVersion === null ||
299 state.fromVersion === serverVersion
300 ? state
301 : IDLE_SERVER_UPDATE_STATE;
302}
303
304export function serverUpdateFailureMessage(error: unknown): string {
305 return error instanceof Error ? error.message : "Server update failed.";
306}
307
308function isRpcSocketError(error: unknown): boolean {
309 if (!isRpcClientError(error)) {
310 return false;
311 }
312 switch (error.reason._tag) {
313 case "SocketReadError":
314 case "SocketWriteError":
315 case "SocketCloseError":
316 return true;
317 default:
318 return false;
319 }
320}
321
322export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
323 if (Cause.hasInterruptsOnly(cause)) {
324 return true;
325 }
326 return (
327 cause.reasons.length > 0 &&
328 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
329 );
330}
331
332export function resolveServerUpdateProgressResult<E>(
333 targetVersion: string,
334 terminal: Option.Option<ServerSelfUpdateResult>,
335 streamExit: Exit.Exit<void, E>,
336): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
337 if (
338 Option.isSome(terminal) &&
339 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
340 ) {
341 return Effect.succeed(terminal.value);
342 }
343 if (Exit.isFailure(streamExit)) {
344 return Effect.failCause(streamExit.cause);
345 }
346 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
347}
348
349const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
350 version: 1,
351 type: "snapshot",
352 config,
353});
354
355export interface ServerConfigSubscriptionOptions {
356 readonly environmentThemes?: boolean;
357 readonly usageLimitSources?: boolean;
358 readonly usageLimitsCommand?: boolean;
359}
360
361export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
362 function* (subscription: ServerConfigSubscriptionOptions) {
363 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
364 const cache = yield* Persistence.EnvironmentCacheStore;
365 const environmentId = supervisor.target.environmentId;
366 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
367 Effect.catch((error) =>
368 Effect.logWarning("Could not load cached server configuration.").pipe(
369 Effect.annotateLogs({
370 environmentId,
371 ...safeErrorLogAttributes(error),
372 }),
373 Effect.as(Option.none<ServerConfig>()),
374 ),
375 ),
376 );
377 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
378 Option.map(cachedConfig, (cached) => ({
379 config: withoutEnvironmentThemes(cached),
380 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
381 source: "cache" as const,
382 })),
383 );
384 const persistence = yield* Queue.sliding<ServerConfig>(1);
385 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
386
387 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
388 config: ServerConfig,
389 ) {
390 return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
391 Effect.as(true),
392 Effect.catch((error) =>
393 Effect.logWarning("Could not persist cached server configuration.").pipe(
394 Effect.annotateLogs({
395 environmentId,
396 ...safeErrorLogAttributes(error),
397 }),
398 Effect.as(false),
399 ),
400 ),
401 );
402 });
403
404 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
405 config: ServerConfig,
406 ) {
407 if (!(yield* persist(config))) {
408 return;
409 }
410 yield* Ref.update(pendingPersistence, (pending) =>
411 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
412 );
413 });
414
415 yield* Effect.addFinalizer(() =>
416 Ref.get(pendingPersistence).pipe(
417 Effect.flatMap(
418 Option.match({
419 onNone: () => Effect.void,
420 onSome: (config) => persist(config).pipe(Effect.asVoid),
421 }),
422 ),
423 ),
424 );
425
426 yield* runCachePersistence(persistence, persistPending).pipe(Effect.forkScoped);
427
428 yield* subscribe(WS_METHODS.subscribeServerConfig, {
429 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
430 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
431 ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
432 }).pipe(
433 Stream.runForEach((event) =>
434 Effect.gen(function* () {
435 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
436 if (Option.isNone(next)) {
437 return;
438 }
439 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
440 yield* SubscriptionRef.set(state, next);
441 yield* Queue.offer(persistence, next.value.config);
442 }),
443 ),
444 Effect.forkScoped,
445 );
446
447 return state;
448 },
449);
450
451function serverConfigStateChanges(
452 environmentId: EnvironmentId,
453 subscription: ServerConfigSubscriptionOptions,
454) {
455 return followStreamInEnvironment(
456 environmentId,
457 Stream.unwrap(
458 makeEnvironmentServerConfigState(subscription).pipe(
459 Effect.map((state) =>
460 SubscriptionRef.changes(state).pipe(
461 Stream.filterMap((projection) =>
462 Option.match(projection, {
463 onNone: () => Result.failVoid,
464 onSome: (value) => Result.succeed(value),
465 }),
466 ),
467 ),
468 ),
469 ),
470 ),
471 );
472}
473
474export function applyServerWelcomeEvent(
475 current: EnvironmentServerWelcomeState,
476 session: RpcSession,
477 event: {
478 readonly type: "welcome" | "ready" | "legacyThreadMigration";
479 readonly payload: unknown;
480 },
481): EnvironmentServerWelcomeState {
482 return event.type === "welcome" && current.currentSession === session
483 ? {
484 ...current,
485 welcomeSession: session,
486 welcome: event.payload as ServerLifecycleWelcomePayload,
487 }
488 : current;
489}
490
491export interface EnvironmentServerWelcomeState {
492 readonly currentSession: RpcSession | null;
493 readonly welcomeSession: RpcSession | null;
494 readonly welcome: ServerLifecycleWelcomePayload | null;
495}
496
497export function resolveServerWelcomeState(
498 state: EnvironmentServerWelcomeState,
499): ServerLifecycleWelcomePayload | null {
500 return state.currentSession === state.welcomeSession ? state.welcome : null;
501}
502
503export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")(
504 function* () {
505 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
506 const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session));
507 const state = yield* SubscriptionRef.make<EnvironmentServerWelcomeState>({
508 currentSession: initialSession,
509 welcomeSession: null,
510 welcome: null,
511 });
512
513 const updateWithCurrentSession = Effect.fn(
514 "EnvironmentServerWelcomeState.updateWithCurrentSession",
515 )(function* (
516 update: (
517 current: EnvironmentServerWelcomeState,
518 currentSession: RpcSession | null,
519 ) => EnvironmentServerWelcomeState,
520 ) {
521 return yield* SubscriptionRef.modifyEffect(state, (current) =>
522 SubscriptionRef.get(supervisor.session).pipe(
523 Effect.map(
524 (latestSession) =>
525 [undefined, update(current, Option.getOrNull(latestSession))] as const,
526 ),
527 ),
528 );
529 });
530
531 yield* SubscriptionRef.changes(supervisor.session).pipe(
532 Stream.runForEach(() =>
533 updateWithCurrentSession((current, currentSession) => ({
534 ...current,
535 currentSession,
536 })),
537 ),
538 Effect.forkScoped,
539 );
540
541 yield* subscribeDynamicWithSession(
542 WS_METHODS.subscribeServerLifecycle,
543 Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) {
544 yield* updateWithCurrentSession((current, currentSession) =>
545 currentSession === session
546 ? {
547 ...current,
548 currentSession,
549 welcomeSession: session,
550 welcome: null,
551 }
552 : { ...current, currentSession },
553 );
554 return {};
555 }),
556 ).pipe(
557 Stream.runForEach(([session, event]) =>
558 updateWithCurrentSession((current, currentSession) =>
559 applyServerWelcomeEvent(
560 {
561 ...current,
562 currentSession,
563 },
564 session,
565 event,
566 ),
567 ),
568 ),
569 Effect.forkScoped,
570 );
571
572 return state;
573 },
574);
575
576function serverWelcomeStateChanges(environmentId: EnvironmentId) {
577 return followStreamInEnvironment(
578 environmentId,
579 Stream.unwrap(
580 makeEnvironmentServerWelcomeState().pipe(
581 Effect.map((state) =>
582 SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)),
583 ),
584 ),
585 ),
586 );
587}
588
589// Avoid repeated config walks from hashing/schema equivalence during boot.
590function sameConfigValue(left: unknown, right: unknown): boolean {
591 if (Object.is(left, right)) return true;
592 if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) {
593 return false;
594 }
595 if (Array.isArray(left)) {
596 if (!Array.isArray(right) || left.length !== right.length) return false;
597 for (let index = 0; index < left.length; index++) {
598 if (!sameConfigValue(left[index], right[index])) return false;
599 }
600 return true;
601 }
602 if (
603 Object.getPrototypeOf(left) !== Object.prototype ||
604 Object.getPrototypeOf(right) !== Object.prototype
605 ) {
606 return Equal.equals(left, right);
607 }
608 const leftRecord = left as Record<string, unknown>;
609 const rightRecord = right as Record<string, unknown>;
610 const keys = Object.keys(leftRecord);
611 if (keys.length !== Object.keys(rightRecord).length) return false;
612 for (const key of keys) {
613 if (!Object.hasOwn(rightRecord, key) || !sameConfigValue(leftRecord[key], rightRecord[key])) {
614 return false;
615 }
616 }
617 return true;
618}
619
620export function resolveServerConfigValue(
621 projection: ServerConfigProjection | null,
622 initialConfig: ServerConfig | null,
623): ServerConfig | null {
624 if (
625 projection?.source === "live" &&
626 (initialConfig === null ||
627 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
628 ) {
629 return projection.config;
630 }
631 return initialConfig ?? projection?.config ?? null;
632}
633
634export function createServerEnvironmentAtoms<R, E>(
635 runtime: Atom.AtomRuntime<
636 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
637 E
638 >,
639 options: {
640 readonly initialConfigValueAtom: (
641 environmentId: EnvironmentId,
642 ) => Atom.Atom<ServerConfig | null>;
643 readonly environmentThemes?: boolean;
644 readonly usageLimitSources?: boolean;
645 readonly usageLimitsCommand?: boolean;
646 },
647) {
648 const configScheduler = createAtomCommandScheduler();
649 const updateScheduler = createAtomCommandScheduler();
650 const configConcurrency = {
651 mode: "serial" as const,
652 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
653 };
654 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
655 runtime
656 .atom(
657 serverConfigStateChanges(environmentId, {
658 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
659 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
660 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
661 }),
662 )
663 .pipe(
664 Atom.setIdleTTL(5 * 60_000),
665 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
666 ),
667 );
668 const configProjection = (target: {
669 readonly environmentId: EnvironmentId;
670 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
671 }) => configProjectionFamily(target.environmentId);
672 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
673 Atom.withLabel("environment-data:server:config:empty"),
674 );
675 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
676 if (environmentId === null) {
677 return emptyConfigAtom;
678 }
679 return Atom.make((get): ServerConfig | null => {
680 const projection = Option.getOrNull(
681 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
682 );
683 return resolveServerConfigValue(
684 projection,
685 get(options.initialConfigValueAtom(environmentId)),
686 );
687 }).pipe(
688 // Cache/session/live handoffs must not rerender readers of an equal config.
689 Atom.withEquality(sameConfigValue),
690 Atom.withLabel(`environment-data:server:config:${environmentId}`),
691 );
692 });
693 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
694 Atom.make((get) =>
695 serverUpdateStateForServerVersion(
696 get(serverUpdateStateAtom(environmentId)),
697 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
698 ),
699 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
700 );
701 const updateStateAtom = (environmentId: EnvironmentId | null) =>
702 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
703 const updateServer = createRuntimeCommand<
704 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
705 E,
706 ServerUpdateTarget,
707 ServerSelfUpdateResult,
708 unknown
709 >(runtime, {
710 label: "environment-data:server:update-server",
711 scheduler: updateScheduler,
712 concurrency: configConcurrency,
713 execute: (target, atomRegistry) => {
714 const stateAtom = serverUpdateStateAtom(target.environmentId);
715 let targetVersion = target.input.targetVersion;
716 let fromVersion =
717 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
718 targetVersion;
719 let currentStage: ServerUpdateStage = "downloading";
720 let desktopCommitLostTransport = false;
721 atomRegistry.set(stateAtom, {
722 status: "running",
723 stage: currentStage,
724 fromVersion,
725 targetVersion,
726 });
727
728 return Effect.gen(function* () {
729 const environmentRegistry = yield* EnvironmentRegistry.EnvironmentRegistry;
730 const desktopCommitStarting = yield* Deferred.make<void>();
731 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
732 const desktopReconnected = yield* Deferred.make<void>();
733 yield* Deferred.await(desktopCommitStarting).pipe(
734 Effect.andThen(
735 environmentRegistry.stateChanges(target.environmentId).pipe(
736 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
737 Stream.dropWhile((state) => state.phase === "connected"),
738 Stream.filter((state) => state.phase === "connected"),
739 Stream.runHead,
740 ),
741 ),
742 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
743 Effect.forkChild,
744 );
745 const result = yield* scheduleAtomCommandEffect(
746 atomRegistry,
747 configScheduler,
748 configConcurrency,
749 target,
750 Effect.gen(function* () {
751 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
752 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
753 atomRegistry.set(stateAtom, {
754 status: "running",
755 stage: currentStage,
756 fromVersion,
757 targetVersion,
758 });
759
760 const supportsProgress =
761 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
762 const updateResult: ServerSelfUpdateResult = supportsProgress
763 ? yield* Effect.gen(function* () {
764 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
765 Option.none(),
766 );
767 const streamExit = yield* environmentRegistry
768 .runStream(
769 target.environmentId,
770 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
771 )
772 .pipe(
773 Stream.runForEach((event) =>
774 Effect.sync(() => {
775 const state = serverUpdateStateForProgressEvent(
776 fromVersion,
777 targetVersion,
778 event,
779 );
780 currentStage = state.stage;
781 atomRegistry.set(stateAtom, state);
782 }).pipe(
783 Effect.andThen(
784 event.type === "complete"
785 ? Ref.set(terminal, Option.some(event.result))
786 : Effect.void,
787 ),
788 ),
789 ),
790 Effect.exit,
791 );
792 return yield* resolveServerUpdateProgressResult(
793 targetVersion,
794 yield* Ref.get(terminal),
795 streamExit,
796 );
797 })
798 : yield* Effect.gen(function* () {
799 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
800 const exit = yield* environmentRegistry
801 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
802 .pipe(Effect.exit);
803 if (Exit.isSuccess(exit)) {
804 return exit.value;
805 }
806 if (
807 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
808 isLegacyUpdateHandoffLoss(exit.cause)
809 ) {
810 // Older servers can tear down the transport before their
811 // unary acknowledgement arrives. Treat only that transport
812 // loss as a handoff, then prove it by waiting for target ready.
813 return { targetVersion, method: selfUpdateMethod };
814 }
815 return yield* Effect.failCause(exit.cause);
816 });
817
818 if (
819 updateResult.method === "desktop-app" &&
820 updateResult.desktopUpdateToken !== undefined
821 ) {
822 yield* Deferred.succeed(desktopCommitStarting, undefined);
823 yield* Deferred.await(desktopReconnectObserverArmed);
824 const commitExit = yield* environmentRegistry
825 .run(
826 target.environmentId,
827 request(WS_METHODS.serverCommitDesktopUpdate, {
828 requestId: updateResult.desktopUpdateToken,
829 }),
830 )
831 .pipe(Effect.exit);
832 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
833 return yield* Effect.failCause(commitExit.cause);
834 }
835 desktopCommitLostTransport = Exit.isFailure(commitExit);
836 }
837
838 targetVersion = updateResult.targetVersion;
839
840 currentStage = "resuming";
841 atomRegistry.set(stateAtom, {
842 status: "running",
843 stage: currentStage,
844 fromVersion,
845 targetVersion,
846 });
847 return updateResult;
848 }),
849 );
850
851 yield* nudgeReconnectDuringUpdateRestart({
852 stateChanges: environmentRegistry.stateChanges(target.environmentId),
853 retryNow: environmentRegistry.retryNow(target.environmentId),
854 }).pipe(Effect.forkChild);
855
856 if (result.method === "desktop-app" && desktopCommitLostTransport) {
857 yield* Deferred.await(desktopReconnected).pipe(
858 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
859 );
860 }
861
862 const waitForReady = environmentRegistry
863 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
864 .pipe(
865 Stream.filter(
866 (event): event is ServerLifecycleStreamReadyEvent =>
867 event.type === "ready" && matchesServerUpdateResumeEvent(result, event),
868 ),
869 Stream.runHead,
870 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
871 Effect.map(Option.flatten),
872 );
873 const nextReady = waitForReady.pipe(
874 Effect.flatMap(
875 Option.match({
876 onNone: () =>
877 new ServerUpdateResumeTimeoutError({
878 environmentId: target.environmentId,
879 targetVersion,
880 }),
881 onSome: Effect.succeed,
882 }),
883 ),
884 );
885 const desktopUpdateToken = result.desktopUpdateToken;
886 const resumed =
887 result.method === "desktop-app" && desktopUpdateToken !== undefined
888 ? yield* waitForDesktopUpdateTarget(
889 result.targetVersion,
890 nextReady,
891 runDesktopCommitWithReconnectObserver(
892 environmentRegistry.stateChanges(target.environmentId),
893 environmentRegistry
894 .run(
895 target.environmentId,
896 request(WS_METHODS.serverCommitDesktopUpdate, {
897 requestId: desktopUpdateToken,
898 }),
899 )
900 .pipe(Effect.asVoid),
901 ),
902 )
903 : yield* nextReady;
904 yield* validateServerUpdateReadyEvent(result, resumed);
905
906 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
907 return result;
908 }).pipe(
909 Effect.onExit((exit) =>
910 Effect.sync(() => {
911 if (Exit.isSuccess(exit)) {
912 return;
913 }
914 if (Cause.hasInterruptsOnly(exit.cause)) {
915 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
916 return;
917 }
918 atomRegistry.set(stateAtom, {
919 status: "failed",
920 stage: currentStage,
921 fromVersion,
922 targetVersion,
923 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
924 });
925 }),
926 ),
927 );
928 },
929 });
930 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
931 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
932 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
933 ),
934 );
935 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
936 Atom.make((get) => {
937 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
938 // Only changed prices should trigger another transcript scan. Settings
939 // snapshots can recreate the same mapping in a different property order.
940 return JSON.stringify(
941 Object.keys(overrides)
942 .sort()
943 .map((model) => {
944 const price = overrides[model]!;
945 return [
946 model,
947 price.inputCostPerMillionTokens,
948 price.outputCostPerMillionTokens,
949 price.cacheReadCostPerMillionTokens,
950 price.cacheWriteCostPerMillionTokens,
951 ];
952 }),
953 );
954 }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
955 );
956 const usageScanSettingsAtom = Atom.family((environmentId: EnvironmentId) =>
957 Atom.make((get) => {
958 const settings = get(settingsValueAtom(environmentId));
959 const aliases = settings?.usageModelAliases ?? {};
960 return JSON.stringify([
961 get(usagePricesAtom(environmentId)),
962 Object.keys(aliases)
963 .sort()
964 .map((model) => [model, aliases[model]]),
965 settings?.cursorKeychainUsageEnabled ?? false,
966 ]);
967 }).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
968 );
969 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
970 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
971 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
972 ),
973 );
974 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
975 runtime
976 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
977 .pipe(
978 Atom.setIdleTTL(5 * 60_000),
979 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
980 ),
981 );
982 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
983 Atom.make((get) => {
984 const result = get(welcomeStateFamily(environmentId));
985 if (result._tag !== "Success") return result;
986 return result.value === null
987 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
988 : AsyncResult.success(result.value, result);
989 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
990 );
991 const welcome = (target: {
992 readonly environmentId: EnvironmentId;
993 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
994 }) => welcomeFamily(target.environmentId);
995 const updateSettings = createEnvironmentRpcCommand(runtime, {
996 label: "environment-data:server:update-settings",
997 tag: WS_METHODS.serverUpdateSettings,
998 scheduler: configScheduler,
999 concurrency: configConcurrency,
1000 });
1001
1002 return {
1003 configValueAtom,
1004 runStorageCleanup: createEnvironmentRpcCommand(runtime, {
1005 label: "environment-data:server:run-storage-cleanup",
1006 tag: WS_METHODS.serverRunStorageCleanup,
1007 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1008 }),
1009 databaseStorage: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1010 label: "environment-data:server:database-storage",
1011 tag: WS_METHODS.serverGetDatabaseStorage,
1012 idleTtlMs: 0,
1013 }),
1014 storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1015 label: "environment-data:server:storage-cleanup-report",
1016 tag: WS_METHODS.serverGetStorageCleanupReport,
1017 idleTtlMs: 0,
1018 }),
1019 updateStateAtom,
1020 settingsValueAtom,
1021 providersValueAtom,
1022 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1023 label: "environment-data:provider:auth-state",
1024 tag: WS_METHODS.providerAuthSubscribe,
1025 idleTtlMs: 0,
1026 }),
1027 startProviderAuth: createEnvironmentRpcCommand(runtime, {
1028 label: "environment-data:provider:auth-start",
1029 tag: WS_METHODS.providerAuthStart,
1030 concurrency: {
1031 mode: "singleFlight",
1032 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1033 },
1034 }),
1035 respondProviderAuth: createEnvironmentRpcCommand(runtime, {
1036 label: "environment-data:provider:auth-respond",
1037 tag: WS_METHODS.providerAuthRespond,
1038 }),
1039 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
1040 label: "environment-data:provider:auth-complete",
1041 tag: WS_METHODS.providerAuthComplete,
1042 }),
1043 chatGptReconnectProfile: createEnvironmentRpcCommand(runtime, {
1044 label: "environment-data:chatgpt:reconnect-profile",
1045 tag: WS_METHODS.chatGptReconnectProfile,
1046 }),
1047 chatGptImportProfile: createEnvironmentRpcCommand(runtime, {
1048 label: "environment-data:chatgpt:import-profile",
1049 tag: WS_METHODS.chatGptImportProfile,
1050 }),
1051 chatGptHandoffState: createEnvironmentSubscriptionAtomFamily(runtime, {
1052 label: "environment-data:chatgpt:handoff",
1053 sensitiveInput: true,
1054 // OAuth must not be replayed when the connection recovers.
1055 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.chatGptHandoffSubscribe>) =>
1056 runStream(WS_METHODS.chatGptHandoffSubscribe, input),
1057 idleTtlMs: 0,
1058 }),
1059 codexAuthCallbackState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1060 label: "environment-data:codex:auth-callback",
1061 tag: WS_METHODS.codexAuthCallbackSubscribe,
1062 idleTtlMs: 0,
1063 }),
1064 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
1065 label: "environment-data:provider:auth-cancel",
1066 tag: WS_METHODS.providerAuthCancel,
1067 }),
1068 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
1069 label: "environment-data:provider:auth-logout",
1070 tag: WS_METHODS.providerAuthLogout,
1071 }),
1072 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1073 label: "environment-data:provider:install-state",
1074 tag: WS_METHODS.providerInstallSubscribe,
1075 idleTtlMs: 0,
1076 }),
1077 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1078 label: "environment-data:provider:install-start",
1079 tag: WS_METHODS.providerInstallStart,
1080 concurrency: {
1081 mode: "singleFlight",
1082 key: ({ environmentId }) => environmentId,
1083 },
1084 }),
1085 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1086 label: "environment-data:provider:install-cancel",
1087 tag: WS_METHODS.providerInstallCancel,
1088 }),
1089 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1090 label: "environment-data:provider:install-remove",
1091 tag: WS_METHODS.providerInstallRemove,
1092 }),
1093 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1094 label: "environment-data:server:trace-diagnostics",
1095 tag: WS_METHODS.serverGetTraceDiagnostics,
1096 }),
1097 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1098 label: "environment-data:server:process-diagnostics",
1099 tag: WS_METHODS.serverGetProcessDiagnostics,
1100 }),
1101 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1102 label: "environment-data:server:host-resources",
1103 idleTtlMs: 0,
1104 staleTimeMs: 5_000,
1105 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1106 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1107 }),
1108 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1109 label: "environment-data:server:process-resource-history",
1110 tag: WS_METHODS.serverGetProcessResourceHistory,
1111 }),
1112 scheduledTaskWebhookDeliveries: createEnvironmentRpcQueryAtomFamily(runtime, {
1113 label: "environment-data:server:scheduled-task:webhook-deliveries",
1114 tag: WS_METHODS.scheduledTasksListWebhookDeliveries,
1115 }),
1116 scheduledTaskWebhookDelivery: createEnvironmentRpcQueryAtomFamily(runtime, {
1117 label: "environment-data:server:scheduled-task:webhook-delivery",
1118 tag: WS_METHODS.scheduledTasksGetWebhookDelivery,
1119 }),
1120 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1121 label: "environment-data:server:scheduled-tasks:live",
1122 tag: WS_METHODS.scheduledTasksSubscribe,
1123 }),
1124 // A cold transcript scan is measured in seconds, so keep the result around
1125 // long enough that switching windows or re-rendering does not rescan.
1126 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1127 label: "environment-data:server:usage-summary",
1128 tag: WS_METHODS.serverGetUsageSummary,
1129 staleTimeMs: 60_000,
1130 refreshTrigger: ({ environmentId }) => usageScanSettingsAtom(environmentId),
1131 execute: (input, emit) =>
1132 request(WS_METHODS.serverGetUsageSummary, input).pipe(
1133 Effect.flatMap((summary) =>
1134 summary.sources.some((source) => source.refreshing === true)
1135 ? emit(summary).pipe(
1136 Effect.andThen(
1137 request(WS_METHODS.serverGetUsageSummary, { ...input, awaitRefresh: true }),
1138 ),
1139 Effect.catch((error) =>
1140 Effect.logWarning("Could not refresh slow usage sources.").pipe(
1141 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
1142 Effect.as(summary),
1143 ),
1144 ),
1145 )
1146 : Effect.succeed(summary),
1147 ),
1148 ),
1149 }),
1150 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1151 label: "environment-data:server:resource-telemetry",
1152 tag: WS_METHODS.subscribeResourceTelemetry,
1153 idleTtlMs: 0,
1154 }),
1155 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1156 label: "environment-data:server:resource-telemetry-history",
1157 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1158 staleTimeMs: 5_000,
1159 }),
1160 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1161 label: "environment-data:server:acp-registry:search",
1162 tag: WS_METHODS.serverSearchAcpRegistry,
1163 staleTimeMs: 0,
1164 idleTtlMs: 0,
1165 }),
1166 configProjection,
1167 welcome,
1168 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1169 label: "environment-data:server:legacy-thread-migration",
1170 tag: WS_METHODS.subscribeServerLifecycle,
1171 transform: (stream) =>
1172 stream.pipe(
1173 Stream.filterMap((event) =>
1174 event.type === "legacyThreadMigration"
1175 ? Result.succeed(event.payload)
1176 : Result.failVoid,
1177 ),
1178 ),
1179 }),
1180 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1181 label: "environment-data:server:consume-reset-credit",
1182 tag: WS_METHODS.providerConsumeResetCredit,
1183 concurrency: {
1184 mode: "singleFlight",
1185 // Both ids are free-form strings; a delimiter could collide.
1186 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1187 },
1188 }),
1189 refreshProviders: createEnvironmentRpcCommand(runtime, {
1190 label: "environment-data:server:refresh-providers",
1191 tag: WS_METHODS.serverRefreshProviders,
1192 concurrency: {
1193 mode: "singleFlight",
1194 key: ({ environmentId, input }) =>
1195 JSON.stringify([
1196 environmentId,
1197 input.instanceId ?? null,
1198 input.cwd ?? null,
1199 input.fresh ?? false,
1200 input.refreshModels ?? false,
1201 ]),
1202 },
1203 }),
1204 updateProvider: createEnvironmentRpcCommand(runtime, {
1205 label: "environment-data:server:update-provider",
1206 tag: WS_METHODS.serverUpdateProvider,
1207 scheduler: configScheduler,
1208 concurrency: configConcurrency,
1209 }),
1210 updateServer,
1211 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1212 label: "environment-data:server:upsert-keybinding",
1213 tag: WS_METHODS.serverUpsertKeybinding,
1214 scheduler: configScheduler,
1215 concurrency: configConcurrency,
1216 }),
1217 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1218 label: "environment-data:server:remove-keybinding",
1219 tag: WS_METHODS.serverRemoveKeybinding,
1220 scheduler: configScheduler,
1221 concurrency: configConcurrency,
1222 }),
1223 updateSettings,
1224 mutateProviderInstance: updateSettings,
1225 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1226 label: "environment-data:server:acp-registry:prepare",
1227 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1228 concurrency: {
1229 mode: "singleFlight",
1230 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1231 },
1232 }),
1233 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1234 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1235 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1236 concurrency: {
1237 mode: "singleFlight",
1238 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1239 },
1240 }),
1241 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1242 label: "environment-data:server:acp-registry:accept-url-auth",
1243 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1244 concurrency: {
1245 mode: "singleFlight",
1246 key: ({ environmentId, input }) =>
1247 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1248 },
1249 }),
1250 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1251 label: "environment-data:server:acp-registry:list-sessions",
1252 tag: WS_METHODS.serverListAcpRegistrySessions,
1253 concurrency: {
1254 mode: "singleFlight",
1255 key: ({ environmentId, input }) =>
1256 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1257 },
1258 }),
1259 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1260 label: "environment-data:server:acp-registry:import-session",
1261 tag: WS_METHODS.serverImportAcpRegistrySession,
1262 concurrency: {
1263 mode: "singleFlight",
1264 key: ({ environmentId, input }) =>
1265 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1266 },
1267 }),
1268 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1269 label: "environment-data:server:acp-registry:delete-session",
1270 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1271 concurrency: {
1272 mode: "singleFlight",
1273 key: ({ environmentId, input }) =>
1274 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1275 },
1276 }),
1277 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1278 label: "environment-data:server:acp-registry:list-providers",
1279 tag: WS_METHODS.serverListAcpRegistryProviders,
1280 concurrency: {
1281 mode: "singleFlight",
1282 key: ({ environmentId, input }) =>
1283 `${environmentId}:${input.instanceId}:${input.projectId}`,
1284 },
1285 }),
1286 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1287 label: "environment-data:server:acp-registry:set-provider",
1288 tag: WS_METHODS.serverSetAcpRegistryProvider,
1289 concurrency: {
1290 mode: "singleFlight",
1291 key: ({ environmentId, input }) =>
1292 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1293 },
1294 }),
1295 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1296 label: "environment-data:server:acp-registry:disable-provider",
1297 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1298 concurrency: {
1299 mode: "singleFlight",
1300 key: ({ environmentId, input }) =>
1301 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1302 },
1303 }),
1304 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1305 label: "environment-data:server:acp-registry:logout",
1306 tag: WS_METHODS.serverLogoutAcpRegistry,
1307 concurrency: {
1308 mode: "singleFlight",
1309 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1310 },
1311 }),
1312 signalProcess: createEnvironmentRpcCommand(runtime, {
1313 label: "environment-data:server:signal-process",
1314 tag: WS_METHODS.serverSignalProcess,
1315 }),
1316 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1317 label: "environment-data:server:scheduled-task:upsert",
1318 tag: WS_METHODS.scheduledTasksUpsert,
1319 scheduler: configScheduler,
1320 concurrency: configConcurrency,
1321 }),
1322 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1323 label: "environment-data:server:scheduled-task:set-enabled",
1324 tag: WS_METHODS.scheduledTasksSetEnabled,
1325 scheduler: configScheduler,
1326 concurrency: configConcurrency,
1327 }),
1328 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1329 label: "environment-data:server:scheduled-task:delete",
1330 tag: WS_METHODS.scheduledTasksDelete,
1331 scheduler: configScheduler,
1332 concurrency: configConcurrency,
1333 }),
1334 // Deliberately not on the config lane: run-now blocks until the run is
1335 // dispatched, and a slow run must not stall settings/keybinding/provider
1336 // mutations (or other scheduled-task edits) queued behind it.
1337 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1338 label: "environment-data:server:scheduled-task:run-now",
1339 tag: WS_METHODS.scheduledTasksRunNow,
1340 }),
1341 rotateScheduledTaskWebhookToken: createEnvironmentRpcCommand(runtime, {
1342 label: "environment-data:server:scheduled-task:rotate-webhook-token",
1343 tag: WS_METHODS.scheduledTasksRotateWebhookToken,
1344 scheduler: configScheduler,
1345 concurrency: configConcurrency,
1346 }),
1347 // Off the config lane: answering a card must not queue behind settings
1348 // edits. One answer per card at a time.
1349 answerSecretRequest: createEnvironmentRpcCommand(runtime, {
1350 label: "environment-data:server:secrets:answer-request",
1351 tag: WS_METHODS.secretsAnswerRequest,
1352 concurrency: {
1353 mode: "singleFlight",
1354 key: ({ environmentId, input }) =>
1355 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
1356 },
1357 }),
1358 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1359 label: "environment-data:server:refresh-usage-rates",
1360 tag: WS_METHODS.serverRefreshUsageRates,
1361 concurrency: {
1362 mode: "singleFlight",
1363 key: ({ environmentId }) => environmentId,
1364 },
1365 }),
1366 checkOtlpEndpoint: createEnvironmentRpcCommand(runtime, {
1367 label: "environment-data:server:check-otlp-endpoint",
1368 tag: WS_METHODS.serverCheckOtlpEndpoint,
1369 }),
1370 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1371 label: "environment-data:server:retry-resource-telemetry",
1372 tag: WS_METHODS.serverRetryResourceTelemetry,
1373 concurrency: {
1374 mode: "singleFlight",
1375 key: ({ environmentId }) => environmentId,
1376 },
1377 }),
1378 };
1379}