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