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

providerMaintenanceRunner.ts

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