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 shouldRecommendDatabaseCompaction,
10 WS_METHODS,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Duration from "effect/Duration";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
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 // A cached stall would read as a fresh freeze on the next launch.
391 const { lastEventLoopStall: _stall, ...cacheable } = withoutEnvironmentThemes(config);
392 return yield* cache.saveServerConfig(environmentId, cacheable).pipe(
393 Effect.as(true),
394 Effect.catch((error) =>
395 Effect.logWarning("Could not persist cached server configuration.").pipe(
396 Effect.annotateLogs({
397 environmentId,
398 ...safeErrorLogAttributes(error),
399 }),
400 Effect.as(false),
401 ),
402 ),
403 );
404 });
405
406 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
407 config: ServerConfig,
408 ) {
409 if (!(yield* persist(config))) {
410 return;
411 }
412 yield* Ref.update(pendingPersistence, (pending) =>
413 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
414 );
415 });
416
417 yield* Effect.addFinalizer(() =>
418 Ref.get(pendingPersistence).pipe(
419 Effect.flatMap(
420 Option.match({
421 onNone: () => Effect.void,
422 onSome: (config) => persist(config).pipe(Effect.asVoid),
423 }),
424 ),
425 ),
426 );
427
428 yield* runCachePersistence(persistence, persistPending).pipe(Effect.forkScoped);
429
430 yield* subscribe(WS_METHODS.subscribeServerConfig, {
431 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
432 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
433 ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
434 }).pipe(
435 Stream.runForEach((event) =>
436 Effect.gen(function* () {
437 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
438 if (Option.isNone(next)) {
439 return;
440 }
441 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
442 yield* SubscriptionRef.set(state, next);
443 yield* Queue.offer(persistence, next.value.config);
444 }),
445 ),
446 Effect.forkScoped,
447 );
448
449 return state;
450 },
451);
452
453function serverConfigStateChanges(
454 environmentId: EnvironmentId,
455 subscription: ServerConfigSubscriptionOptions,
456) {
457 return followStreamInEnvironment(
458 environmentId,
459 Stream.unwrap(
460 makeEnvironmentServerConfigState(subscription).pipe(
461 Effect.map((state) =>
462 SubscriptionRef.changes(state).pipe(
463 Stream.filterMap((projection) =>
464 Option.match(projection, {
465 onNone: () => Result.failVoid,
466 onSome: (value) => Result.succeed(value),
467 }),
468 ),
469 ),
470 ),
471 ),
472 ),
473 );
474}
475
476export function applyServerWelcomeEvent(
477 current: EnvironmentServerWelcomeState,
478 session: RpcSession,
479 event: {
480 readonly type: "welcome" | "ready" | "legacyThreadMigration";
481 readonly payload: unknown;
482 },
483): EnvironmentServerWelcomeState {
484 return event.type === "welcome" && current.currentSession === session
485 ? {
486 ...current,
487 welcomeSession: session,
488 welcome: event.payload as ServerLifecycleWelcomePayload,
489 }
490 : current;
491}
492
493export interface EnvironmentServerWelcomeState {
494 readonly currentSession: RpcSession | null;
495 readonly welcomeSession: RpcSession | null;
496 readonly welcome: ServerLifecycleWelcomePayload | null;
497}
498
499export function resolveServerWelcomeState(
500 state: EnvironmentServerWelcomeState,
501): ServerLifecycleWelcomePayload | null {
502 return state.currentSession === state.welcomeSession ? state.welcome : null;
503}
504
505export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")(
506 function* () {
507 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
508 const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session));
509 const state = yield* SubscriptionRef.make<EnvironmentServerWelcomeState>({
510 currentSession: initialSession,
511 welcomeSession: null,
512 welcome: null,
513 });
514
515 const updateWithCurrentSession = Effect.fn(
516 "EnvironmentServerWelcomeState.updateWithCurrentSession",
517 )(function* (
518 update: (
519 current: EnvironmentServerWelcomeState,
520 currentSession: RpcSession | null,
521 ) => EnvironmentServerWelcomeState,
522 ) {
523 return yield* SubscriptionRef.modifyEffect(state, (current) =>
524 SubscriptionRef.get(supervisor.session).pipe(
525 Effect.map(
526 (latestSession) =>
527 [undefined, update(current, Option.getOrNull(latestSession))] as const,
528 ),
529 ),
530 );
531 });
532
533 yield* SubscriptionRef.changes(supervisor.session).pipe(
534 Stream.runForEach(() =>
535 updateWithCurrentSession((current, currentSession) => ({
536 ...current,
537 currentSession,
538 })),
539 ),
540 Effect.forkScoped,
541 );
542
543 yield* subscribeDynamicWithSession(
544 WS_METHODS.subscribeServerLifecycle,
545 Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) {
546 yield* updateWithCurrentSession((current, currentSession) =>
547 currentSession === session
548 ? {
549 ...current,
550 currentSession,
551 welcomeSession: session,
552 welcome: null,
553 }
554 : { ...current, currentSession },
555 );
556 return {};
557 }),
558 ).pipe(
559 Stream.runForEach(([session, event]) =>
560 updateWithCurrentSession((current, currentSession) =>
561 applyServerWelcomeEvent(
562 {
563 ...current,
564 currentSession,
565 },
566 session,
567 event,
568 ),
569 ),
570 ),
571 Effect.forkScoped,
572 );
573
574 return state;
575 },
576);
577
578function serverWelcomeStateChanges(environmentId: EnvironmentId) {
579 return followStreamInEnvironment(
580 environmentId,
581 Stream.unwrap(
582 makeEnvironmentServerWelcomeState().pipe(
583 Effect.map((state) =>
584 SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)),
585 ),
586 ),
587 ),
588 );
589}
590
591export function resolveServerConfigValue(
592 projection: ServerConfigProjection | null,
593 initialConfig: ServerConfig | null,
594): ServerConfig | null {
595 if (
596 projection?.source === "live" &&
597 (initialConfig === null ||
598 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
599 ) {
600 return projection.config;
601 }
602 return initialConfig ?? projection?.config ?? null;
603}
604
605export function createServerEnvironmentAtoms<R, E>(
606 runtime: Atom.AtomRuntime<
607 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
608 E
609 >,
610 options: {
611 readonly initialConfigValueAtom: (
612 environmentId: EnvironmentId,
613 ) => Atom.Atom<ServerConfig | null>;
614 readonly environmentThemes?: boolean;
615 readonly usageLimitSources?: boolean;
616 readonly usageLimitsCommand?: boolean;
617 },
618) {
619 const configScheduler = createAtomCommandScheduler();
620 const updateScheduler = createAtomCommandScheduler();
621 const configConcurrency = {
622 mode: "serial" as const,
623 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
624 };
625 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
626 runtime
627 .atom(
628 serverConfigStateChanges(environmentId, {
629 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
630 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
631 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
632 }),
633 )
634 .pipe(
635 Atom.setIdleTTL(5 * 60_000),
636 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
637 ),
638 );
639 const configProjection = (target: {
640 readonly environmentId: EnvironmentId;
641 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
642 }) => configProjectionFamily(target.environmentId);
643 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
644 Atom.withLabel("environment-data:server:config:empty"),
645 );
646 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
647 if (environmentId === null) {
648 return emptyConfigAtom;
649 }
650 return Atom.make((get): ServerConfig | null => {
651 const projection = Option.getOrNull(
652 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
653 );
654 return resolveServerConfigValue(
655 projection,
656 get(options.initialConfigValueAtom(environmentId)),
657 );
658 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
659 });
660 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
661 Atom.make((get) =>
662 serverUpdateStateForServerVersion(
663 get(serverUpdateStateAtom(environmentId)),
664 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
665 ),
666 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
667 );
668 const updateStateAtom = (environmentId: EnvironmentId | null) =>
669 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
670 const updateServer = createRuntimeCommand<
671 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
672 E,
673 ServerUpdateTarget,
674 ServerSelfUpdateResult,
675 unknown
676 >(runtime, {
677 label: "environment-data:server:update-server",
678 scheduler: updateScheduler,
679 concurrency: configConcurrency,
680 execute: (target, atomRegistry) => {
681 const stateAtom = serverUpdateStateAtom(target.environmentId);
682 let targetVersion = target.input.targetVersion;
683 let fromVersion =
684 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
685 targetVersion;
686 let currentStage: ServerUpdateStage = "downloading";
687 let desktopCommitLostTransport = false;
688 atomRegistry.set(stateAtom, {
689 status: "running",
690 stage: currentStage,
691 fromVersion,
692 targetVersion,
693 });
694
695 return Effect.gen(function* () {
696 const environmentRegistry = yield* EnvironmentRegistry.EnvironmentRegistry;
697 const desktopCommitStarting = yield* Deferred.make<void>();
698 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
699 const desktopReconnected = yield* Deferred.make<void>();
700 yield* Deferred.await(desktopCommitStarting).pipe(
701 Effect.andThen(
702 environmentRegistry.stateChanges(target.environmentId).pipe(
703 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
704 Stream.dropWhile((state) => state.phase === "connected"),
705 Stream.filter((state) => state.phase === "connected"),
706 Stream.runHead,
707 ),
708 ),
709 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
710 Effect.forkChild,
711 );
712 const result = yield* scheduleAtomCommandEffect(
713 atomRegistry,
714 configScheduler,
715 configConcurrency,
716 target,
717 Effect.gen(function* () {
718 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
719 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
720 atomRegistry.set(stateAtom, {
721 status: "running",
722 stage: currentStage,
723 fromVersion,
724 targetVersion,
725 });
726
727 const supportsProgress =
728 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
729 const updateResult: ServerSelfUpdateResult = supportsProgress
730 ? yield* Effect.gen(function* () {
731 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
732 Option.none(),
733 );
734 const streamExit = yield* environmentRegistry
735 .runStream(
736 target.environmentId,
737 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
738 )
739 .pipe(
740 Stream.runForEach((event) =>
741 Effect.sync(() => {
742 const state = serverUpdateStateForProgressEvent(
743 fromVersion,
744 targetVersion,
745 event,
746 );
747 currentStage = state.stage;
748 atomRegistry.set(stateAtom, state);
749 }).pipe(
750 Effect.andThen(
751 event.type === "complete"
752 ? Ref.set(terminal, Option.some(event.result))
753 : Effect.void,
754 ),
755 ),
756 ),
757 Effect.exit,
758 );
759 return yield* resolveServerUpdateProgressResult(
760 targetVersion,
761 yield* Ref.get(terminal),
762 streamExit,
763 );
764 })
765 : yield* Effect.gen(function* () {
766 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
767 const exit = yield* environmentRegistry
768 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
769 .pipe(Effect.exit);
770 if (Exit.isSuccess(exit)) {
771 return exit.value;
772 }
773 if (
774 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
775 isLegacyUpdateHandoffLoss(exit.cause)
776 ) {
777 // Older servers can tear down the transport before their
778 // unary acknowledgement arrives. Treat only that transport
779 // loss as a handoff, then prove it by waiting for target ready.
780 return { targetVersion, method: selfUpdateMethod };
781 }
782 return yield* Effect.failCause(exit.cause);
783 });
784
785 if (
786 updateResult.method === "desktop-app" &&
787 updateResult.desktopUpdateToken !== undefined
788 ) {
789 yield* Deferred.succeed(desktopCommitStarting, undefined);
790 yield* Deferred.await(desktopReconnectObserverArmed);
791 const commitExit = yield* environmentRegistry
792 .run(
793 target.environmentId,
794 request(WS_METHODS.serverCommitDesktopUpdate, {
795 requestId: updateResult.desktopUpdateToken,
796 }),
797 )
798 .pipe(Effect.exit);
799 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
800 return yield* Effect.failCause(commitExit.cause);
801 }
802 desktopCommitLostTransport = Exit.isFailure(commitExit);
803 }
804
805 targetVersion = updateResult.targetVersion;
806
807 currentStage = "resuming";
808 atomRegistry.set(stateAtom, {
809 status: "running",
810 stage: currentStage,
811 fromVersion,
812 targetVersion,
813 });
814 return updateResult;
815 }),
816 );
817
818 yield* nudgeReconnectDuringUpdateRestart({
819 stateChanges: environmentRegistry.stateChanges(target.environmentId),
820 retryNow: environmentRegistry.retryNow(target.environmentId),
821 }).pipe(Effect.forkChild);
822
823 if (result.method === "desktop-app" && desktopCommitLostTransport) {
824 yield* Deferred.await(desktopReconnected).pipe(
825 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
826 );
827 }
828
829 const waitForReady = environmentRegistry
830 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
831 .pipe(
832 Stream.filter(
833 (event): event is ServerLifecycleStreamReadyEvent =>
834 event.type === "ready" && matchesServerUpdateResumeEvent(result, event),
835 ),
836 Stream.runHead,
837 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
838 Effect.map(Option.flatten),
839 );
840 const nextReady = waitForReady.pipe(
841 Effect.flatMap(
842 Option.match({
843 onNone: () =>
844 new ServerUpdateResumeTimeoutError({
845 environmentId: target.environmentId,
846 targetVersion,
847 }),
848 onSome: Effect.succeed,
849 }),
850 ),
851 );
852 const desktopUpdateToken = result.desktopUpdateToken;
853 const resumed =
854 result.method === "desktop-app" && desktopUpdateToken !== undefined
855 ? yield* waitForDesktopUpdateTarget(
856 result.targetVersion,
857 nextReady,
858 runDesktopCommitWithReconnectObserver(
859 environmentRegistry.stateChanges(target.environmentId),
860 environmentRegistry
861 .run(
862 target.environmentId,
863 request(WS_METHODS.serverCommitDesktopUpdate, {
864 requestId: desktopUpdateToken,
865 }),
866 )
867 .pipe(Effect.asVoid),
868 ),
869 )
870 : yield* nextReady;
871 yield* validateServerUpdateReadyEvent(result, resumed);
872
873 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
874 return result;
875 }).pipe(
876 Effect.onExit((exit) =>
877 Effect.sync(() => {
878 if (Exit.isSuccess(exit)) {
879 return;
880 }
881 if (Cause.hasInterruptsOnly(exit.cause)) {
882 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
883 return;
884 }
885 atomRegistry.set(stateAtom, {
886 status: "failed",
887 stage: currentStage,
888 fromVersion,
889 targetVersion,
890 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
891 });
892 }),
893 ),
894 );
895 },
896 });
897 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
898 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
899 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
900 ),
901 );
902 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
903 Atom.make((get) => {
904 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
905 // Only changed prices should trigger another transcript scan. Settings
906 // snapshots can recreate the same mapping in a different property order.
907 return JSON.stringify(
908 Object.keys(overrides)
909 .sort()
910 .map((model) => {
911 const price = overrides[model]!;
912 return [
913 model,
914 price.inputCostPerMillionTokens,
915 price.outputCostPerMillionTokens,
916 price.cacheReadCostPerMillionTokens,
917 price.cacheWriteCostPerMillionTokens,
918 ];
919 }),
920 );
921 }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
922 );
923 const usageScanSettingsAtom = Atom.family((environmentId: EnvironmentId) =>
924 Atom.make((get) => {
925 const settings = get(settingsValueAtom(environmentId));
926 const aliases = settings?.usageModelAliases ?? {};
927 return JSON.stringify([
928 get(usagePricesAtom(environmentId)),
929 Object.keys(aliases)
930 .sort()
931 .map((model) => [model, aliases[model]]),
932 settings?.cursorKeychainUsageEnabled ?? false,
933 ]);
934 }).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
935 );
936 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
937 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
938 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
939 ),
940 );
941 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
942 runtime
943 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
944 .pipe(
945 Atom.setIdleTTL(5 * 60_000),
946 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
947 ),
948 );
949 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
950 Atom.make((get) => {
951 const result = get(welcomeStateFamily(environmentId));
952 if (result._tag !== "Success") return result;
953 return result.value === null
954 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
955 : AsyncResult.success(result.value, result);
956 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
957 );
958 const databaseStorage = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
959 label: "environment-data:server:database-storage",
960 tag: WS_METHODS.serverGetDatabaseStorage,
961 idleTtlMs: 0,
962 });
963 // Keyed by a JSON array of environment ids so one notice can list every machine.
964 const databaseCompactionRecommendations = Atom.family((environmentIdsKey: string) => {
965 const sources = (JSON.parse(environmentIdsKey) as EnvironmentId[]).map((environmentId) => ({
966 environmentId,
967 atom: databaseStorage({ environmentId, input: {} }),
968 }));
969 return Atom.make((get) =>
970 sources
971 .flatMap(({ environmentId, atom }) => {
972 const result = get(atom);
973 return result._tag === "Success" &&
974 result.value !== null &&
975 shouldRecommendDatabaseCompaction(result.value)
976 ? [{ environmentId, status: result.value }]
977 : [];
978 })
979 .sort((left, right) => right.status.reclaimableBytes - left.status.reclaimableBytes),
980 ).pipe(
981 Atom.withLabel(
982 `environment-data:server:database-compaction-recommendations:${environmentIdsKey}`,
983 ),
984 );
985 });
986 const welcome = (target: {
987 readonly environmentId: EnvironmentId;
988 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
989 }) => welcomeFamily(target.environmentId);
990 const updateSettings = createEnvironmentRpcCommand(runtime, {
991 label: "environment-data:server:update-settings",
992 tag: WS_METHODS.serverUpdateSettings,
993 scheduler: configScheduler,
994 concurrency: configConcurrency,
995 });
996
997 return {
998 configValueAtom,
999 runStorageCleanup: createEnvironmentRpcCommand(runtime, {
1000 label: "environment-data:server:run-storage-cleanup",
1001 tag: WS_METHODS.serverRunStorageCleanup,
1002 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1003 }),
1004 databaseStorage,
1005 databaseCompactionRecommendations,
1006 storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1007 label: "environment-data:server:storage-cleanup-report",
1008 tag: WS_METHODS.serverGetStorageCleanupReport,
1009 idleTtlMs: 0,
1010 }),
1011 updateStateAtom,
1012 settingsValueAtom,
1013 providersValueAtom,
1014 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1015 label: "environment-data:provider:auth-state",
1016 tag: WS_METHODS.providerAuthSubscribe,
1017 idleTtlMs: 0,
1018 }),
1019 startProviderAuth: createEnvironmentRpcCommand(runtime, {
1020 label: "environment-data:provider:auth-start",
1021 tag: WS_METHODS.providerAuthStart,
1022 concurrency: {
1023 mode: "singleFlight",
1024 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1025 },
1026 }),
1027 respondProviderAuth: createEnvironmentRpcCommand(runtime, {
1028 label: "environment-data:provider:auth-respond",
1029 tag: WS_METHODS.providerAuthRespond,
1030 }),
1031 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
1032 label: "environment-data:provider:auth-complete",
1033 tag: WS_METHODS.providerAuthComplete,
1034 }),
1035 chatGptReconnectProfile: createEnvironmentRpcCommand(runtime, {
1036 label: "environment-data:chatgpt:reconnect-profile",
1037 tag: WS_METHODS.chatGptReconnectProfile,
1038 }),
1039 chatGptImportProfile: createEnvironmentRpcCommand(runtime, {
1040 label: "environment-data:chatgpt:import-profile",
1041 tag: WS_METHODS.chatGptImportProfile,
1042 }),
1043 chatGptHandoffState: createEnvironmentSubscriptionAtomFamily(runtime, {
1044 label: "environment-data:chatgpt:handoff",
1045 sensitiveInput: true,
1046 // OAuth must not be replayed when the connection recovers.
1047 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.chatGptHandoffSubscribe>) =>
1048 runStream(WS_METHODS.chatGptHandoffSubscribe, input),
1049 idleTtlMs: 0,
1050 }),
1051 codexAuthCallbackState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1052 label: "environment-data:codex:auth-callback",
1053 tag: WS_METHODS.codexAuthCallbackSubscribe,
1054 idleTtlMs: 0,
1055 }),
1056 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
1057 label: "environment-data:provider:auth-cancel",
1058 tag: WS_METHODS.providerAuthCancel,
1059 }),
1060 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
1061 label: "environment-data:provider:auth-logout",
1062 tag: WS_METHODS.providerAuthLogout,
1063 }),
1064 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1065 label: "environment-data:provider:install-state",
1066 tag: WS_METHODS.providerInstallSubscribe,
1067 idleTtlMs: 0,
1068 }),
1069 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1070 label: "environment-data:provider:install-start",
1071 tag: WS_METHODS.providerInstallStart,
1072 concurrency: {
1073 mode: "singleFlight",
1074 key: ({ environmentId }) => environmentId,
1075 },
1076 }),
1077 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1078 label: "environment-data:provider:install-cancel",
1079 tag: WS_METHODS.providerInstallCancel,
1080 }),
1081 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1082 label: "environment-data:provider:install-remove",
1083 tag: WS_METHODS.providerInstallRemove,
1084 }),
1085 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1086 label: "environment-data:server:trace-diagnostics",
1087 tag: WS_METHODS.serverGetTraceDiagnostics,
1088 }),
1089 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1090 label: "environment-data:server:process-diagnostics",
1091 tag: WS_METHODS.serverGetProcessDiagnostics,
1092 }),
1093 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1094 label: "environment-data:server:host-resources",
1095 idleTtlMs: 0,
1096 staleTimeMs: 5_000,
1097 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1098 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1099 }),
1100 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1101 label: "environment-data:server:process-resource-history",
1102 tag: WS_METHODS.serverGetProcessResourceHistory,
1103 }),
1104 scheduledTaskWebhookDeliveries: createEnvironmentRpcQueryAtomFamily(runtime, {
1105 label: "environment-data:server:scheduled-task:webhook-deliveries",
1106 tag: WS_METHODS.scheduledTasksListWebhookDeliveries,
1107 }),
1108 scheduledTaskWebhookDelivery: createEnvironmentRpcQueryAtomFamily(runtime, {
1109 label: "environment-data:server:scheduled-task:webhook-delivery",
1110 tag: WS_METHODS.scheduledTasksGetWebhookDelivery,
1111 }),
1112 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1113 label: "environment-data:server:scheduled-tasks:live",
1114 tag: WS_METHODS.scheduledTasksSubscribe,
1115 }),
1116 // A cold transcript scan is measured in seconds, so keep the result around
1117 // long enough that switching windows or re-rendering does not rescan.
1118 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1119 label: "environment-data:server:usage-summary",
1120 tag: WS_METHODS.serverGetUsageSummary,
1121 staleTimeMs: 60_000,
1122 refreshTrigger: ({ environmentId }) => usageScanSettingsAtom(environmentId),
1123 execute: (input, emit) =>
1124 request(WS_METHODS.serverGetUsageSummary, input).pipe(
1125 Effect.flatMap((summary) =>
1126 summary.sources.some((source) => source.refreshing === true)
1127 ? emit(summary).pipe(
1128 Effect.andThen(
1129 request(WS_METHODS.serverGetUsageSummary, { ...input, awaitRefresh: true }),
1130 ),
1131 Effect.catch((error) =>
1132 Effect.logWarning("Could not refresh slow usage sources.").pipe(
1133 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
1134 Effect.as(summary),
1135 ),
1136 ),
1137 )
1138 : Effect.succeed(summary),
1139 ),
1140 ),
1141 }),
1142 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1143 label: "environment-data:server:resource-telemetry",
1144 tag: WS_METHODS.subscribeResourceTelemetry,
1145 idleTtlMs: 0,
1146 }),
1147 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1148 label: "environment-data:server:resource-telemetry-history",
1149 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1150 staleTimeMs: 5_000,
1151 }),
1152 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1153 label: "environment-data:server:acp-registry:search",
1154 tag: WS_METHODS.serverSearchAcpRegistry,
1155 staleTimeMs: 0,
1156 idleTtlMs: 0,
1157 }),
1158 configProjection,
1159 welcome,
1160 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1161 label: "environment-data:server:legacy-thread-migration",
1162 tag: WS_METHODS.subscribeServerLifecycle,
1163 transform: (stream) =>
1164 stream.pipe(
1165 Stream.filterMap((event) =>
1166 event.type === "legacyThreadMigration"
1167 ? Result.succeed(event.payload)
1168 : Result.failVoid,
1169 ),
1170 ),
1171 }),
1172 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1173 label: "environment-data:server:consume-reset-credit",
1174 tag: WS_METHODS.providerConsumeResetCredit,
1175 concurrency: {
1176 mode: "singleFlight",
1177 // Both ids are free-form strings; a delimiter could collide.
1178 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1179 },
1180 }),
1181 refreshProviders: createEnvironmentRpcCommand(runtime, {
1182 label: "environment-data:server:refresh-providers",
1183 tag: WS_METHODS.serverRefreshProviders,
1184 concurrency: {
1185 mode: "singleFlight",
1186 key: ({ environmentId, input }) =>
1187 JSON.stringify([
1188 environmentId,
1189 input.instanceId ?? null,
1190 input.cwd ?? null,
1191 input.fresh ?? false,
1192 input.refreshModels ?? false,
1193 ]),
1194 },
1195 }),
1196 updateProvider: createEnvironmentRpcCommand(runtime, {
1197 label: "environment-data:server:update-provider",
1198 tag: WS_METHODS.serverUpdateProvider,
1199 scheduler: configScheduler,
1200 concurrency: configConcurrency,
1201 }),
1202 updateServer,
1203 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1204 label: "environment-data:server:upsert-keybinding",
1205 tag: WS_METHODS.serverUpsertKeybinding,
1206 scheduler: configScheduler,
1207 concurrency: configConcurrency,
1208 }),
1209 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1210 label: "environment-data:server:remove-keybinding",
1211 tag: WS_METHODS.serverRemoveKeybinding,
1212 scheduler: configScheduler,
1213 concurrency: configConcurrency,
1214 }),
1215 updateSettings,
1216 mutateProviderInstance: updateSettings,
1217 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1218 label: "environment-data:server:acp-registry:prepare",
1219 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1220 concurrency: {
1221 mode: "singleFlight",
1222 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1223 },
1224 }),
1225 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1226 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1227 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1228 concurrency: {
1229 mode: "singleFlight",
1230 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1231 },
1232 }),
1233 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1234 label: "environment-data:server:acp-registry:accept-url-auth",
1235 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1236 concurrency: {
1237 mode: "singleFlight",
1238 key: ({ environmentId, input }) =>
1239 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1240 },
1241 }),
1242 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1243 label: "environment-data:server:acp-registry:list-sessions",
1244 tag: WS_METHODS.serverListAcpRegistrySessions,
1245 concurrency: {
1246 mode: "singleFlight",
1247 key: ({ environmentId, input }) =>
1248 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1249 },
1250 }),
1251 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1252 label: "environment-data:server:acp-registry:import-session",
1253 tag: WS_METHODS.serverImportAcpRegistrySession,
1254 concurrency: {
1255 mode: "singleFlight",
1256 key: ({ environmentId, input }) =>
1257 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1258 },
1259 }),
1260 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1261 label: "environment-data:server:acp-registry:delete-session",
1262 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1263 concurrency: {
1264 mode: "singleFlight",
1265 key: ({ environmentId, input }) =>
1266 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1267 },
1268 }),
1269 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1270 label: "environment-data:server:acp-registry:list-providers",
1271 tag: WS_METHODS.serverListAcpRegistryProviders,
1272 concurrency: {
1273 mode: "singleFlight",
1274 key: ({ environmentId, input }) =>
1275 `${environmentId}:${input.instanceId}:${input.projectId}`,
1276 },
1277 }),
1278 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1279 label: "environment-data:server:acp-registry:set-provider",
1280 tag: WS_METHODS.serverSetAcpRegistryProvider,
1281 concurrency: {
1282 mode: "singleFlight",
1283 key: ({ environmentId, input }) =>
1284 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1285 },
1286 }),
1287 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1288 label: "environment-data:server:acp-registry:disable-provider",
1289 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1290 concurrency: {
1291 mode: "singleFlight",
1292 key: ({ environmentId, input }) =>
1293 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1294 },
1295 }),
1296 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1297 label: "environment-data:server:acp-registry:logout",
1298 tag: WS_METHODS.serverLogoutAcpRegistry,
1299 concurrency: {
1300 mode: "singleFlight",
1301 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1302 },
1303 }),
1304 signalProcess: createEnvironmentRpcCommand(runtime, {
1305 label: "environment-data:server:signal-process",
1306 tag: WS_METHODS.serverSignalProcess,
1307 }),
1308 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1309 label: "environment-data:server:scheduled-task:upsert",
1310 tag: WS_METHODS.scheduledTasksUpsert,
1311 scheduler: configScheduler,
1312 concurrency: configConcurrency,
1313 }),
1314 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1315 label: "environment-data:server:scheduled-task:set-enabled",
1316 tag: WS_METHODS.scheduledTasksSetEnabled,
1317 scheduler: configScheduler,
1318 concurrency: configConcurrency,
1319 }),
1320 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1321 label: "environment-data:server:scheduled-task:delete",
1322 tag: WS_METHODS.scheduledTasksDelete,
1323 scheduler: configScheduler,
1324 concurrency: configConcurrency,
1325 }),
1326 // Deliberately not on the config lane: run-now blocks until the run is
1327 // dispatched, and a slow run must not stall settings/keybinding/provider
1328 // mutations (or other scheduled-task edits) queued behind it.
1329 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1330 label: "environment-data:server:scheduled-task:run-now",
1331 tag: WS_METHODS.scheduledTasksRunNow,
1332 }),
1333 rotateScheduledTaskWebhookToken: createEnvironmentRpcCommand(runtime, {
1334 label: "environment-data:server:scheduled-task:rotate-webhook-token",
1335 tag: WS_METHODS.scheduledTasksRotateWebhookToken,
1336 scheduler: configScheduler,
1337 concurrency: configConcurrency,
1338 }),
1339 // Off the config lane: answering a card must not queue behind settings
1340 // edits. One answer per card at a time.
1341 answerSecretRequest: createEnvironmentRpcCommand(runtime, {
1342 label: "environment-data:server:secrets:answer-request",
1343 tag: WS_METHODS.secretsAnswerRequest,
1344 concurrency: {
1345 mode: "singleFlight",
1346 key: ({ environmentId, input }) =>
1347 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
1348 },
1349 }),
1350 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1351 label: "environment-data:server:refresh-usage-rates",
1352 tag: WS_METHODS.serverRefreshUsageRates,
1353 concurrency: {
1354 mode: "singleFlight",
1355 key: ({ environmentId }) => environmentId,
1356 },
1357 }),
1358 checkOtlpEndpoint: createEnvironmentRpcCommand(runtime, {
1359 label: "environment-data:server:check-otlp-endpoint",
1360 tag: WS_METHODS.serverCheckOtlpEndpoint,
1361 }),
1362 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1363 label: "environment-data:server:retry-resource-telemetry",
1364 tag: WS_METHODS.serverRetryResourceTelemetry,
1365 concurrency: {
1366 mode: "singleFlight",
1367 key: ({ environmentId }) => environmentId,
1368 },
1369 }),
1370 };
1371}