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

server.ts

1,421 lines52.2 KB

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