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