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

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