Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

1,345 lines49.6 KB

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