@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,942 lines 74 KB
Raw
1 import {
2 errorI18nMessage,
3 type MarkedText,
4 markedTextEnglish,
5 resolveMarkedText,
6 thrownErrorMessage,
7 withI18nMessage,
8 } from "../errors/translatable.ts";
9 import {
10 type DesktopUpdateChannel,
11 type EnvironmentId,
12 type ProviderInstanceId,
13 type ServerConfig,
14 type ServerConfigStreamEvent,
15 type ServerLifecycleWelcomePayload,
16 type ServerLifecycleStreamReadyEvent,
17 type ServerProviderWorkspaceSnapshot,
18 ServerSelfUpdateError,
19 type ServerSelfUpdateProgressEvent,
20 type ServerSelfUpdateResult,
21 shouldRecommendDatabaseCompaction,
22 type UsageSummary,
23 WS_METHODS,
24 } from "@t3tools/contracts";
25 import * as Cause from "effect/Cause";
26 import * as Duration from "effect/Duration";
27 import * as Equal from "effect/Equal";
28 import * as Deferred from "effect/Deferred";
29 import * as Effect from "effect/Effect";
30 import * as Exit from "effect/Exit";
31 import * as Fiber from "effect/Fiber";
32 import * as Option from "effect/Option";
33 import * as Queue from "effect/Queue";
34 import * as Ref from "effect/Ref";
35 import * as Result from "effect/Result";
36 import * as Schema from "effect/Schema";
37 import * as Stream from "effect/Stream";
38 import * as SubscriptionRef from "effect/SubscriptionRef";
39 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
40
41 import {
42 createAtomCommandScheduler,
43 createEnvironmentRpcCommand,
44 createEnvironmentQueryAtomFamily,
45 createEnvironmentRpcQueryAtomFamily,
46 createEnvironmentRpcSubscriptionAtomFamily,
47 createEnvironmentSubscriptionAtomFamily,
48 createRuntimeCommand,
49 } from "./runtime.ts";
50 import * as EnvironmentRegistry from "../connection/registry.ts";
51 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
52 import { safeErrorLogAttributes } from "../errors/safeLog.ts";
53 import * as Persistence from "../platform/persistence.ts";
54 import { runCachePersistence } from "./cachePersistence.ts";
55 import {
56 currentSession,
57 isRpcClientError,
58 request,
59 requestGuarded,
60 requestInSession,
61 runStream,
62 runStreamInSession,
63 subscribe,
64 subscribeDynamicWithSession,
65 type EnvironmentRpcInput,
66 } from "../rpc/client.ts";
67 import type { RpcSession } from "../rpc/session.ts";
68 import { followStreamInEnvironment } from "./runtime.ts";
69 import {
70 applyServerConfigProjection,
71 reuseUnchanged,
72 type ServerConfigProjection,
73 withoutEnvironmentThemes,
74 } from "./serverConfigProjection.ts";
75 import { mFallback, msg } from "gt-i18n";
76 import type { MFunctionType } from "gt-i18n/types";
77
78 export type { ServerConfigProjection } from "./serverConfigProjection.ts";
79
80 export type ServerUpdateStage = "downloading" | "installing" | "resuming";
81
82 export type ServerUpdateState =
83 | { readonly status: "idle" }
84 | {
85 readonly status: "running";
86 readonly stage: ServerUpdateStage;
87 readonly fromVersion: string;
88 readonly targetVersion: string;
89 }
90 | {
91 readonly status: "failed";
92 readonly stage: ServerUpdateStage;
93 readonly fromVersion: string;
94 readonly targetVersion: string;
95 readonly message: string;
96 /** `message` as marked text, so it follows the UI language; absent for plain error text. */
97 readonly i18nMessage?: MarkedText;
98 };
99
100 export interface ServerUpdateTarget {
101 readonly environmentId: EnvironmentId;
102 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
103 }
104
105 const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
106 const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
107 Atom.withLabel("environment-data:server:update-state:empty"),
108 );
109 export const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
110 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
111 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
112 ),
113 );
114
115 export class ServerUpdateResumeTimeoutError extends Schema.TaggedError<ServerUpdateResumeTimeoutError>()(
116 "ServerUpdateResumeTimeoutError",
117 {
118 environmentId: Schema.String,
119 targetVersion: Schema.String,
120 },
121 ) {
122 override get message(): string {
123 return markedTextEnglish(this.i18nMessage);
124 }
125
126 get i18nMessage(): MarkedText {
127 return [
128 msg(
129 "Could not confirm that the server resumed on t3@{version}. Reconnect to check the update outcome.",
130 { version: this.targetVersion },
131 ),
132 ];
133 }
134 }
135
136 export class ServerUpdateProgressIncompleteError extends Schema.TaggedError<ServerUpdateProgressIncompleteError>()(
137 "ServerUpdateProgressIncompleteError",
138 {
139 targetVersion: Schema.String,
140 },
141 ) {
142 override get message(): string {
143 return markedTextEnglish(this.i18nMessage);
144 }
145
146 get i18nMessage(): MarkedText {
147 return [
148 msg("The t3@{version} update ended before the server accepted the restart.", {
149 version: this.targetVersion,
150 }),
151 ];
152 }
153 }
154
155 const DESKTOP_RESUMED_WITHOUT_UPDATE = msg(
156 "The desktop app resumed without installing the prepared update.",
157 );
158
159 export class ServerUpdateTerminalError extends Schema.TaggedError<ServerUpdateTerminalError>()(
160 "ServerUpdateTerminalError",
161 {
162 targetVersion: Schema.String,
163 status: Schema.Literals(["committed", "rolled-back", "failed"]),
164 reason: Schema.optional(Schema.String),
165 },
166 ) {
167 override get message(): string {
168 return this.reason ?? markedTextEnglish(this.statusText);
169 }
170
171 get i18nMessage(): MarkedText | undefined {
172 return this.reason === undefined
173 ? this.statusText
174 : this.reason === DESKTOP_RESUMED_WITHOUT_UPDATE
175 ? [DESKTOP_RESUMED_WITHOUT_UPDATE]
176 : undefined;
177 }
178
179 private get statusText(): MarkedText {
180 const version = this.targetVersion;
181 switch (this.status) {
182 case "committed":
183 return [msg("The t3@{version} update committed.", { version })];
184 case "rolled-back":
185 return [msg("The t3@{version} update rolled-back.", { version })];
186 case "failed":
187 return [msg("The t3@{version} update failed.", { version })];
188 }
189 }
190 }
191
192 // Covers the service launcher's 30-minute trial deadline (PREPARED_TIMEOUT_MS)
193 // and a final restart of the previous version when the trial rolls back.
194 const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(32);
195 // A live host replays its ready on subscribe within a round trip; past this, update without a baseline.
196 const SERVER_UPDATE_ACCEPTING_READY_TIMEOUT = Duration.seconds(5);
197
198 export function matchesServerUpdateReadyEvent(
199 result: ServerSelfUpdateResult,
200 event: ServerLifecycleStreamReadyEvent,
201 ): boolean {
202 return result.updateId === undefined
203 ? event.payload.environment.serverVersion === result.targetVersion
204 : event.payload.updateOutcome?.id === result.updateId;
205 }
206
207 /**
208 * `acceptedAt` is the `ready.at` of the process that accepted the update. A launcher host
209 * that comes back as any other process ends the wait, so validation can reject a missing
210 * or foreign outcome instead of timing out.
211 */
212 export function matchesServerUpdateResumeEvent(
213 result: ServerSelfUpdateResult,
214 event: ServerLifecycleStreamReadyEvent,
215 acceptedAt?: string,
216 ): boolean {
217 return (
218 (result.method === "desktop-app" && result.desktopUpdateToken !== undefined) ||
219 matchesServerUpdateReadyEvent(result, event) ||
220 (result.updateId !== undefined && acceptedAt !== undefined && event.payload.at !== acceptedAt)
221 );
222 }
223
224 export function validateServerUpdateReadyEvent(
225 result: ServerSelfUpdateResult,
226 event: ServerLifecycleStreamReadyEvent,
227 ): Effect.Effect<void, ServerUpdateTerminalError> {
228 if (result.updateId === undefined) return Effect.void;
229 const reported = event.payload.updateOutcome;
230 const outcome = reported?.id === result.updateId ? reported : undefined;
231 if (
232 outcome?.status === "committed" &&
233 outcome.targetVersion === result.targetVersion &&
234 event.payload.environment.serverVersion === result.targetVersion
235 ) {
236 return Effect.void;
237 }
238 return Effect.fail(
239 new ServerUpdateTerminalError({
240 targetVersion: result.targetVersion,
241 status: outcome?.status ?? "failed",
242 reason:
243 outcome?.reason ??
244 "The service launcher resumed without committing the requested server version.",
245 }),
246 );
247 }
248
249 /**
250 * The sleep before each nudge is the pacer: a connection that fails instantly
251 * re-enters backoff immediately and would otherwise spin a tight retry loop.
252 *
253 * Callers fork this as a child of the update command so it is interrupted as
254 * soon as the update settles, whether it succeeds, fails, or times out.
255 */
256 export function nudgeReconnectDuringUpdateRestart(input: {
257 readonly stateChanges: Stream.Stream<
258 {
259 readonly phase: string;
260 readonly lastFailure?: { readonly reason: string } | null;
261 },
262 unknown
263 >;
264 readonly retryNow: Effect.Effect<void>;
265 readonly interval?: Duration.Duration;
266 }): Effect.Effect<void> {
267 return input.stateChanges.pipe(
268 Stream.filter(
269 (state) =>
270 state.phase === "backoff" ||
271 (state.phase === "blocked" && state.lastFailure?.reason === "authentication"),
272 ),
273 Stream.runForEach(() =>
274 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
275 ),
276 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
277 Effect.ignore,
278 );
279 }
280
281 export function waitForNextEnvironmentReconnect<E>(
282 stateChanges: Stream.Stream<{ readonly phase: string }, E>,
283 ): Effect.Effect<void, E> {
284 return stateChanges.pipe(
285 Stream.dropWhile((state) => state.phase === "connected"),
286 Stream.filter((state) => state.phase === "connected"),
287 Stream.runHead,
288 Effect.asVoid,
289 );
290 }
291
292 export const runDesktopCommitWithReconnectObserver = Effect.fn(
293 "runDesktopCommitWithReconnectObserver",
294 )(function* <EState, ECommit>(
295 stateChanges: Stream.Stream<{ readonly phase: string }, EState>,
296 commit: Effect.Effect<void, ECommit>,
297 ) {
298 const armed = yield* Deferred.make<void>();
299 const reconnected = yield* Deferred.make<void>();
300 const observer = yield* stateChanges.pipe(
301 Stream.tap(() => Deferred.succeed(armed, undefined)),
302 waitForNextEnvironmentReconnect,
303 Effect.andThen(Deferred.succeed(reconnected, undefined)),
304 Effect.forkChild,
305 );
306 yield* Deferred.await(armed);
307 const commitExit = yield* commit.pipe(Effect.exit);
308 if (Exit.isSuccess(commitExit)) {
309 yield* Fiber.interrupt(observer);
310 return;
311 }
312 if (!isLegacyUpdateHandoffLoss(commitExit.cause)) {
313 yield* Fiber.interrupt(observer);
314 return yield* Effect.failCause(commitExit.cause);
315 }
316 yield* Deferred.await(reconnected).pipe(Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT));
317 return yield* Effect.failCause(commitExit.cause);
318 });
319
320 export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget")(function* <
321 EReady,
322 ECommit,
323 >(
324 targetVersion: string,
325 nextReady: Effect.Effect<ServerLifecycleStreamReadyEvent, EReady>,
326 retryCommit: Effect.Effect<void, ECommit>,
327 ): Effect.fn.Return<ServerLifecycleStreamReadyEvent, EReady | ECommit | ServerUpdateTerminalError> {
328 const maxCommitAttempts = 3;
329 for (let attempt = 1; attempt <= maxCommitAttempts; attempt += 1) {
330 const ready = yield* nextReady;
331 if (ready.payload.environment.serverVersion === targetVersion) return ready;
332 if (attempt === maxCommitAttempts) break;
333 const retryExit = yield* retryCommit.pipe(Effect.exit);
334 if (Exit.isSuccess(retryExit)) break;
335 if (!isLegacyUpdateHandoffLoss(retryExit.cause)) {
336 return yield* Effect.failCause(retryExit.cause);
337 }
338 }
339 return yield* new ServerUpdateTerminalError({
340 targetVersion,
341 status: "failed",
342 reason: DESKTOP_RESUMED_WITHOUT_UPDATE,
343 });
344 });
345
346 export function serverUpdateStateForProgressEvent(
347 fromVersion: string,
348 targetVersion: string,
349 event: ServerSelfUpdateProgressEvent,
350 ): Extract<ServerUpdateState, { status: "running" }> {
351 return {
352 status: "running",
353 stage:
354 event.type !== "complete"
355 ? event.stage
356 : event.result.method === "desktop-app" && event.result.desktopUpdateToken !== undefined
357 ? "installing"
358 : "resuming",
359 fromVersion,
360 targetVersion,
361 };
362 }
363
364 export function serverUpdateStateForServerVersion(
365 state: ServerUpdateState,
366 serverVersion: string | null,
367 ): ServerUpdateState {
368 return state.status === "idle" ||
369 state.status === "running" ||
370 serverVersion === null ||
371 state.fromVersion === serverVersion
372 ? state
373 : IDLE_SERVER_UPDATE_STATE;
374 }
375
376 function serverUpdateFailureMessage(error: unknown, resolve: MFunctionType = mFallback): string {
377 return error instanceof Error
378 ? (thrownErrorMessage(error, resolve) ?? error.message)
379 : resolve(msg("Server update failed."));
380 }
381
382 /** The failed state's `message` and, when the text is ours, its marked text. */
383 export function serverUpdateFailure(error: unknown): {
384 readonly message: string;
385 readonly i18nMessage?: MarkedText;
386 } {
387 const i18nMessage =
388 error instanceof Error ? errorI18nMessage(error) : [msg("Server update failed.")];
389 return i18nMessage === undefined
390 ? { message: serverUpdateFailureMessage(error) }
391 : { message: serverUpdateFailureMessage(error), i18nMessage };
392 }
393
394 /** Marked text for a desktop app whose build track differs from its saved update track. */
395 export function desktopTrackMismatchText(mismatch: {
396 readonly buildChannel: DesktopUpdateChannel;
397 readonly savedChannel: DesktopUpdateChannel;
398 }): string {
399 return msg(
400 "This {build, select, nightly {Nightly} other {Stable}} build can't update from the {saved, select, nightly {Nightly} other {Stable}} track on its own. Switch the update track back to {build, select, nightly {Nightly} other {Stable}}, or use Review beside Update track to retry the switch to {saved, select, nightly {Nightly} other {Stable}}.",
401 { build: mismatch.buildChannel, saved: mismatch.savedChannel },
402 );
403 }
404
405 const isServerSelfUpdateError = Schema.is(ServerSelfUpdateError);
406
407 /** Gives a host's track mismatch marked text; older hosts send only the English `reason`. */
408 export function localizeServerSelfUpdateError<E>(error: E): E {
409 if (!isServerSelfUpdateError(error) || error.trackMismatch === undefined) return error;
410 return withI18nMessage(
411 error,
412 msg("Server update failed:"),
413 desktopTrackMismatchText(error.trackMismatch),
414 );
415 }
416
417 export function serverUpdateFailureText(
418 state: Extract<ServerUpdateState, { status: "failed" }>,
419 resolve: MFunctionType = mFallback,
420 ): string {
421 return state.i18nMessage === undefined
422 ? state.message
423 : resolveMarkedText(state.i18nMessage, resolve);
424 }
425
426 function isRpcSocketError(error: unknown): boolean {
427 if (!isRpcClientError(error)) {
428 return false;
429 }
430 switch (error.reason._tag) {
431 case "SocketReadError":
432 case "SocketWriteError":
433 case "SocketCloseError":
434 return true;
435 default:
436 return false;
437 }
438 }
439
440 export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
441 if (Cause.hasInterruptsOnly(cause)) {
442 return true;
443 }
444 return (
445 cause.reasons.length > 0 &&
446 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
447 );
448 }
449
450 export function resolveServerUpdateProgressResult<E>(
451 targetVersion: string,
452 terminal: Option.Option<ServerSelfUpdateResult>,
453 streamExit: Exit.Exit<void, E>,
454 accepted?: ServerSelfUpdateResult,
455 ): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
456 if (
457 Option.isSome(terminal) &&
458 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
459 ) {
460 return Effect.succeed(terminal.value);
461 }
462 if (Exit.isFailure(streamExit)) {
463 if (accepted !== undefined && isLegacyUpdateHandoffLoss(streamExit.cause)) {
464 return Effect.succeed(accepted);
465 }
466 return Effect.failCause(streamExit.cause);
467 }
468 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
469 }
470
471 const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
472 version: 1,
473 type: "snapshot",
474 config,
475 });
476
477 export interface ServerConfigSubscriptionOptions {
478 readonly environmentThemes?: boolean;
479 readonly usageLimitSources?: boolean;
480 readonly usageLimitsCommand?: boolean;
481 readonly providerCatalogsOnDemand?: boolean;
482 readonly providerCatalogDigests?: boolean;
483 readonly providerStatusDeltas?: boolean;
484 }
485
486 type ServerProviderEntry = ServerConfig["providers"][number];
487
488 /** Machine slash commands and skills a cwd snapshot reply carried, with the digest they belong to. */
489 export interface FetchedMachineCatalog {
490 readonly instanceId: ProviderInstanceId;
491 readonly digest: string;
492 readonly slashCommands: ServerProviderEntry["slashCommands"];
493 readonly skills: ServerProviderEntry["skills"];
494 }
495
496 function withFetchedMachineCatalogs(
497 projection: ServerConfigProjection,
498 catalogs: ReadonlyArray<FetchedMachineCatalog>,
499 ): ServerConfigProjection {
500 let changed = false;
501 const providers = projection.config.providers.map((provider) => {
502 const catalog = catalogs.find((entry) => entry.instanceId === provider.instanceId);
503 // Only the lists of the live catalog apply. A reply for an older one is dropped, and a
504 // reply that lands before the config names its digest applies when the config does.
505 if (
506 catalog === undefined ||
507 catalog.digest !== provider.catalogDigest ||
508 provider.loadedCatalogDigest === catalog.digest
509 ) {
510 return provider;
511 }
512 changed = true;
513 return {
514 ...provider,
515 slashCommands: catalog.slashCommands,
516 skills: catalog.skills,
517 loadedCatalogDigest: catalog.digest,
518 };
519 });
520 return changed ? { ...projection, config: { ...projection.config, providers } } : projection;
521 }
522
523 // Configs are JSON-shaped. Missing and undefined object fields persist identically.
524 function sameCacheValue(previous: unknown, next: unknown): boolean {
525 if (previous === next) return true;
526 if (
527 previous === null ||
528 next === null ||
529 typeof previous !== "object" ||
530 typeof next !== "object"
531 ) {
532 return false;
533 }
534 if (Array.isArray(previous) || Array.isArray(next)) {
535 if (!Array.isArray(previous) || !Array.isArray(next) || previous.length !== next.length) {
536 return false;
537 }
538 for (let index = 0; index < previous.length; index += 1) {
539 if (!sameCacheValue(previous[index], next[index])) return false;
540 }
541 return true;
542 }
543 if (
544 Object.getPrototypeOf(previous) !== Object.prototype ||
545 Object.getPrototypeOf(next) !== Object.prototype
546 ) {
547 return false;
548 }
549 const before = previous as Record<string, unknown>;
550 const after = next as Record<string, unknown>;
551 return (
552 Object.keys(before).every((key) =>
553 sameCacheValue(before[key], Object.hasOwn(after, key) ? after[key] : undefined),
554 ) && Object.keys(after).every((key) => Object.hasOwn(before, key) || after[key] === undefined)
555 );
556 }
557
558 export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
559 function* (
560 subscription: ServerConfigSubscriptionOptions,
561 // Merged into the state, so the cache keeps the lists for the next launch and for offline.
562 machineCatalogs: Stream.Stream<ReadonlyArray<FetchedMachineCatalog>> = Stream.empty,
563 ) {
564 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
565 const cache = yield* Persistence.EnvironmentCacheStore;
566 const environmentId = supervisor.target.environmentId;
567 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
568 Effect.catch((error) =>
569 Effect.logWarning("Could not load cached server configuration.").pipe(
570 Effect.annotateLogs({
571 environmentId,
572 ...safeErrorLogAttributes(error),
573 }),
574 Effect.as(Option.none<ServerConfig>()),
575 ),
576 ),
577 );
578 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
579 Option.map(cachedConfig, (cached) => ({
580 config: withoutEnvironmentThemes(cached),
581 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
582 source: "cache" as const,
583 })),
584 );
585 const persistence = yield* Queue.sliding<ServerConfig>(1);
586 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
587 let lastPersisted: ServerConfig | undefined;
588
589 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
590 config: ServerConfig,
591 ) {
592 // A cached stall would read as a fresh freeze on the next launch, and
593 // serverTime changes every connect, which would rewrite the cache each time.
594 const {
595 environmentThemes: _themes,
596 usageLimitSources: _sources,
597 lastEventLoopStall: _stall,
598 serverTime: _serverTime,
599 ...cacheable
600 } = config;
601 if (lastPersisted !== undefined && sameCacheValue(lastPersisted, cacheable)) {
602 return true;
603 }
604 const saved = yield* cache.saveServerConfig(environmentId, cacheable).pipe(
605 Effect.as(true),
606 Effect.catch((error) =>
607 Effect.logWarning("Could not persist cached server configuration.").pipe(
608 Effect.annotateLogs({
609 environmentId,
610 ...safeErrorLogAttributes(error),
611 }),
612 Effect.as(false),
613 ),
614 ),
615 );
616 if (saved) lastPersisted = cacheable;
617 return saved;
618 });
619
620 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
621 config: ServerConfig,
622 ) {
623 if (!(yield* persist(config))) {
624 return;
625 }
626 yield* Ref.update(pendingPersistence, (pending) =>
627 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
628 );
629 });
630
631 yield* Effect.addFinalizer(() =>
632 Ref.get(pendingPersistence).pipe(
633 Effect.flatMap(
634 Option.match({
635 onNone: () => Effect.void,
636 onSome: (config) => persist(config).pipe(Effect.asVoid),
637 }),
638 ),
639 ),
640 );
641
642 yield* runCachePersistence(persistence, persistPending).pipe(Effect.forkScoped);
643
644 type Update = (
645 current: Option.Option<ServerConfigProjection>,
646 ) => Option.Option<ServerConfigProjection>;
647 // Written and read inside the one update loop below.
648 let fetchedCatalogs: ReadonlyArray<FetchedMachineCatalog> = [];
649 const configUpdates = subscribe(WS_METHODS.subscribeServerConfig, {
650 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
651 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
652 ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
653 ...(subscription.providerCatalogsOnDemand === true ? { providerCatalogsOnDemand: true } : {}),
654 ...(subscription.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}),
655 ...(subscription.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}),
656 }).pipe(
657 Stream.map((event): Update => (current) => {
658 const next = applyServerConfigProjection(current, event);
659 return fetchedCatalogs.length === 0
660 ? next
661 : Option.map(next, (projection) =>
662 withFetchedMachineCatalogs(projection, fetchedCatalogs),
663 );
664 }),
665 );
666 const catalogUpdates = machineCatalogs.pipe(
667 Stream.map((catalogs): Update => (current) => {
668 fetchedCatalogs = catalogs;
669 return Option.map(current, (projection) =>
670 withFetchedMachineCatalogs(projection, catalogs),
671 );
672 }),
673 );
674
675 // One loop for both sources, so a fetched catalog never overwrites a newer config event.
676 yield* Stream.merge(configUpdates, catalogUpdates).pipe(
677 Stream.runForEach((update) =>
678 Effect.gen(function* () {
679 const current = yield* SubscriptionRef.get(state);
680 const next = update(current);
681 if (Option.isNone(next) || next.value === Option.getOrUndefined(current)) {
682 return;
683 }
684 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
685 yield* SubscriptionRef.set(state, next);
686 yield* Queue.offer(persistence, next.value.config);
687 }),
688 ),
689 Effect.forkScoped,
690 );
691
692 return state;
693 },
694 );
695
696 function serverConfigStateChanges(
697 environmentId: EnvironmentId,
698 subscription: ServerConfigSubscriptionOptions,
699 machineCatalogs: Stream.Stream<ReadonlyArray<FetchedMachineCatalog>>,
700 ) {
701 return followStreamInEnvironment(
702 environmentId,
703 Stream.unwrap(
704 makeEnvironmentServerConfigState(subscription, machineCatalogs).pipe(
705 Effect.map((state) =>
706 SubscriptionRef.changes(state).pipe(
707 Stream.filterMap((projection) =>
708 Option.match(projection, {
709 onNone: () => Result.failVoid,
710 onSome: (value) => Result.succeed(value),
711 }),
712 ),
713 ),
714 ),
715 ),
716 ),
717 );
718 }
719
720 export function applyServerWelcomeEvent(
721 current: EnvironmentServerWelcomeState,
722 session: RpcSession,
723 event: {
724 readonly type: "welcome" | "ready" | "legacyThreadMigration";
725 readonly payload: unknown;
726 },
727 ): EnvironmentServerWelcomeState {
728 return event.type === "welcome" && current.currentSession === session
729 ? {
730 ...current,
731 welcomeSession: session,
732 welcome: event.payload as ServerLifecycleWelcomePayload,
733 }
734 : current;
735 }
736
737 export interface EnvironmentServerWelcomeState {
738 readonly currentSession: RpcSession | null;
739 readonly welcomeSession: RpcSession | null;
740 readonly welcome: ServerLifecycleWelcomePayload | null;
741 }
742
743 export function resolveServerWelcomeState(
744 state: EnvironmentServerWelcomeState,
745 ): ServerLifecycleWelcomePayload | null {
746 return state.currentSession === state.welcomeSession ? state.welcome : null;
747 }
748
749 export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")(
750 function* () {
751 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
752 const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session));
753 const state = yield* SubscriptionRef.make<EnvironmentServerWelcomeState>({
754 currentSession: initialSession,
755 welcomeSession: null,
756 welcome: null,
757 });
758
759 const updateWithCurrentSession = Effect.fn(
760 "EnvironmentServerWelcomeState.updateWithCurrentSession",
761 )(function* (
762 update: (
763 current: EnvironmentServerWelcomeState,
764 currentSession: RpcSession | null,
765 ) => EnvironmentServerWelcomeState,
766 ) {
767 return yield* SubscriptionRef.modifyEffect(state, (current) =>
768 SubscriptionRef.get(supervisor.session).pipe(
769 Effect.map(
770 (latestSession) =>
771 [undefined, update(current, Option.getOrNull(latestSession))] as const,
772 ),
773 ),
774 );
775 });
776
777 yield* SubscriptionRef.changes(supervisor.session).pipe(
778 Stream.runForEach(() =>
779 updateWithCurrentSession((current, currentSession) => ({
780 ...current,
781 currentSession,
782 })),
783 ),
784 Effect.forkScoped,
785 );
786
787 yield* subscribeDynamicWithSession(
788 WS_METHODS.subscribeServerLifecycle,
789 Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) {
790 yield* updateWithCurrentSession((current, currentSession) =>
791 currentSession === session
792 ? {
793 ...current,
794 currentSession,
795 welcomeSession: session,
796 welcome: null,
797 }
798 : { ...current, currentSession },
799 );
800 return {};
801 }),
802 ).pipe(
803 Stream.runForEach(([session, event]) =>
804 updateWithCurrentSession((current, currentSession) =>
805 applyServerWelcomeEvent(
806 {
807 ...current,
808 currentSession,
809 },
810 session,
811 event,
812 ),
813 ),
814 ),
815 Effect.forkScoped,
816 );
817
818 return state;
819 },
820 );
821
822 function serverWelcomeStateChanges(environmentId: EnvironmentId) {
823 return followStreamInEnvironment(
824 environmentId,
825 Stream.unwrap(
826 makeEnvironmentServerWelcomeState().pipe(
827 Effect.map((state) =>
828 SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)),
829 ),
830 ),
831 ),
832 );
833 }
834
835 export function resolveServerConfigValue(
836 projection: ServerConfigProjection | null,
837 initialConfig: ServerConfig | null,
838 ): ServerConfig | null {
839 if (
840 projection?.source === "live" &&
841 (initialConfig === null ||
842 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
843 ) {
844 return projection.config;
845 }
846 return initialConfig ?? projection?.config ?? null;
847 }
848
849 /**
850 * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, a
851 * /usage-limits change, or a server rescan that changed the skills shows up here, so a snapshot
852 * fetched before it no longer applies.
853 */
854 const snapshotBasis = (provider: ServerProviderEntry | undefined) =>
855 provider && {
856 enabled: provider.enabled,
857 models: provider.models,
858 // The digest stands for the lists, which load with a snapshot and must not unseat it.
859 ...(provider.catalogDigest === undefined
860 ? { slashCommands: provider.slashCommands, skills: provider.skills }
861 : { catalogDigest: provider.catalogDigest }),
862 ...(provider.workspaceRescannedAt === undefined
863 ? {}
864 : { workspaceRescannedAt: provider.workspaceRescannedAt }),
865 };
866
867 interface FetchedWorkspaceSnapshot {
868 readonly instanceId: ProviderInstanceId;
869 readonly snapshot: ServerProviderWorkspaceSnapshot;
870 readonly basis: ReturnType<typeof snapshotBasis>;
871 }
872
873 const MAX_FETCHED_WORKSPACE_SNAPSHOTS = 32;
874
875 /**
876 * Servers with `providerWorkspaceSnapshotsOnDemand` leave per-cwd snapshots out of the config,
877 * so the ones this client fetched are merged back in. Older servers send every snapshot and
878 * their drops, so their config is used as is.
879 */
880 export function withFetchedWorkspaceSnapshots(
881 config: ServerConfig,
882 fetched: ReadonlyArray<FetchedWorkspaceSnapshot>,
883 ): ServerConfig {
884 if (
885 fetched.length === 0 ||
886 config.environment.capabilities.providerWorkspaceSnapshotsOnDemand !== true
887 ) {
888 return config;
889 }
890 return {
891 ...config,
892 providers: config.providers.map((provider) => {
893 // A dropped snapshot reads as lost, and the composer fetches it again.
894 const own = fetched.filter(
895 (entry) =>
896 entry.instanceId === provider.instanceId &&
897 Equal.equals(entry.basis, snapshotBasis(provider)),
898 );
899 return own.length === 0
900 ? provider
901 : { ...provider, workspaceSnapshots: own.map((entry) => entry.snapshot) };
902 }),
903 };
904 }
905
906 export function recordFetchedWorkspaceSnapshot(
907 current: ReadonlyArray<FetchedWorkspaceSnapshot>,
908 input: { readonly instanceId: ProviderInstanceId; readonly cwd: string; readonly fresh: boolean },
909 providers: ServerConfig["providers"],
910 configProvider: ServerProviderEntry | undefined,
911 ): ReadonlyArray<FetchedWorkspaceSnapshot> {
912 const basis = snapshotBasis(configProvider);
913 const snapshot = providers
914 .find((provider) => provider.instanceId === input.instanceId)
915 ?.workspaceSnapshots?.find((candidate) => candidate.cwd === input.cwd);
916 const stored = current.find(
917 (entry) => entry.instanceId === input.instanceId && entry.snapshot.cwd === input.cwd,
918 );
919 // A cached answer from the server would otherwise re-render every config reader.
920 if (
921 !input.fresh &&
922 snapshot &&
923 stored &&
924 Equal.equals(stored.snapshot, snapshot) &&
925 Equal.equals(stored.basis, basis)
926 ) {
927 return current;
928 }
929 // A fresh scan drops the cwd's snapshots for every provider, as the server does.
930 const kept = current.filter(
931 (entry) =>
932 entry.snapshot.cwd !== input.cwd || (!input.fresh && entry.instanceId !== input.instanceId),
933 );
934 if (!snapshot) return kept.length === current.length ? current : kept;
935 return [...kept, { instanceId: input.instanceId, snapshot, basis }].slice(
936 -MAX_FETCHED_WORKSPACE_SNAPSHOTS,
937 );
938 }
939
940 export function createServerEnvironmentAtoms<R, E>(
941 runtime: Atom.AtomRuntime<
942 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
943 E
944 >,
945 options: {
946 readonly initialConfigValueAtom: (
947 environmentId: EnvironmentId,
948 ) => Atom.Atom<ServerConfig | null>;
949 readonly environmentThemes?: boolean;
950 readonly usageLimitSources?: boolean;
951 readonly usageLimitsCommand?: boolean;
952 readonly providerCatalogsOnDemand?: boolean;
953 readonly providerCatalogDigests?: boolean;
954 readonly providerStatusDeltas?: boolean;
955 /** Machine refresh replies carry no providers; the config stream already delivers them. */
956 readonly omitRefreshedProviders?: boolean;
957 },
958 ) {
959 const configScheduler = createAtomCommandScheduler();
960 const updateScheduler = createAtomCommandScheduler();
961 const configConcurrency = {
962 mode: "serial" as const,
963 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
964 };
965 const fetchedMachineCatalogsAtom = Atom.family((environmentId: EnvironmentId) =>
966 Atom.make<ReadonlyArray<FetchedMachineCatalog>>([]).pipe(
967 Atom.keepAlive,
968 Atom.withLabel(`environment-data:server:fetched-machine-catalogs:${environmentId}`),
969 ),
970 );
971 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
972 runtime
973 .atom((get) =>
974 serverConfigStateChanges(
975 environmentId,
976 {
977 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
978 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
979 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
980 ...(options.providerCatalogsOnDemand === true
981 ? { providerCatalogsOnDemand: true }
982 : {}),
983 ...(options.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}),
984 ...(options.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}),
985 },
986 // Scoped to the stream, which restarts with every new session.
987 AtomRegistry.toStream(get.registry, fetchedMachineCatalogsAtom(environmentId)),
988 ),
989 )
990 .pipe(
991 Atom.setIdleTTL(5 * 60_000),
992 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
993 ),
994 );
995 const configProjection = (target: {
996 readonly environmentId: EnvironmentId;
997 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
998 }) => configProjectionFamily(target.environmentId);
999 const fetchedWorkspaceSnapshotsAtom = Atom.family((environmentId: EnvironmentId) =>
1000 Atom.make<ReadonlyArray<FetchedWorkspaceSnapshot>>([]).pipe(
1001 Atom.keepAlive,
1002 Atom.withLabel(`environment-data:server:fetched-workspace-snapshots:${environmentId}`),
1003 ),
1004 );
1005 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
1006 Atom.withLabel("environment-data:server:config:empty"),
1007 );
1008 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
1009 if (environmentId === null) {
1010 return emptyConfigAtom;
1011 }
1012 let previousProviders: ServerConfig["providers"] | undefined;
1013 return Atom.make((get): ServerConfig | null => {
1014 const projection = AsyncResult.getOrElse(
1015 get(configProjection({ environmentId, input: {} })),
1016 () => null,
1017 );
1018 const config = resolveServerConfigValue(
1019 projection,
1020 get(options.initialConfigValueAtom(environmentId)),
1021 );
1022 if (config === null) return null;
1023 const merged = withFetchedWorkspaceSnapshots(
1024 config,
1025 get(fetchedWorkspaceSnapshotsAtom(environmentId)),
1026 );
1027 if (merged === config) return config;
1028 // Keep provider identities stable across config events; the projection already reuses the rest.
1029 previousProviders = reuseUnchanged(previousProviders, merged.providers);
1030 return { ...merged, providers: previousProviders };
1031 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
1032 });
1033 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
1034 Atom.make((get) =>
1035 serverUpdateStateForServerVersion(
1036 get(serverUpdateStateAtom(environmentId)),
1037 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
1038 ),
1039 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
1040 );
1041 const updateStateAtom = (environmentId: EnvironmentId | null) =>
1042 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
1043 const updateServer = createRuntimeCommand<
1044 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore | R,
1045 E,
1046 ServerUpdateTarget,
1047 ServerSelfUpdateResult,
1048 unknown
1049 >(runtime, {
1050 label: "environment-data:server:update-server",
1051 scheduler: updateScheduler,
1052 concurrency: configConcurrency,
1053 execute: Effect.fn("ServerUpdate.updateServer")(function (target, atomRegistry) {
1054 const stateAtom = serverUpdateStateAtom(target.environmentId);
1055 let targetVersion = target.input.targetVersion;
1056 let fromVersion =
1057 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
1058 targetVersion;
1059 let currentStage: ServerUpdateStage = "downloading";
1060 let desktopCommitLostTransport = false;
1061 atomRegistry.set(stateAtom, {
1062 status: "running",
1063 stage: currentStage,
1064 fromVersion,
1065 targetVersion,
1066 });
1067
1068 return Effect.gen(function* () {
1069 const environmentRegistry = yield* EnvironmentRegistry.EnvironmentRegistry;
1070 const desktopCommitStarting = yield* Deferred.make<void>();
1071 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
1072 const desktopReconnected = yield* Deferred.make<void>();
1073 let accepting: { readonly session: RpcSession; readonly at: string } | undefined;
1074 let acceptedAt: string | undefined;
1075 // The baseline only describes the accepting process if the request rides its session,
1076 // so the session read here is the one the request is sent on.
1077 const acceptingSession = currentSession().pipe(
1078 Effect.tap((session) =>
1079 Effect.sync(() => {
1080 acceptedAt = accepting?.session === session ? accepting.at : undefined;
1081 }),
1082 ),
1083 );
1084 yield* Deferred.await(desktopCommitStarting).pipe(
1085 Effect.andThen(
1086 environmentRegistry.stateChanges(target.environmentId).pipe(
1087 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
1088 Stream.dropWhile((state) => state.phase === "connected"),
1089 Stream.filter((state) => state.phase === "connected"),
1090 Stream.runHead,
1091 ),
1092 ),
1093 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
1094 Effect.forkChild,
1095 );
1096 const result = yield* configScheduler.schedule(
1097 atomRegistry,
1098 configConcurrency,
1099 target,
1100 Effect.gen(function* () {
1101 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
1102 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
1103 atomRegistry.set(stateAtom, {
1104 status: "running",
1105 stage: currentStage,
1106 fromVersion,
1107 targetVersion,
1108 });
1109 // Only launcher updates carry an updateId. Read before the request so a ready from
1110 // after it can never pose as the accepting process.
1111 if (currentConfig?.environment.capabilities.serverSelfUpdate === "boot-service") {
1112 accepting = yield* environmentRegistry
1113 .followStream(
1114 target.environmentId,
1115 subscribeDynamicWithSession(WS_METHODS.subscribeServerLifecycle, () =>
1116 Effect.succeed({}),
1117 ),
1118 )
1119 .pipe(
1120 Stream.filter(
1121 (entry): entry is readonly [RpcSession, ServerLifecycleStreamReadyEvent] =>
1122 entry[1].type === "ready",
1123 ),
1124 Stream.map(([session, ready]) => ({ session, at: ready.payload.at })),
1125 Stream.runHead,
1126 Effect.timeoutOption(SERVER_UPDATE_ACCEPTING_READY_TIMEOUT),
1127 Effect.map((head) => Option.getOrUndefined(Option.flatten(head))),
1128 Effect.orElseSucceed(() => undefined),
1129 );
1130 }
1131
1132 const supportsProgress =
1133 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
1134 const updateResult: ServerSelfUpdateResult = supportsProgress
1135 ? yield* Effect.gen(function* () {
1136 let receivedProgress = false;
1137 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
1138 Option.none(),
1139 );
1140 const streamExit = yield* environmentRegistry
1141 .runStream(
1142 target.environmentId,
1143 Stream.unwrap(
1144 acceptingSession.pipe(
1145 Effect.map((session) =>
1146 runStreamInSession(
1147 session,
1148 WS_METHODS.serverUpdateServerWithProgress,
1149 target.input,
1150 ),
1151 ),
1152 ),
1153 ),
1154 )
1155 .pipe(
1156 Stream.runForEach((event) =>
1157 Effect.sync(() => {
1158 receivedProgress ||= event.type === "progress";
1159 const state = serverUpdateStateForProgressEvent(
1160 fromVersion,
1161 targetVersion,
1162 event,
1163 );
1164 currentStage = state.stage;
1165 atomRegistry.set(stateAtom, state);
1166 }).pipe(
1167 Effect.andThen(
1168 event.type === "complete"
1169 ? Ref.set(terminal, Option.some(event.result))
1170 : Effect.void,
1171 ),
1172 ),
1173 ),
1174 Effect.exit,
1175 );
1176 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
1177 // Desktop preparation needs its terminal commit token.
1178 const accepted =
1179 receivedProgress &&
1180 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn")
1181 ? { targetVersion, method: selfUpdateMethod }
1182 : undefined;
1183 return yield* resolveServerUpdateProgressResult(
1184 targetVersion,
1185 yield* Ref.get(terminal),
1186 streamExit,
1187 accepted,
1188 );
1189 })
1190 : yield* Effect.gen(function* () {
1191 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
1192 const exit = yield* environmentRegistry
1193 .run(
1194 target.environmentId,
1195 acceptingSession.pipe(
1196 Effect.flatMap((session) =>
1197 requestInSession(session, WS_METHODS.serverUpdateServer, target.input),
1198 ),
1199 ),
1200 )
1201 .pipe(Effect.exit);
1202 if (Exit.isSuccess(exit)) {
1203 return exit.value;
1204 }
1205 if (
1206 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
1207 isLegacyUpdateHandoffLoss(exit.cause)
1208 ) {
1209 // Older servers can tear down the transport before their
1210 // unary acknowledgement arrives. Treat only that transport
1211 // loss as a handoff, then prove it by waiting for target ready.
1212 return { targetVersion, method: selfUpdateMethod };
1213 }
1214 return yield* Effect.failCause(exit.cause);
1215 });
1216
1217 if (
1218 updateResult.method === "desktop-app" &&
1219 updateResult.desktopUpdateToken !== undefined
1220 ) {
1221 yield* Deferred.succeed(desktopCommitStarting, undefined);
1222 yield* Deferred.await(desktopReconnectObserverArmed);
1223 const commitExit = yield* environmentRegistry
1224 .run(
1225 target.environmentId,
1226 request(WS_METHODS.serverCommitDesktopUpdate, {
1227 requestId: updateResult.desktopUpdateToken,
1228 }),
1229 )
1230 .pipe(Effect.exit);
1231 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
1232 return yield* Effect.failCause(commitExit.cause);
1233 }
1234 desktopCommitLostTransport = Exit.isFailure(commitExit);
1235 }
1236
1237 targetVersion = updateResult.targetVersion;
1238
1239 currentStage = "resuming";
1240 atomRegistry.set(stateAtom, {
1241 status: "running",
1242 stage: currentStage,
1243 fromVersion,
1244 targetVersion,
1245 });
1246 return updateResult;
1247 }).pipe(Effect.mapError(localizeServerSelfUpdateError)),
1248 );
1249
1250 // A track switch's desktop host already on its track's newest build only saved the
1251 // track; nothing restarts.
1252 if (
1253 result.method === "desktop-app" &&
1254 result.desktopUpdateToken === undefined &&
1255 result.targetVersion === fromVersion
1256 ) {
1257 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
1258 return result;
1259 }
1260
1261 yield* nudgeReconnectDuringUpdateRestart({
1262 stateChanges: environmentRegistry.stateChanges(target.environmentId),
1263 retryNow: environmentRegistry.retryNow(target.environmentId),
1264 }).pipe(Effect.forkChild);
1265
1266 if (result.method === "desktop-app" && desktopCommitLostTransport) {
1267 yield* Deferred.await(desktopReconnected).pipe(
1268 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
1269 );
1270 }
1271
1272 const waitForReady = environmentRegistry
1273 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
1274 .pipe(
1275 Stream.filter(
1276 (event): event is ServerLifecycleStreamReadyEvent =>
1277 event.type === "ready" && matchesServerUpdateResumeEvent(result, event, acceptedAt),
1278 ),
1279 Stream.runHead,
1280 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
1281 Effect.map(Option.flatten),
1282 );
1283 const nextReady = waitForReady.pipe(
1284 Effect.flatMap(
1285 Option.match({
1286 onNone: () =>
1287 new ServerUpdateResumeTimeoutError({
1288 environmentId: target.environmentId,
1289 targetVersion,
1290 }),
1291 onSome: Effect.succeed,
1292 }),
1293 ),
1294 );
1295 const desktopUpdateToken = result.desktopUpdateToken;
1296 const resumed =
1297 result.method === "desktop-app" && desktopUpdateToken !== undefined
1298 ? yield* waitForDesktopUpdateTarget(
1299 result.targetVersion,
1300 nextReady,
1301 runDesktopCommitWithReconnectObserver(
1302 environmentRegistry.stateChanges(target.environmentId),
1303 environmentRegistry
1304 .run(
1305 target.environmentId,
1306 request(WS_METHODS.serverCommitDesktopUpdate, {
1307 requestId: desktopUpdateToken,
1308 }),
1309 )
1310 .pipe(Effect.asVoid),
1311 ),
1312 )
1313 : yield* nextReady;
1314 yield* validateServerUpdateReadyEvent(result, resumed);
1315
1316 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
1317 return result;
1318 }).pipe(
1319 Effect.onExit((exit) =>
1320 Effect.sync(() => {
1321 if (Exit.isSuccess(exit)) {
1322 return;
1323 }
1324 if (Cause.hasInterruptsOnly(exit.cause)) {
1325 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
1326 return;
1327 }
1328 atomRegistry.set(stateAtom, {
1329 status: "failed",
1330 stage: currentStage,
1331 fromVersion,
1332 targetVersion,
1333 ...serverUpdateFailure(Cause.squash(exit.cause)),
1334 });
1335 }),
1336 ),
1337 );
1338 }),
1339 });
1340 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
1341 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
1342 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
1343 ),
1344 );
1345 const hiddenThreadTagsAtom = Atom.family((environmentId: EnvironmentId) =>
1346 Atom.make((get) => {
1347 const settings = get(settingsValueAtom(environmentId));
1348 if (settings?.hideTaggedThreads !== true) return null;
1349 // Tags are trimmed on write; trim hand-edited entries so " private" still matches.
1350 const tags = settings.hiddenThreadTags.map((tag) => tag.trim()).filter((tag) => tag !== "");
1351 return tags.length > 0 ? tags : null;
1352 }).pipe(
1353 // Trimming makes a new array on every settings push; keep equal lists stable.
1354 Atom.withEquality(
1355 (a: ReadonlyArray<string> | null, b: ReadonlyArray<string> | null) =>
1356 a === b ||
1357 (a !== null &&
1358 b !== null &&
1359 a.length === b.length &&
1360 a.every((tag, index) => tag === b[index])),
1361 ),
1362 Atom.withLabel(`environment-data:server:hidden-thread-tags:${environmentId}`),
1363 ),
1364 );
1365 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
1366 Atom.make((get) => {
1367 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
1368 // Only changed prices should trigger another transcript scan. Settings
1369 // snapshots can recreate the same mapping in a different property order.
1370 return JSON.stringify(
1371 Object.keys(overrides)
1372 .sort()
1373 .map((model) => {
1374 const price = overrides[model]!;
1375 return [
1376 model,
1377 price.inputCostPerMillionTokens,
1378 price.outputCostPerMillionTokens,
1379 price.cacheReadCostPerMillionTokens,
1380 price.cacheWriteCostPerMillionTokens,
1381 ];
1382 }),
1383 );
1384 }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
1385 );
1386 const usageScanSettingsAtom = Atom.family((environmentId: EnvironmentId) =>
1387 Atom.make((get) => {
1388 const settings = get(settingsValueAtom(environmentId));
1389 const aliases = settings?.usageModelAliases ?? {};
1390 return JSON.stringify([
1391 get(usagePricesAtom(environmentId)),
1392 Object.keys(aliases)
1393 .sort()
1394 .map((model) => [model, aliases[model]]),
1395 ]);
1396 }).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)),
1397 );
1398 // Settings snapshots rebuild the filter object; only a changed filter should touch the Usage tab.
1399 const usageModelFilterAtom = Atom.family((environmentId: EnvironmentId) =>
1400 Atom.make((get) => get(settingsValueAtom(environmentId))?.usageModelFilter).pipe(
1401 Atom.withEquality((a, b) => JSON.stringify(a) === JSON.stringify(b)),
1402 Atom.withLabel(`environment-data:server:usage-model-filter:${environmentId}`),
1403 ),
1404 );
1405 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
1406 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
1407 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
1408 ),
1409 );
1410 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
1411 runtime
1412 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
1413 .pipe(
1414 Atom.setIdleTTL(5 * 60_000),
1415 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
1416 ),
1417 );
1418 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
1419 Atom.make((get) => {
1420 const result = get(welcomeStateFamily(environmentId));
1421 if (result._tag !== "Success") return result;
1422 return result.value === null
1423 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
1424 : AsyncResult.success(result.value, result);
1425 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
1426 );
1427 const databaseStorage = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1428 label: "environment-data:server:database-storage",
1429 tag: WS_METHODS.serverGetDatabaseStorage,
1430 idleTtlMs: 0,
1431 });
1432 // Keyed by a JSON array of environment ids so one notice can list every machine.
1433 const databaseCompactionRecommendations = Atom.family((environmentIdsKey: string) => {
1434 const sources = (JSON.parse(environmentIdsKey) as EnvironmentId[]).map((environmentId) => ({
1435 environmentId,
1436 atom: databaseStorage({ environmentId, input: {} }),
1437 }));
1438 return Atom.make((get) =>
1439 sources
1440 .flatMap(({ environmentId, atom }) => {
1441 const result = get(atom);
1442 return result._tag === "Success" &&
1443 result.value !== null &&
1444 shouldRecommendDatabaseCompaction(result.value)
1445 ? [{ environmentId, status: result.value }]
1446 : [];
1447 })
1448 .sort((left, right) => right.status.reclaimableBytes - left.status.reclaimableBytes),
1449 ).pipe(
1450 Atom.withLabel(
1451 `environment-data:server:database-compaction-recommendations:${environmentIdsKey}`,
1452 ),
1453 );
1454 });
1455 const welcome = (target: {
1456 readonly environmentId: EnvironmentId;
1457 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
1458 }) => welcomeFamily(target.environmentId);
1459 const updateSettings = createEnvironmentRpcCommand(runtime, {
1460 label: "environment-data:server:update-settings",
1461 tag: WS_METHODS.serverUpdateSettings,
1462 scheduler: configScheduler,
1463 concurrency: configConcurrency,
1464 });
1465
1466 return {
1467 configValueAtom,
1468 runStorageCleanup: createEnvironmentRpcCommand(runtime, {
1469 label: "environment-data:server:run-storage-cleanup",
1470 tag: WS_METHODS.serverRunStorageCleanup,
1471 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1472 }),
1473 prepareTriage: createEnvironmentRpcCommand(runtime, {
1474 label: "environment-data:server:prepare-triage",
1475 tag: WS_METHODS.serverPrepareTriage,
1476 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1477 }),
1478 databaseStorage,
1479 databaseCompactionRecommendations,
1480 reclaimDatabaseSpace: createEnvironmentRpcCommand(runtime, {
1481 label: "environment-data:server:reclaim-database-space",
1482 tag: WS_METHODS.serverReclaimDatabaseSpace,
1483 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1484 }),
1485 storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1486 label: "environment-data:server:storage-cleanup-report",
1487 tag: WS_METHODS.serverGetStorageCleanupReport,
1488 idleTtlMs: 0,
1489 }),
1490 updateStateAtom,
1491 settingsValueAtom,
1492 hiddenThreadTagsAtom,
1493 usageModelFilterAtom,
1494 providersValueAtom,
1495 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1496 label: "environment-data:provider:auth-state",
1497 tag: WS_METHODS.providerAuthSubscribe,
1498 idleTtlMs: 0,
1499 }),
1500 startProviderAuth: createEnvironmentRpcCommand(runtime, {
1501 label: "environment-data:provider:auth-start",
1502 tag: WS_METHODS.providerAuthStart,
1503 concurrency: {
1504 mode: "singleFlight",
1505 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1506 },
1507 }),
1508 respondProviderAuth: createEnvironmentRpcCommand(runtime, {
1509 label: "environment-data:provider:auth-respond",
1510 tag: WS_METHODS.providerAuthRespond,
1511 }),
1512 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
1513 label: "environment-data:provider:auth-complete",
1514 tag: WS_METHODS.providerAuthComplete,
1515 }),
1516 chatGptReconnectProfile: createEnvironmentRpcCommand(runtime, {
1517 label: "environment-data:chatgpt:reconnect-profile",
1518 tag: WS_METHODS.chatGptReconnectProfile,
1519 }),
1520 chatGptImportProfile: createEnvironmentRpcCommand(runtime, {
1521 label: "environment-data:chatgpt:import-profile",
1522 tag: WS_METHODS.chatGptImportProfile,
1523 }),
1524 chatGptHandoffState: createEnvironmentSubscriptionAtomFamily(runtime, {
1525 label: "environment-data:chatgpt:handoff",
1526 sensitiveInput: true,
1527 // OAuth must not be replayed when the connection recovers.
1528 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.chatGptHandoffSubscribe>) =>
1529 runStream(WS_METHODS.chatGptHandoffSubscribe, input),
1530 idleTtlMs: 0,
1531 }),
1532 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
1533 label: "environment-data:provider:auth-cancel",
1534 tag: WS_METHODS.providerAuthCancel,
1535 }),
1536 removeProviderAuthMethod: createEnvironmentRpcCommand(runtime, {
1537 label: "environment-data:provider:auth-remove-method",
1538 tag: WS_METHODS.providerAuthRemoveMethod,
1539 }),
1540 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
1541 label: "environment-data:provider:auth-logout",
1542 tag: WS_METHODS.providerAuthLogout,
1543 }),
1544 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1545 label: "environment-data:provider:install-state",
1546 tag: WS_METHODS.providerInstallSubscribe,
1547 idleTtlMs: 0,
1548 }),
1549 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1550 label: "environment-data:provider:install-start",
1551 tag: WS_METHODS.providerInstallStart,
1552 concurrency: {
1553 mode: "singleFlight",
1554 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1555 },
1556 }),
1557 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1558 label: "environment-data:provider:install-cancel",
1559 tag: WS_METHODS.providerInstallCancel,
1560 }),
1561 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1562 label: "environment-data:provider:install-remove",
1563 tag: WS_METHODS.providerInstallRemove,
1564 }),
1565 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1566 label: "environment-data:server:trace-diagnostics",
1567 tag: WS_METHODS.serverGetTraceDiagnostics,
1568 }),
1569 npmRelease: createEnvironmentRpcQueryAtomFamily(runtime, {
1570 label: "environment-data:server:npm-release",
1571 tag: WS_METHODS.serverGetNpmRelease,
1572 staleTimeMs: 60_000,
1573 refreshIntervalMs: 5 * 60_000,
1574 }),
1575 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1576 label: "environment-data:server:process-diagnostics",
1577 tag: WS_METHODS.serverGetProcessDiagnostics,
1578 }),
1579 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1580 label: "environment-data:server:host-resources",
1581 idleTtlMs: 0,
1582 staleTimeMs: 5_000,
1583 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1584 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1585 }),
1586 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1587 label: "environment-data:server:process-resource-history",
1588 tag: WS_METHODS.serverGetProcessResourceHistory,
1589 staleTimeMs: 5_000,
1590 refreshIntervalMs: 5_000,
1591 idleTtlMs: 0,
1592 }),
1593 scheduledTaskWebhookDeliveries: createEnvironmentRpcQueryAtomFamily(runtime, {
1594 label: "environment-data:server:scheduled-task:webhook-deliveries",
1595 tag: WS_METHODS.scheduledTasksListWebhookDeliveries,
1596 }),
1597 scheduledTaskWebhookDelivery: createEnvironmentRpcQueryAtomFamily(runtime, {
1598 label: "environment-data:server:scheduled-task:webhook-delivery",
1599 tag: WS_METHODS.scheduledTasksGetWebhookDelivery,
1600 }),
1601 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1602 label: "environment-data:server:scheduled-tasks:live",
1603 tag: WS_METHODS.scheduledTasksSubscribe,
1604 }),
1605 // A cold transcript scan is measured in seconds, so keep the result around
1606 // long enough that switching windows or re-rendering does not rescan. With
1607 // nothing to show yet, the server's last scan answers first, then a plain
1608 // read, then a read that waits for slow sources.
1609 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1610 label: "environment-data:server:usage-summary",
1611 tag: WS_METHODS.serverGetUsageSummary,
1612 staleTimeMs: 60_000,
1613 refreshTrigger: ({ environmentId }) => usageScanSettingsAtom(environmentId),
1614 execute: (input, emit, previous) => {
1615 const settled = (summary: UsageSummary) =>
1616 !summary.sources.some((source) => source.refreshing === true);
1617 const read = request(WS_METHODS.serverGetUsageSummary, input).pipe(
1618 Effect.filterOrElse(settled, (summary) =>
1619 emit(summary).pipe(
1620 Effect.andThen(
1621 request(WS_METHODS.serverGetUsageSummary, { ...input, awaitRefresh: true }),
1622 ),
1623 Effect.catch((error) =>
1624 Effect.logWarning("Could not refresh slow usage sources.").pipe(
1625 Effect.annotateLogs({ ...safeErrorLogAttributes(error) }),
1626 Effect.as(summary),
1627 ),
1628 ),
1629 ),
1630 ),
1631 );
1632 if (Option.isSome(previous)) return read;
1633 return request(WS_METHODS.serverGetUsageSummary, { ...input, provisional: true }).pipe(
1634 Effect.matchEffect({
1635 // The saved answer only speeds things up; without it the plain read still answers.
1636 onFailure: () => read,
1637 onSuccess: (saved) =>
1638 settled(saved) ? Effect.succeed(saved) : emit(saved).pipe(Effect.andThen(read)),
1639 }),
1640 );
1641 },
1642 }),
1643 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1644 label: "environment-data:server:resource-telemetry",
1645 tag: WS_METHODS.subscribeResourceTelemetry,
1646 idleTtlMs: 0,
1647 }),
1648 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1649 label: "environment-data:server:resource-telemetry-history",
1650 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1651 staleTimeMs: 5_000,
1652 refreshIntervalMs: 5_000,
1653 idleTtlMs: 0,
1654 }),
1655 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1656 label: "environment-data:server:acp-registry:search",
1657 tag: WS_METHODS.serverSearchAcpRegistry,
1658 // Reopening Add provider reuses recent results. Submitting the same search asks the
1659 // server again, which reuses a Registry index fetched in the last five minutes.
1660 staleTimeMs: 5 * 60_000,
1661 }),
1662 configProjection,
1663 welcome,
1664 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1665 label: "environment-data:server:legacy-thread-migration",
1666 tag: WS_METHODS.subscribeServerLifecycle,
1667 transform: (stream) =>
1668 stream.pipe(
1669 Stream.filterMap((event) =>
1670 event.type === "legacyThreadMigration"
1671 ? Result.succeed(event.payload)
1672 : Result.failVoid,
1673 ),
1674 ),
1675 }),
1676 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1677 label: "environment-data:server:consume-reset-credit",
1678 tag: WS_METHODS.providerConsumeResetCredit,
1679 concurrency: {
1680 mode: "singleFlight",
1681 // Both ids are free-form strings; a delimiter could collide.
1682 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1683 },
1684 }),
1685 refreshProviders: createEnvironmentRpcCommand(runtime, {
1686 label: "environment-data:server:refresh-providers",
1687 tag: WS_METHODS.serverRefreshProviders,
1688 // A rescan during the request must leave the stored basis behind the new stamp.
1689 onStart: ({ environmentId, input }, registry) =>
1690 registry
1691 .get(configValueAtom(environmentId))
1692 ?.providers.find((provider) => provider.instanceId === input.instanceId),
1693 execute: (input, registry, environmentId) => {
1694 const { instanceId, cwd } = input;
1695 const provider =
1696 instanceId === undefined || cwd === undefined
1697 ? undefined
1698 : registry
1699 .get(configValueAtom(environmentId))
1700 ?.providers.find((candidate) => candidate.instanceId === instanceId);
1701 return requestGuarded(WS_METHODS.serverRefreshProviders, {
1702 ...input,
1703 workspaceSnapshotsOnDemand: true,
1704 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
1705 ...(options.providerCatalogsOnDemand === true ? { providerCatalogsOnDemand: true } : {}),
1706 ...(options.omitRefreshedProviders === true ? { omitProviders: true } : {}),
1707 // The held lists are stale or missing, so the cwd snapshot brings the current ones.
1708 ...(provider?.catalogDigest !== undefined &&
1709 provider.loadedCatalogDigest !== provider.catalogDigest
1710 ? { machineCatalog: true }
1711 : {}),
1712 });
1713 },
1714 onSuccess: ({ environmentId, input }, registry, result, startedProvider) =>
1715 Effect.sync(() => {
1716 const { instanceId, cwd } = input;
1717 if (instanceId === undefined || cwd === undefined) return;
1718 const refreshed = result.providers.find((provider) => provider.instanceId === instanceId);
1719 if (refreshed?.catalogDigest !== undefined) {
1720 const catalog = {
1721 instanceId,
1722 digest: refreshed.catalogDigest,
1723 slashCommands: refreshed.slashCommands,
1724 skills: refreshed.skills,
1725 };
1726 registry.update(fetchedMachineCatalogsAtom(environmentId), (current) => [
1727 ...current.filter((entry) => entry.instanceId !== instanceId),
1728 catalog,
1729 ]);
1730 }
1731 registry.update(fetchedWorkspaceSnapshotsAtom(environmentId), (current) =>
1732 recordFetchedWorkspaceSnapshot(
1733 current,
1734 { instanceId, cwd, fresh: input.fresh === true },
1735 result.providers,
1736 startedProvider,
1737 ),
1738 );
1739 }),
1740 concurrency: {
1741 mode: "singleFlight",
1742 key: ({ environmentId, input }) =>
1743 JSON.stringify([
1744 environmentId,
1745 input.instanceId ?? null,
1746 input.cwd ?? null,
1747 input.fresh ?? false,
1748 input.refreshModels ?? false,
1749 input.modelCatalogOnly ?? false,
1750 ]),
1751 },
1752 }),
1753 updateProvider: createEnvironmentRpcCommand(runtime, {
1754 label: "environment-data:server:update-provider",
1755 tag: WS_METHODS.serverUpdateProvider,
1756 }),
1757 updateServer,
1758 stageServerUpdate: createEnvironmentRpcCommand(runtime, {
1759 label: "environment-data:server:stage-update",
1760 tag: WS_METHODS.serverUpdateServer,
1761 }),
1762 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1763 label: "environment-data:server:upsert-keybinding",
1764 tag: WS_METHODS.serverUpsertKeybinding,
1765 scheduler: configScheduler,
1766 concurrency: configConcurrency,
1767 }),
1768 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1769 label: "environment-data:server:remove-keybinding",
1770 tag: WS_METHODS.serverRemoveKeybinding,
1771 scheduler: configScheduler,
1772 concurrency: configConcurrency,
1773 }),
1774 updateSettings,
1775 mutateProviderInstance: updateSettings,
1776 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1777 label: "environment-data:server:acp-registry:prepare",
1778 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1779 concurrency: {
1780 mode: "singleFlight",
1781 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1782 },
1783 }),
1784 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1785 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1786 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1787 concurrency: {
1788 mode: "singleFlight",
1789 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1790 },
1791 }),
1792 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1793 label: "environment-data:server:acp-registry:accept-url-auth",
1794 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1795 concurrency: {
1796 mode: "singleFlight",
1797 key: ({ environmentId, input }) =>
1798 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1799 },
1800 }),
1801 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1802 label: "environment-data:server:acp-registry:list-sessions",
1803 tag: WS_METHODS.serverListAcpRegistrySessions,
1804 concurrency: {
1805 mode: "singleFlight",
1806 key: ({ environmentId, input }) =>
1807 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1808 },
1809 }),
1810 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1811 label: "environment-data:server:acp-registry:import-session",
1812 tag: WS_METHODS.serverImportAcpRegistrySession,
1813 concurrency: {
1814 mode: "singleFlight",
1815 key: ({ environmentId, input }) =>
1816 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1817 },
1818 }),
1819 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1820 label: "environment-data:server:acp-registry:delete-session",
1821 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1822 concurrency: {
1823 mode: "singleFlight",
1824 key: ({ environmentId, input }) =>
1825 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1826 },
1827 }),
1828 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1829 label: "environment-data:server:acp-registry:list-providers",
1830 tag: WS_METHODS.serverListAcpRegistryProviders,
1831 concurrency: {
1832 mode: "singleFlight",
1833 key: ({ environmentId, input }) =>
1834 `${environmentId}:${input.instanceId}:${input.projectId}`,
1835 },
1836 }),
1837 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1838 label: "environment-data:server:acp-registry:set-provider",
1839 tag: WS_METHODS.serverSetAcpRegistryProvider,
1840 concurrency: {
1841 mode: "singleFlight",
1842 key: ({ environmentId, input }) =>
1843 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1844 },
1845 }),
1846 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1847 label: "environment-data:server:acp-registry:disable-provider",
1848 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1849 concurrency: {
1850 mode: "singleFlight",
1851 key: ({ environmentId, input }) =>
1852 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1853 },
1854 }),
1855 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1856 label: "environment-data:server:acp-registry:logout",
1857 tag: WS_METHODS.serverLogoutAcpRegistry,
1858 concurrency: {
1859 mode: "singleFlight",
1860 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1861 },
1862 }),
1863 signalProcess: createEnvironmentRpcCommand(runtime, {
1864 label: "environment-data:server:signal-process",
1865 tag: WS_METHODS.serverSignalProcess,
1866 }),
1867 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1868 label: "environment-data:server:scheduled-task:upsert",
1869 tag: WS_METHODS.scheduledTasksUpsert,
1870 scheduler: configScheduler,
1871 concurrency: configConcurrency,
1872 }),
1873 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1874 label: "environment-data:server:scheduled-task:set-enabled",
1875 tag: WS_METHODS.scheduledTasksSetEnabled,
1876 scheduler: configScheduler,
1877 concurrency: configConcurrency,
1878 }),
1879 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1880 label: "environment-data:server:scheduled-task:delete",
1881 tag: WS_METHODS.scheduledTasksDelete,
1882 scheduler: configScheduler,
1883 concurrency: configConcurrency,
1884 }),
1885 // Deliberately not on the config lane: run-now blocks until the run is
1886 // dispatched, and a slow run must not stall settings/keybinding/provider
1887 // mutations (or other scheduled-task edits) queued behind it.
1888 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1889 label: "environment-data:server:scheduled-task:run-now",
1890 tag: WS_METHODS.scheduledTasksRunNow,
1891 }),
1892 rotateScheduledTaskWebhookToken: createEnvironmentRpcCommand(runtime, {
1893 label: "environment-data:server:scheduled-task:rotate-webhook-token",
1894 tag: WS_METHODS.scheduledTasksRotateWebhookToken,
1895 scheduler: configScheduler,
1896 concurrency: configConcurrency,
1897 }),
1898 createGuestShare: createEnvironmentRpcCommand(runtime, {
1899 label: "environment-data:server:guest-share:create",
1900 tag: WS_METHODS.guestShareCreate,
1901 }),
1902 // Off the config lane: answering a card must not queue behind settings
1903 // edits. One answer per card at a time.
1904 answerSecretRequest: createEnvironmentRpcCommand(runtime, {
1905 label: "environment-data:server:secrets:answer-request",
1906 tag: WS_METHODS.secretsAnswerRequest,
1907 concurrency: {
1908 mode: "singleFlight",
1909 key: ({ environmentId, input }) =>
1910 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
1911 },
1912 }),
1913 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1914 label: "environment-data:server:refresh-usage-rates",
1915 tag: WS_METHODS.serverRefreshUsageRates,
1916 concurrency: {
1917 mode: "singleFlight",
1918 key: ({ environmentId }) => environmentId,
1919 },
1920 }),
1921 checkOtlpEndpoint: createEnvironmentRpcCommand(runtime, {
1922 label: "environment-data:server:check-otlp-endpoint",
1923 tag: WS_METHODS.serverCheckOtlpEndpoint,
1924 }),
1925 checkSecretSource: createEnvironmentRpcCommand(runtime, {
1926 label: "environment-data:server:check-secret-source",
1927 tag: WS_METHODS.serverCheckSecretSource,
1928 }),
1929 listTextGeneratorModels: createEnvironmentRpcCommand(runtime, {
1930 label: "environment-data:server:list-text-generator-models",
1931 tag: WS_METHODS.serverListTextGeneratorModels,
1932 }),
1933 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1934 label: "environment-data:server:retry-resource-telemetry",
1935 tag: WS_METHODS.serverRetryResourceTelemetry,
1936 concurrency: {
1937 mode: "singleFlight",
1938 key: ({ environmentId }) => environmentId,
1939 },
1940 }),
1941 };
1942 }