Open History to see the last commit
1import {
2 defaultInstanceIdForDriver,
3 ProviderDriverKind,
4 ServerProviderUpdateError,
5 type ProviderInstanceId,
6 type ServerProvider,
7 type ServerProviderUpdatedPayload,
8 type ServerProviderUpdateState,
9} from "@t3tools/contracts";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Cause from "effect/Cause";
12import * as Context from "effect/Context";
13import * as DateTime from "effect/DateTime";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Fiber from "effect/Fiber";
17import * as Layer from "effect/Layer";
18import * as Ref from "effect/Ref";
19import * as Schedule from "effect/Schedule";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import { HttpClient } from "effect/http";
23import { ChildProcess, ChildProcessSpawner } from "effect/process";
24import * as NodeUtil from "node:util";
25
26import * as ModelManifest from "./ModelManifest.ts";
27import * as ProviderInstallationGate from "./ProviderInstallationGate.ts";
28import * as ProviderRegistry from "./ProviderRegistry.ts";
29import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
30import {
31 enrichProviderSnapshotWithVersionAdvisory,
32 invalidateLatestProviderVersion,
33 makeTargetedProviderUpdateAction,
34 resolveLatestProviderUpdateAction,
35 resolveLatestProviderVersion,
36 type ProviderMaintenanceCommandAction,
37} from "@t3tools/provider-core/server/maintenanceResolver";
38import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
39import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
40import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
41const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
42
43const UPDATE_OUTPUT_MAX_BYTES = 10_000;
44// Sample installer output because every progress update resends the provider list to all clients.
45const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1);
46const UPDATE_PROGRESS_MAX_LENGTH = 200;
47// An installer may write for minutes without a line ending; only its tail matters.
48const UPDATE_PARTIAL_LINE_MAX_LENGTH = 4_096;
49
50export interface ProviderMaintenanceCommandResult {
51 readonly stdout: string;
52 readonly stderr: string;
53 readonly exitCode: number | null;
54 readonly stdoutTruncated: boolean;
55 readonly stderrTruncated: boolean;
56}
57
58export interface ProviderMaintenanceRunnerShape {
59 readonly updateProvider: (
60 target:
61 | ProviderDriverKind
62 | {
63 readonly provider: ProviderDriverKind;
64 readonly instanceId?: ProviderInstanceId | undefined;
65 readonly targetVersion?: string | undefined;
66 },
67 ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;
68}
69
70export class ProviderMaintenanceRunner extends Context.Service<
71 ProviderMaintenanceRunner,
72 ProviderMaintenanceRunnerShape
73>()("t3/provider/providerMaintenanceRunner") {}
74
75class ProviderMaintenanceCommandError extends Schema.TaggedError<ProviderMaintenanceCommandError>()(
76 "ProviderMaintenanceCommandError",
77 {
78 message: Schema.String,
79 cause: Schema.optional(Schema.Defect()),
80 },
81) {}
82
83interface VerifiedProviderRefresh {
84 readonly providers: ReadonlyArray<ServerProvider>;
85 readonly verifiedProviders: ReadonlyArray<ServerProvider>;
86 readonly advisoryEnriched: boolean;
87}
88
89const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
90
91const OPENCODE_SERVER_RESTART_MESSAGE =
92 "OpenCode CLI updated. Restart the configured local OpenCode server to use the new version.";
93
94const needsOpenCodeServerRestart = (providers: ReadonlyArray<ServerProvider>) =>
95 providers.some(
96 (provider) =>
97 provider.driver === ProviderDriverKind.make("opencode") &&
98 provider.installedVersion != null &&
99 provider.version != null &&
100 provider.installedVersion !== provider.version,
101 );
102
103const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceRunner.runCommand")(
104 function* (input: {
105 readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
106 readonly command: string;
107 readonly args: ReadonlyArray<string>;
108 readonly env?: NodeJS.ProcessEnv;
109 readonly onProgress?: (line: string) => Effect.Effect<void>;
110 }) {
111 const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
112 function* () {
113 const env = input.env ? { env: input.env, extendEnv: true } : {};
114 // Windows batch shims require shell dispatch through resolveSpawnCommand.
115 const resolved = yield* resolveSpawnCommand(input.command, input.args, env);
116 const child = yield* input.spawner
117 .spawn(
118 ChildProcess.make(resolved.command, resolved.args, {
119 shell: resolved.shell,
120 // Nothing answers an update command, so one that reads stdin must see EOF, not wait.
121 stdin: "ignore",
122 ...env,
123 }),
124 )
125 .pipe(
126 Effect.mapError(
127 (cause) =>
128 new ProviderMaintenanceCommandError({
129 message: `Failed to run update command ${input.command}: ${cause.message}`,
130 cause,
131 }),
132 ),
133 );
134 yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
135
136 const pendingProgress = yield* Ref.make<string | null>(null);
137 const onProgress = input.onProgress;
138 if (onProgress) {
139 yield* Ref.getAndSet(pendingProgress, null).pipe(
140 Effect.flatMap((line) => (line === null ? Effect.void : onProgress(line))),
141 Effect.repeat(Schedule.spaced(UPDATE_PROGRESS_INTERVAL)),
142 Effect.forkScoped,
143 );
144 }
145 const trackProgress = <E>(stream: Stream.Stream<Uint8Array, E>) => {
146 if (!onProgress) {
147 return stream;
148 }
149 const decoder = new TextDecoder();
150 let partialLine = "";
151 return stream.pipe(
152 Stream.tap((chunk) => {
153 const split = splitOutputLines(partialLine, decoder.decode(chunk, { stream: true }));
154 partialLine = split.partialLine;
155 const line =
156 toProgressLine(split.partialLine) ??
157 split.lines.map(toProgressLine).findLast((value) => value !== null);
158 return line ? Ref.set(pendingProgress, line) : Effect.void;
159 }),
160 );
161 };
162
163 const [stdout, stderr, exitCode] = yield* Effect.all(
164 [
165 collectUint8StreamText({
166 stream: trackProgress(child.stdout),
167 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
168 }),
169 collectUint8StreamText({
170 stream: trackProgress(child.stderr),
171 maxBytes: UPDATE_OUTPUT_MAX_BYTES,
172 }),
173 child.exitCode,
174 ],
175 { concurrency: "unbounded" },
176 ).pipe(
177 Effect.mapError(
178 (cause) =>
179 new ProviderMaintenanceCommandError({
180 message: cause instanceof Error ? cause.message : "Update command failed to run.",
181 cause,
182 }),
183 ),
184 );
185
186 return {
187 stdout: stdout.text,
188 stderr: stderr.text,
189 exitCode: Number(exitCode),
190 stdoutTruncated: stdout.truncated,
191 stderrTruncated: stderr.truncated,
192 } satisfies ProviderMaintenanceCommandResult;
193 },
194 );
195
196 // No timeout: killing an installer mid-install leaves the provider half-replaced (npm has moved
197 // the old package and its shims aside; `claude update` leaves a truncated binary), and an
198 // installer still running must keep the update's locks until it exits.
199 return yield* collectCommandResult().pipe(Effect.scoped);
200 },
201);
202
203export function splitOutputLines(
204 partialLine: string,
205 text: string,
206): { readonly lines: ReadonlyArray<string>; readonly partialLine: string } {
207 const parts = (partialLine + text).replace(/\x1b\[(?:0*1?G|999D)/g, "\r").split(/\r\n|\r|\n/);
208 return { partialLine: (parts.pop() ?? "").slice(-UPDATE_PARTIAL_LINE_MAX_LENGTH), lines: parts };
209}
210
211export function toProgressLine(line: string): string | null {
212 if (/\x1b(?:\[[0-9]*)?$/.test(line)) {
213 return null;
214 }
215 const text = NodeUtil.stripVTControlCharacters(line).replace(/\s+/g, " ").trim();
216 if (text.length === 0) {
217 return null;
218 }
219 return text.length <= UPDATE_PROGRESS_MAX_LENGTH
220 ? text
221 : `${text.slice(0, UPDATE_PROGRESS_MAX_LENGTH - 1)}…`;
222}
223
224function describeCommand(command: ProviderMaintenanceCommandAction): string {
225 const executable = command.executable.split(/[\\/]/).pop() || command.executable;
226 return [executable, ...command.args].join(" ");
227}
228
229function trimNullable(value: string): string | null {
230 const trimmed = value.trim();
231 return trimmed.length > 0 ? trimmed : null;
232}
233
234function truncateText(value: string, maxLength: number): string {
235 return value.length <= maxLength ? value : value.slice(0, maxLength);
236}
237
238function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
239 const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
240 if (!output) {
241 return null;
242 }
243 return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
244}
245
246// Updaters report on stderr, but may follow their error with hints (`claude update`
247// ends with "Try running claude doctor"), so prefer the last line naming an error.
248function failureReason(result: ProviderMaintenanceCommandResult): string | null {
249 const streams = [result.stderr, result.stdout].map((output) =>
250 output
251 .split(/\r\n|\r|\n/)
252 .map(toProgressLine)
253 .filter((line) => line !== null),
254 );
255 return (
256 streams.map((lines) => lines.findLast((line) => /error|fail/i.test(line))).find(Boolean) ??
257 streams.map((lines) => lines.at(-1)).find(Boolean) ??
258 null
259 );
260}
261
262function failureMessage(result: ProviderMaintenanceCommandResult): string {
263 const summary =
264 result.exitCode !== null && result.exitCode !== 0
265 ? `Update command exited with code ${result.exitCode}`
266 : "Update command failed";
267 const reason = failureReason(result);
268 return reason ? `${summary}: ${reason}` : `${summary}.`;
269}
270
271function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
272 return provider?.versionAdvisory?.status === "behind_latest";
273}
274
275function isStillInstalled(provider: ServerProvider): boolean {
276 return provider.installed;
277}
278
279function makeUpdateState(input: {
280 readonly status: ServerProviderUpdateState["status"];
281 readonly startedAt: string | null;
282 readonly finishedAt: string | null;
283 readonly message: string | null;
284 readonly output?: string | null;
285}): ServerProviderUpdateState {
286 return {
287 status: input.status,
288 startedAt: input.startedAt,
289 finishedAt: input.finishedAt,
290 message: input.message,
291 output: input.output ?? null,
292 };
293}
294
295/** @public */
296export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
297 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
298 const manifestService = yield* ModelManifest.ModelManifest;
299 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
300 const httpClient = yield* HttpClient.HttpClient;
301 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
302 const serviceScope = yield* Effect.scope;
303 const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate;
304 const runMaintenanceCommand = (
305 update: ProviderMaintenanceCommandAction,
306 onProgress: (line: string) => Effect.Effect<void>,
307 ) =>
308 runProviderMaintenanceCommandWithSpawner({
309 spawner,
310 command: update.executable,
311 args: update.args,
312 onProgress,
313 ...(update.env ? { env: update.env } : {}),
314 });
315 // Instances with other homes or accounts can still run the binary this update replaces. The
316 // lock key names the package manager location, so other drivers there keep their own package.
317 const instancesSharingInstallation = Effect.fn(
318 "ProviderMaintenanceRunner.instancesSharingInstallation",
319 )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind, lockKey: string) {
320 const providers = yield* providerRegistry.getProviders;
321 const shared = yield* Effect.forEach(
322 providers.filter(
323 (candidate) => candidate.instanceId !== instanceId && candidate.driver === provider,
324 ),
325 (candidate) =>
326 providerRegistry
327 .getProviderMaintenanceCapabilitiesForInstance(candidate.instanceId, candidate.driver)
328 .pipe(
329 Effect.map((capabilities) =>
330 capabilities.update?.lockKey === lockKey ? [candidate.instanceId] : [],
331 ),
332 ),
333 { concurrency: "unbounded" },
334 );
335 return [instanceId, ...shared.flat()];
336 });
337 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
338 makeAlreadyRunningError: () =>
339 new ServerProviderUpdateError({
340 provider: ProviderDriverKind.make("unknown"),
341 reason: "An update is already running for this provider.",
342 }),
343 });
344
345 const verifyFromRefresh = (
346 refresh: Effect.Effect<ReadonlyArray<ServerProvider>>,
347 provider: ProviderDriverKind,
348 maintenanceCapabilities: ProviderMaintenanceCapabilities,
349 instanceId: ProviderInstanceId,
350 phase: "pre-update" | "post-update",
351 ): Effect.Effect<VerifiedProviderRefresh> =>
352 refresh.pipe(
353 Effect.flatMap((providers) => {
354 const refreshedProviders = providers.filter(
355 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
356 );
357 if (refreshedProviders.length === 0) {
358 return Effect.succeed<VerifiedProviderRefresh>({
359 providers,
360 verifiedProviders: [],
361 advisoryEnriched: true,
362 });
363 }
364 return Effect.forEach(
365 refreshedProviders,
366 (refreshedProvider) =>
367 enrichProviderSnapshotWithVersionAdvisory(
368 refreshedProvider,
369 maintenanceCapabilities,
370 ).pipe(
371 Effect.provideService(HttpClient.HttpClient, httpClient),
372 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
373 ),
374 {
375 concurrency: "unbounded",
376 },
377 ).pipe(
378 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
379 providers,
380 verifiedProviders,
381 advisoryEnriched: true,
382 })),
383 Effect.catchCause((cause) =>
384 Effect.logWarning("Provider version verification failed", {
385 provider,
386 phase,
387 cause: Cause.pretty(cause),
388 }).pipe(
389 Effect.as<VerifiedProviderRefresh>({
390 providers,
391 verifiedProviders: refreshedProviders,
392 advisoryEnriched: false,
393 }),
394 ),
395 ),
396 );
397 }),
398 );
399
400 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
401 "ProviderMaintenanceRunner.updateProvider",
402 )(function* (target) {
403 const provider = typeof target === "string" ? target : target.provider;
404 const instanceId =
405 typeof target === "string"
406 ? defaultInstanceIdForDriver(provider)
407 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
408 const targetVersion = typeof target === "string" ? undefined : target.targetVersion;
409 const targetKey = `instance:${instanceId}`;
410 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
411 instanceId,
412 provider,
413 );
414 const update = capabilities.update;
415 if (!update) {
416 return yield* new ServerProviderUpdateError({
417 provider,
418 reason: "This provider does not support one-click updates.",
419 });
420 }
421
422 const startedAtRef = yield* Ref.make<string | null>(null);
423 const settled = yield* Ref.make(false);
424 const setUpdateState = (state: ServerProviderUpdateState | null) =>
425 providerRegistry.setProviderMaintenanceActionState({
426 instanceId,
427 action: "update",
428 state,
429 targetVersion,
430 });
431 const setQueuedState = setUpdateState(
432 makeUpdateState({
433 status: "queued",
434 startedAt: null,
435 finishedAt: null,
436 message: "Waiting for another provider update to finish.",
437 }),
438 ).pipe(Effect.asVoid);
439
440 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
441 function* () {
442 // Uninterruptible, so a dropped request cannot leave settled set without the state.
443 const finish = (state: ServerProviderUpdateState) =>
444 Ref.set(settled, true).pipe(
445 Effect.andThen(setUpdateState(state)),
446 Effect.map((providers) => ({ providers })),
447 Effect.uninterruptible,
448 );
449
450 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
451 function* () {
452 const startedAt = yield* nowIso;
453 yield* Ref.set(startedAtRef, startedAt);
454 const setRunningMessage = (message: string) =>
455 setUpdateState(
456 makeUpdateState({
457 status: "running",
458 startedAt,
459 finishedAt: null,
460 message,
461 }),
462 ).pipe(Effect.asVoid);
463 yield* setRunningMessage("Checking for the latest version");
464
465 // Recheck ownership after acquiring the cached lock in case the executable changed.
466 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
467 instanceId,
468 provider,
469 { fresh: true },
470 );
471 if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
472 return yield* finish(
473 makeUpdateState({
474 status: "failed",
475 startedAt,
476 finishedAt: yield* nowIso,
477 message: "Provider installation changed. Refresh and try again.",
478 }),
479 );
480 }
481
482 const manifest = yield* manifestService.current;
483 // Check compatibility against what an unpinned command would install now.
484 const candidateVersion =
485 targetVersion ??
486 (yield* invalidateLatestProviderVersion(fresh).pipe(
487 Effect.andThen(resolveLatestProviderVersion(fresh)),
488 Effect.provideService(HttpClient.HttpClient, httpClient),
489 Effect.provideService(
490 ProviderLatestVersions.ProviderLatestVersions,
491 latestVersions,
492 ),
493 ));
494 const advisory = ModelManifest.providerCompatibility(
495 manifest,
496 provider,
497 candidateVersion,
498 );
499 const command =
500 targetVersion !== undefined
501 ? makeTargetedProviderUpdateAction(fresh, targetVersion)
502 : resolveLatestProviderUpdateAction(fresh, candidateVersion);
503 const rejected =
504 targetVersion !== undefined
505 ? !command ||
506 advisory?.recommendedVersion !== targetVersion ||
507 advisory.status !== "supported"
508 : advisory?.status === "broken" || advisory?.status === "unsupported";
509 if (rejected || !command) {
510 return yield* finish(
511 makeUpdateState({
512 status: "failed",
513 startedAt,
514 finishedAt: yield* nowIso,
515 message:
516 targetVersion !== undefined
517 ? "This version is no longer recommended or this installer cannot install a specific version. Refresh provider settings."
518 : "The latest provider version is incompatible with this T3 Code release. Review provider settings.",
519 }),
520 );
521 }
522
523 if (targetVersion === undefined) {
524 const prior = (yield* providerRegistry.getProviders).find(
525 (candidate) => candidate.instanceId === instanceId,
526 );
527 const precheck = yield* verifyFromRefresh(
528 providerRegistry.refreshInstance(instanceId),
529 provider,
530 fresh,
531 instanceId,
532 "pre-update",
533 );
534 const alreadyCurrent =
535 precheck.advisoryEnriched &&
536 prior !== undefined &&
537 precheck.verifiedProviders.length > 0 &&
538 precheck.verifiedProviders.every(
539 (verified) =>
540 verified.checkedAt !== prior.checkedAt &&
541 verified.installed &&
542 verified.status !== "error" &&
543 verified.versionAdvisory?.status === "current",
544 );
545 if (alreadyCurrent) {
546 return yield* finish(
547 makeUpdateState({
548 status: "succeeded",
549 startedAt,
550 finishedAt: yield* nowIso,
551 message: needsOpenCodeServerRestart(precheck.verifiedProviders)
552 ? OPENCODE_SERVER_RESTART_MESSAGE
553 : "Already up to date.",
554 }),
555 );
556 }
557 }
558
559 const sharingInstances = yield* instancesSharingInstallation(
560 instanceId,
561 provider,
562 update.lockKey,
563 );
564 yield* setRunningMessage("Waiting for running provider work to finish.");
565 const result = yield* installationGate.update(
566 sharingInstances,
567 setRunningMessage(`Running ${describeCommand(command)}`).pipe(
568 Effect.andThen(runMaintenanceCommand(command, setRunningMessage)),
569 ),
570 );
571 const finishedAt = yield* nowIso;
572 if (result.exitCode !== 0) {
573 yield* Effect.logWarning("Provider update command failed", {
574 provider,
575 command: describeCommand(command),
576 exitCode: result.exitCode,
577 output: commandOutput(result),
578 });
579 return yield* finish(
580 makeUpdateState({
581 status: "failed",
582 startedAt,
583 finishedAt,
584 message: failureMessage(result),
585 output: commandOutput(result),
586 }),
587 );
588 }
589
590 yield* setRunningMessage("Verifying the installed version");
591 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
592 instanceId,
593 provider,
594 { fresh: true },
595 );
596 yield* invalidateLatestProviderVersion(verified).pipe(
597 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
598 );
599 const { verifiedProviders } = yield* verifyFromRefresh(
600 providerRegistry.refreshAfterUpdate(provider, instanceId),
601 provider,
602 verified,
603 instanceId,
604 "post-update",
605 );
606 // Cursor about probes can fail transiently; missing versions alone do not imply failure.
607 const couldNotVerify =
608 verifiedProviders.length === 0 ||
609 verifiedProviders.some((verifiedProvider) => {
610 const installedVersion =
611 verifiedProvider.installedVersion !== undefined
612 ? verifiedProvider.installedVersion
613 : verifiedProvider.version;
614 return (
615 !isStillInstalled(verifiedProvider) ||
616 (verifiedProvider.status === "error" &&
617 (verifiedProvider.auth.status !== "unauthenticated" ||
618 !verifiedProvider.version)) ||
619 (targetVersion !== undefined &&
620 installedVersion?.replace(/^v/, "") !== targetVersion)
621 );
622 });
623 const stillOutdated =
624 targetVersion === undefined &&
625 verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
626 return yield* finish(
627 makeUpdateState({
628 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
629 startedAt,
630 finishedAt,
631 message: couldNotVerify
632 ? "Update command completed, but T3 Code could not verify the provider version."
633 : stillOutdated
634 ? "Update command completed, but T3 Code still detects an outdated provider version."
635 : needsOpenCodeServerRestart(verifiedProviders)
636 ? OPENCODE_SERVER_RESTART_MESSAGE
637 : "Provider updated.",
638 output: commandOutput(result),
639 }),
640 );
641 },
642 );
643
644 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
645 function* (cause: Cause.Cause<unknown>) {
646 const failure = Cause.squash(cause);
647 const startedAt = yield* Ref.get(startedAtRef);
648 return yield* finish(
649 makeUpdateState({
650 status: "failed",
651 startedAt,
652 finishedAt: yield* nowIso,
653 message: failure instanceof Error ? failure.message : "Update command failed.",
654 output: null,
655 }),
656 );
657 },
658 );
659
660 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
661 },
662 );
663
664 // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller.
665 const updateFiber = yield* commandCoordinator
666 .withCommandLock({
667 targetKey,
668 lockKey: update.lockKey,
669 onQueued: setQueuedState,
670 run: runProviderUpdate(),
671 })
672 .pipe(
673 // Server shutdown interrupts the update; a "running" state would spin until restart.
674 Effect.onInterrupt(() =>
675 Effect.gen(function* () {
676 // A finished state stays, even if shutdown lands while it is being written.
677 if (yield* Ref.get(settled)) return;
678 yield* setUpdateState(
679 makeUpdateState({
680 status: "failed",
681 startedAt: yield* Ref.get(startedAtRef),
682 finishedAt: yield* nowIso,
683 message: "Update stopped before it finished.",
684 }),
685 );
686 }).pipe(Effect.ignore),
687 ),
688 Effect.forkIn(serviceScope),
689 );
690 return yield* Fiber.join(updateFiber).pipe(
691 Effect.mapError((error) =>
692 isServerProviderUpdateError(error)
693 ? new ServerProviderUpdateError({
694 provider,
695 reason: error.reason,
696 })
697 : error,
698 ),
699 );
700 });
701
702 return ProviderMaintenanceRunner.of({
703 updateProvider,
704 });
705});
706
707export const layer = Layer.effect(ProviderMaintenanceRunner, make());