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

server.ts

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