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

providerMaintenanceRunner.ts

790 lines30.5 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 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;
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>;
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;
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 };
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)}…`;
223​
224function updateLockKey(capabilities: ProviderMaintenanceCapabilities): string | null {
225 return capabilities.update?.lockKey ?? capabilities.managedUpdate?.lockKey ?? null;
227​
228function installationTargetKey(
229 provider: ProviderDriverKind,
230 capabilities: ProviderMaintenanceCapabilities,
231): string | null {
232 const lockKey = updateLockKey(capabilities);
233 if (lockKey === null) {
234 return null;
235 }
236 const update = capabilities.update;
237 return update !== null
238 ? ["installation", provider, lockKey, update.executable, ...update.args].join("\0")
239 : ["installation", provider, lockKey].join("\0");
241​
242const MANAGED_UPDATE_SUCCEEDED: ProviderMaintenanceCommandResult = {
243 stdout: "",
244 stderr: "",
245 exitCode: 0,
246 stdoutTruncated: false,
247 stderrTruncated: false,
248};
249​
250function describeCommand(command: ProviderMaintenanceCommandAction): string {
251 const executable = command.executable.split(/[\\/]/).pop() || command.executable;
252 return [executable, ...command.args].join(" ");
254​
255function trimNullable(value: string): string | null {
256 const trimmed = value.trim();
257 return trimmed.length > 0 ? trimmed : null;
259​
260function truncateText(value: string, maxLength: number): string {
261 return value.length <= maxLength ? value : value.slice(0, maxLength);
263​
264function commandOutput(result: ProviderMaintenanceCommandResult): string | null {
265 const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join("\n\n"));
266 if (!output) {
267 return null;
268 }
269 return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);
271​
272// Updaters report on stderr, but may follow their error with hints (`claude update`
273// ends with "Try running claude doctor"), so prefer the last line naming an error.
274function failureReason(result: ProviderMaintenanceCommandResult): string | null {
275 const streams = [result.stderr, result.stdout].map((output) =>
276 output
277 .split(/\r\n|\r|\n/)
278 .map(toProgressLine)
279 .filter((line) => line !== null),
280 );
281 return (
282 streams.map((lines) => lines.findLast((line) => /error|fail/i.test(line))).find(Boolean) ??
283 streams.map((lines) => lines.at(-1)).find(Boolean) ??
284 null
285 );
287​
288function failureMessage(result: ProviderMaintenanceCommandResult): string {
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 serviceScope = yield* Effect.scope;
329 const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate;
330 const runMaintenanceCommand = (
331 update: ProviderMaintenanceCommandAction,
332 onProgress: (line: string) => Effect.Effect<void>,
333 ) =>
334 runProviderMaintenanceCommandWithSpawner({
335 spawner,
336 command: update.executable,
337 args: update.args,
338 onProgress,
339 ...(update.env ? { env: update.env } : {}),
340 });
341 const siblingInstances = Effect.fn("ProviderMaintenanceRunner.siblingInstances")(function* (
342 instanceId: ProviderInstanceId,
343 provider: ProviderDriverKind,
344 matches: (capabilities: ProviderMaintenanceCapabilities) => boolean,
345 options?: { readonly enabledOnly?: boolean },
346 ) {
347 const providers = yield* providerRegistry.getProviders;
348 const shared = yield* Effect.forEach(
349 providers.filter(
350 (candidate) =>
351 candidate.instanceId !== instanceId &&
352 candidate.driver === provider &&
353 (options?.enabledOnly !== true || candidate.enabled),
354 ),
355 (candidate) =>
356 providerRegistry
357 .getProviderMaintenanceCapabilitiesForInstance(candidate.instanceId, candidate.driver)
358 .pipe(
359 Effect.map((capabilities) => (matches(capabilities) ? [candidate.instanceId] : [])),
360 ),
361 { concurrency: "unbounded" },
362 );
363 return [instanceId, ...shared.flat()];
364 });
365 // Instances with other homes or accounts can still run the binary this update replaces. The
366 // lock key names the package manager location, so other drivers there keep their own package.
367 const instancesSharingInstallation = (
368 instanceId: ProviderInstanceId,
369 provider: ProviderDriverKind,
370 lockKey: string,
371 ) =>
372 siblingInstances(
373 instanceId,
374 provider,
375 (capabilities) => capabilities.update?.lockKey === lockKey,
376 );
377 const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
378 makeAlreadyRunningError: () =>
379 new ServerProviderUpdateError({
380 provider: ProviderDriverKind.make("unknown"),
381 reason: "An update is already running for this provider.",
382 }),
383 });
384​
385 const verifyFromRefresh = (
386 refresh: Effect.Effect<ReadonlyArray<ServerProvider>>,
387 provider: ProviderDriverKind,
388 maintenanceCapabilities: ProviderMaintenanceCapabilities,
389 instanceId: ProviderInstanceId,
390 phase: "pre-update" | "post-update",
391 ): Effect.Effect<VerifiedProviderRefresh> =>
392 refresh.pipe(
393 Effect.flatMap((providers) => {
394 const refreshedProviders = providers.filter(
395 (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
396 );
397 if (refreshedProviders.length === 0) {
398 return Effect.succeed<VerifiedProviderRefresh>({
399 providers,
400 verifiedProviders: [],
401 advisoryEnriched: true,
402 });
403 }
404 return Effect.forEach(
405 refreshedProviders,
406 (refreshedProvider) =>
407 enrichProviderSnapshotWithVersionAdvisory(
408 refreshedProvider,
409 maintenanceCapabilities,
410 // Pre/post-update verification must not treat a stale cached version as live proof.
411 { fallbackToStale: false },
412 ).pipe(
413 Effect.provideService(HttpClient.HttpClient, httpClient),
414 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
415 ),
416 {
417 concurrency: "unbounded",
418 },
419 ).pipe(
420 Effect.map((verifiedProviders): VerifiedProviderRefresh => ({
421 providers,
422 verifiedProviders,
423 advisoryEnriched: true,
424 })),
425 Effect.catchCause((cause) =>
426 Effect.logWarning("Provider version verification failed", {
427 provider,
428 phase,
429 cause: Cause.pretty(cause),
430 }).pipe(
431 Effect.as<VerifiedProviderRefresh>({
432 providers,
433 verifiedProviders: refreshedProviders,
434 advisoryEnriched: false,
435 }),
436 ),
437 ),
438 );
439 }),
440 );
441​
442 const updateProvider: ProviderMaintenanceRunnerShape["updateProvider"] = Effect.fn(
443 "ProviderMaintenanceRunner.updateProvider",
444 )(function* (target) {
445 const provider = typeof target === "string" ? target : target.provider;
446 const instanceId =
447 typeof target === "string"
448 ? defaultInstanceIdForDriver(provider)
449 : (target.instanceId ?? defaultInstanceIdForDriver(provider));
450 const targetVersion = typeof target === "string" ? undefined : target.targetVersion;
451 const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
452 instanceId,
453 provider,
454 );
455 const lockKey = updateLockKey(capabilities);
456 const targetKey = installationTargetKey(provider, capabilities);
457 if (lockKey === null || targetKey === null) {
458 return yield* new ServerProviderUpdateError({
459 provider,
460 reason: "This provider does not support one-click updates.",
461 });
462 }
463 // Enabled siblings on the same installation show this update's progress; disabled ones are
464 // not refreshed afterwards, so a mirrored state there would never clear.
465 const siblingsOnInstallation = (key: string) =>
466 siblingInstances(
467 instanceId,
468 provider,
469 (sibling) => installationTargetKey(provider, sibling) === key,
470 { enabledOnly: true },
471 );
472 const stateRecipientsRef = yield* Ref.make(yield* siblingsOnInstallation(targetKey));
473​
474 const startedAtRef = yield* Ref.make<string | null>(null);
475 const settled = yield* Ref.make(false);
476 const setUpdateState = (state: ServerProviderUpdateState | null) =>
477 Ref.get(stateRecipientsRef).pipe(
478 Effect.flatMap((instanceIds) =>
479 providerRegistry.setProviderMaintenanceActionState({
480 instanceIds,
481 action: "update",
482 state,
483 targetVersion,
484 }),
485 ),
486 );
487 const setQueuedState = setUpdateState(
488 makeUpdateState({
489 status: "queued",
490 startedAt: null,
491 finishedAt: null,
492 message: "Waiting for another provider update to finish.",
493 }),
494 ).pipe(Effect.asVoid);
495​
496 const runProviderUpdate = Effect.fn("ProviderMaintenanceRunner.runProviderUpdate")(
497 function* () {
498 // Uninterruptible, so a dropped request cannot leave settled set without the state.
499 const finish = (state: ServerProviderUpdateState) =>
500 Ref.set(settled, true).pipe(
501 Effect.andThen(setUpdateState(state)),
502 Effect.map((providers) => ({ providers })),
503 Effect.uninterruptible,
504 );
505​
506 const runCommandAndVerify = Effect.fn("ProviderMaintenanceRunner.runCommandAndVerify")(
507 function* () {
508 const startedAt = yield* nowIso;
509 yield* Ref.set(startedAtRef, startedAt);
510 const setRunningMessage = (message: string) =>
511 setUpdateState(
512 makeUpdateState({
513 status: "running",
514 startedAt,
515 finishedAt: null,
516 message,
517 }),
518 ).pipe(Effect.asVoid);
519 yield* setRunningMessage("Checking for the latest version");
520​
521 // Recheck ownership after acquiring the cached lock in case the executable changed.
522 const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
523 instanceId,
524 provider,
525 { fresh: true },
526 );
527 if (updateLockKey(fresh) !== lockKey) {
528 return yield* finish(
529 makeUpdateState({
530 status: "failed",
531 startedAt,
532 finishedAt: yield* nowIso,
533 message: "Provider installation changed. Refresh and try again.",
534 }),
535 );
536 }
537​
538 // A fresh resolution can name another executable under the same lock, so the
539 // progress follows the installation the command will actually update.
540 const freshTargetKey = installationTargetKey(provider, fresh);
541 if (freshTargetKey !== null && freshTargetKey !== targetKey) {
542 const previous = yield* Ref.get(stateRecipientsRef);
543 const next = yield* siblingsOnInstallation(freshTargetKey);
544 yield* providerRegistry.setProviderMaintenanceActionState({
545 instanceIds: previous.filter((id) => !next.includes(id)),
546 action: "update",
547 state: null,
548 });
549 yield* Ref.set(stateRecipientsRef, next);
550 yield* setRunningMessage("Checking for the latest version");
551 }
552​
553 const manifest = yield* manifestService.current;
554 // Check compatibility against what an unpinned command would install now.
555 const candidateVersion =
556 targetVersion ??
557 (yield* invalidateLatestProviderVersion(fresh).pipe(
558 Effect.andThen(resolveLatestProviderVersion(fresh)),
559 Effect.provideService(HttpClient.HttpClient, httpClient),
560 Effect.provideService(
561 ProviderLatestVersions.ProviderLatestVersions,
562 latestVersions,
563 ),
564 ));
565 const advisory = ModelManifest.providerCompatibility(
566 manifest,
567 provider,
568 candidateVersion,
569 );
570 const command =
571 targetVersion !== undefined
572 ? makeTargetedProviderUpdateAction(fresh, targetVersion)
573 : resolveLatestProviderUpdateAction(fresh, candidateVersion);
574 const managedUpdate = targetVersion === undefined ? fresh.managedUpdate : undefined;
575 const rejected =
576 targetVersion !== undefined
577 ? !command ||
578 advisory?.recommendedVersion !== targetVersion ||
579 advisory.status !== "supported"
580 : advisory?.status === "broken" || advisory?.status === "unsupported";
581 if (rejected || (!command && !managedUpdate)) {
582 return yield* finish(
583 makeUpdateState({
584 status: "failed",
585 startedAt,
586 finishedAt: yield* nowIso,
587 message:
588 targetVersion !== undefined
589 ? "This version is no longer recommended or this installer cannot install a specific version. Refresh provider settings."
590 : "The latest provider version is incompatible with this T3 Code release. Review provider settings.",
591 }),
592 );
593 }
594​
595 if (targetVersion === undefined) {
596 const prior = (yield* providerRegistry.getProviders).find(
597 (candidate) => candidate.instanceId === instanceId,
598 );
599 const precheck = yield* verifyFromRefresh(
600 providerRegistry.refreshInstance(instanceId),
601 provider,
602 fresh,
603 instanceId,
604 "pre-update",
605 );
606 const alreadyCurrent =
607 precheck.advisoryEnriched &&
608 prior !== undefined &&
609 precheck.verifiedProviders.length > 0 &&
610 precheck.verifiedProviders.every(
611 (verified) =>
612 verified.checkedAt !== prior.checkedAt &&
613 verified.installed &&
614 verified.status !== "error" &&
615 verified.versionAdvisory?.status === "current",
616 );
617 if (alreadyCurrent) {
618 return yield* finish(
619 makeUpdateState({
620 status: "succeeded",
621 startedAt,
622 finishedAt: yield* nowIso,
623 message: needsOpenCodeServerRestart(precheck.verifiedProviders)
624 ? OPENCODE_SERVER_RESTART_MESSAGE
625 : "Already up to date.",
626 }),
627 );
628 }
629 }
630​
631 const result = yield* command
632 ? setRunningMessage("Waiting for running provider work to finish.").pipe(
633 Effect.andThen(instancesSharingInstallation(instanceId, provider, lockKey)),
634 Effect.flatMap((sharingInstances) =>
635 installationGate.update(
636 sharingInstances,
637 setRunningMessage(`Running ${describeCommand(command)}`).pipe(
638 Effect.andThen(runMaintenanceCommand(command, setRunningMessage)),
639 ),
640 ),
641 ),
642 )
643 : // A managed install lands beside the runtime that open sessions hold, so nothing drains.
644 setRunningMessage("Installing the latest version").pipe(
645 Effect.andThen(managedUpdate!.run(setRunningMessage)),
646 Effect.as(MANAGED_UPDATE_SUCCEEDED),
647 );
648 const finishedAt = yield* nowIso;
649 if (result.exitCode !== 0) {
650 yield* Effect.logWarning("Provider update command failed", {
651 provider,
652 command: command && describeCommand(command),
653 exitCode: result.exitCode,
654 output: commandOutput(result),
655 });
656 return yield* finish(
657 makeUpdateState({
658 status: "failed",
659 startedAt,
660 finishedAt,
661 message: failureMessage(result),
662 output: commandOutput(result),
663 }),
664 );
665 }
666​
667 yield* setRunningMessage("Verifying the installed version");
668 const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
669 instanceId,
670 provider,
671 { fresh: true },
672 );
673 yield* invalidateLatestProviderVersion(verified).pipe(
674 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
675 );
676 const { verifiedProviders } = yield* verifyFromRefresh(
677 providerRegistry.refreshAfterUpdate(provider, instanceId),
678 provider,
679 verified,
680 instanceId,
681 "post-update",
682 );
683 // Cursor about probes can fail transiently; missing versions alone do not imply failure.
684 const couldNotVerify =
685 verifiedProviders.length === 0 ||
686 verifiedProviders.some((verifiedProvider) => {
687 const installedVersion =
688 verifiedProvider.installedVersion !== undefined
689 ? verifiedProvider.installedVersion
690 : verifiedProvider.version;
691 return (
692 !isStillInstalled(verifiedProvider) ||
693 (verifiedProvider.status === "error" &&
694 (verifiedProvider.auth.status !== "unauthenticated" ||
695 !verifiedProvider.version)) ||
696 (targetVersion !== undefined &&
697 installedVersion?.replace(/^v/, "") !== targetVersion)
698 );
699 });
700 const startupFailure = verifiedProviders.find(
701 (verifiedProvider) =>
702 verifiedProvider.status === "error" && verifiedProvider.message?.trim(),
703 )?.message;
704 const stillOutdated =
705 targetVersion === undefined &&
706 verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
707 return yield* finish(
708 makeUpdateState({
709 status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
710 startedAt,
711 finishedAt,
712 message: couldNotVerify
713 ? startupFailure
714 ? `Update command completed, but the provider cannot start: ${startupFailure.trim()}`
715 : "Update command completed, but T3 Code could not verify the provider version."
716 : stillOutdated
717 ? "Update command completed, but T3 Code still detects an outdated provider version."
718 : needsOpenCodeServerRestart(verifiedProviders)
719 ? OPENCODE_SERVER_RESTART_MESSAGE
720 : "Provider updated.",
721 output: commandOutput(result),
722 }),
723 );
724 },
725 );
726​
727 const recordFailedUpdate = Effect.fn("ProviderMaintenanceRunner.recordFailedUpdate")(
728 function* (cause: Cause.Cause<unknown>) {
729 const failure = Cause.squash(cause);
730 const startedAt = yield* Ref.get(startedAtRef);
731 return yield* finish(
732 makeUpdateState({
733 status: "failed",
734 startedAt,
735 finishedAt: yield* nowIso,
736 message: failure instanceof Error ? failure.message : "Update command failed.",
737 output: null,
738 }),
739 );
740 },
741 );
742​
743 return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));
744 },
745 );
746​
747 // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller.
748 const updateFiber = yield* commandCoordinator
749 .withCommandLock({
750 targetKey,
751 lockKey,
752 onQueued: setQueuedState,
753 run: runProviderUpdate(),
754 })
755 .pipe(
756 // Server shutdown interrupts the update; a "running" state would spin until restart.
757 Effect.onInterrupt(() =>
758 Effect.gen(function* () {
759 // A finished state stays, even if shutdown lands while it is being written.
760 if (yield* Ref.get(settled)) return;
761 yield* setUpdateState(
762 makeUpdateState({
763 status: "failed",
764 startedAt: yield* Ref.get(startedAtRef),
765 finishedAt: yield* nowIso,
766 message: "Update stopped before it finished.",
767 }),
768 );
769 }).pipe(Effect.ignore),
770 ),
771 Effect.forkIn(serviceScope),
772 );
773 return yield* Fiber.join(updateFiber).pipe(
774 Effect.mapError((error) =>
775 isServerProviderUpdateError(error)
776 ? new ServerProviderUpdateError({
777 provider,
778 reason: error.reason,
779 })
780 : error,
781 ),
782 );
783 });
784​
785 return ProviderMaintenanceRunner.of({
786 updateProvider,
787 });
788});
789​
790export const layer = Layer.effect(ProviderMaintenanceRunner, make());