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

providerMaintenanceRunner.ts

736 lines28.0 KB

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