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

snapshotProbe.ts

281 lines9.7 KB

1import type {
2 CustomModelSetting,
3 ProviderDriverKind,
4 ModelCapabilities,
5 RuntimeMode,
6 ServerProvider,
7 ServerProviderAuth,
8 ServerProviderSkill,
9 ServerProviderSlashCommand,
10 ServerProviderModel,
11 ServerProviderUpdateRequiredModel,
12 ServerProviderState,
13 ServerProviderUsageLimits,
14} from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as PlatformError from "effect/PlatformError";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as ChildProcess from "effect/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21import { readCustomModelEntries } from "@t3tools/shared/model";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23import { createProviderVersionAdvisory } from "./maintenanceResolver.ts";
24import { collectUint8StreamText } from "./collectStreamText.ts";
25​
26const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
27 /is not recognized as an internal or external command/i,
28 /n.o . reconhecido como um comando interno/i,
29 /non . riconosciuto come comando interno o esterno/i,
30 /n.est pas reconnu en tant que commande interne/i,
31 /no se reconoce como un comando interno o externo/i,
32 /wird nicht als interner oder externer befehl/i,
33] as const;
34​
35export const isWindowsCommandNotFound = Effect.fn("isWindowsCommandNotFound")(function* (
36 code: number | null,
37 stderr: string,
38) {
39 const platform = yield* HostProcess.Platform;
40 if (platform !== "win32") return false;
41 if (code === 9009) return true;
42 return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(stderr));
43});
44​
45export const DEFAULT_TIMEOUT_MS = 4_000;
46export const AUTH_PROBE_TIMEOUT_MS = 10_000;
47​
48export const COMPACT_SLASH_COMMAND = {
49 name: "compact",
50 description: "Summarize the conversation and reduce context usage",
51} satisfies ServerProviderSlashCommand;
52​
53export interface CommandResult {
54 readonly stdout: string;
55 readonly stderr: string;
56 readonly code: number;
58​
59export class ProviderCommandNotFoundError extends Schema.TaggedError<ProviderCommandNotFoundError>()(
60 "ProviderCommandNotFoundError",
61 {
62 binaryPath: Schema.String,
63 exitCode: Schema.Number,
64 stdoutLength: Schema.Number,
65 stderrLength: Schema.Number,
66 },
67) {
68 override get message(): string {
69 return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;
70 }
72​
73const isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);
74​
75export interface ProviderProbeResult {
76 readonly installed: boolean;
77 readonly version: string | null;
78 readonly status: Exclude<ServerProviderState, "disabled">;
79 readonly auth: ServerProviderAuth;
80 readonly message?: string;
81 readonly usageLimits?: ServerProviderUsageLimits;
83​
84export interface ServerProviderPresentation {
85 readonly displayName: string;
86 readonly badgeLabel?: string;
87 readonly showInteractionModeToggle?: boolean;
88 readonly reportsContextWindow?: boolean;
89 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
90 readonly supportsConversationRollback?: boolean;
92​
93export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
94​
95export function nonEmptyTrimmed(value: string | undefined): string | undefined {
96 if (!value) return undefined;
97 const trimmed = value.trim();
98 return trimmed.length > 0 ? trimmed : undefined;
100​
101export function isCommandMissingCause(error: unknown): boolean {
102 if (isProviderCommandNotFoundError(error)) return true;
103 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
105​
106export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (
107 binaryPath: string,
108 command: ChildProcess.Command,
109) {
110 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
111 const child = yield* spawner.spawn(command);
112 const [stdout, stderr, exitCode] = yield* Effect.all(
113 [
114 collectStreamAsString(child.stdout),
115 collectStreamAsString(child.stderr),
116 child.exitCode.pipe(Effect.map(Number)),
117 ],
118 { concurrency: "unbounded" },
119 );
120​
121 const result: CommandResult = { stdout, stderr, code: exitCode };
122 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
123 return yield* new ProviderCommandNotFoundError({
124 binaryPath,
125 exitCode,
126 stdoutLength: stdout.length,
127 stderrLength: stderr.length,
128 });
129 }
130 return result;
131}, Effect.scoped);
132​
133export function parseGenericCliVersion(output: string): string | null {
134 // Consume v before the digits; v2 has no internal word boundary.
135 const match = output.match(/\bv?(\d+\.\d+\.\d+)\b/);
136 return match?.[1] ?? null;
138​
139export function providerModelsFromSettings(
140 builtInModels: ReadonlyArray<ServerProviderModel>,
141 customModels: ReadonlyArray<CustomModelSetting>,
142 customModelCapabilities: ModelCapabilities | null,
143): ReadonlyArray<ServerProviderModel> {
144 const entries = readCustomModelEntries(customModels);
145 if (entries.length === 0) return builtInModels;
146​
147 const nameOverrides = new Map(
148 entries.filter((entry) => entry.name !== entry.slug).map((entry) => [entry.slug, entry.name]),
149 );
150 const resolvedBuiltInModels = builtInModels.map((model) => {
151 const name = nameOverrides.get(model.slug);
152 if (!name) return model;
153 const { shortName: _shortName, ...rest } = model;
154 return { ...rest, name };
155 });
156 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
157 const customEntries: ServerProviderModel[] = [];
158​
159 for (const entry of entries) {
160 if (seen.has(entry.slug)) {
161 continue;
162 }
163 seen.add(entry.slug);
164 customEntries.push({
165 slug: entry.slug,
166 name: entry.name,
167 isCustom: true,
168 capabilities: entry.capabilities ?? customModelCapabilities,
169 });
170 }
171​
172 return [...resolvedBuiltInModels, ...customEntries];
174​
175export function buildSelectOptionDescriptor(input: {
176 readonly id: string;
177 readonly label: string;
178 readonly options:
179 | ReadonlyArray<{
180 value: string;
181 label: string;
182 description?: string | undefined;
183 isDefault?: boolean | undefined;
184 }>
185 | undefined;
186 readonly description?: string;
187 readonly promptInjectedValues?: ReadonlyArray<string>;
188}) {
189 const options = (input.options ?? []).map((option) => ({
190 id: option.value,
191 label: option.label,
192 ...(option.description ? { description: option.description } : {}),
193 ...(option.isDefault ? { isDefault: true } : {}),
194 }));
195 const currentValue = options.find((option) => option.isDefault)?.id;
196 return {
197 id: input.id,
198 label: input.label,
199 type: "select" as const,
200 options,
201 ...(currentValue ? { currentValue } : {}),
202 ...(input.description ? { description: input.description } : {}),
203 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
204 ? { promptInjectedValues: [...input.promptInjectedValues] }
205 : {}),
206 };
208​
209export function buildBooleanOptionDescriptor(input: {
210 readonly id: string;
211 readonly label: string;
212 readonly currentValue?: boolean;
213 readonly description?: string;
214}) {
215 return {
216 id: input.id,
217 label: input.label,
218 type: "boolean" as const,
219 ...(input.description ? { description: input.description } : {}),
220 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
221 };
223​
224export function buildServerProvider(input: {
225 driver?: ProviderDriverKind;
226 presentation: ServerProviderPresentation;
227 enabled: boolean;
228 checkedAt: string;
229 models: ReadonlyArray<ServerProviderModel>;
230 updateRequiredModels?: ReadonlyArray<ServerProviderUpdateRequiredModel>;
231 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
232 skills?: ReadonlyArray<ServerProviderSkill>;
233 probe: ProviderProbeResult;
234}): ServerProviderDraft {
235 const versionAdvisory = input.driver
236 ? createProviderVersionAdvisory({
237 driver: input.driver,
238 currentVersion: input.probe.version,
239 checkedAt: input.checkedAt,
240 })
241 : undefined;
242 return {
243 displayName: input.presentation.displayName,
244 ...(typeof input.presentation.supportsConversationRollback === "boolean"
245 ? { supportsConversationRollback: input.presentation.supportsConversationRollback }
246 : {}),
247 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
248 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
249 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
250 : {}),
251 ...(typeof input.presentation.reportsContextWindow === "boolean"
252 ? { reportsContextWindow: input.presentation.reportsContextWindow }
253 : {}),
254 ...(input.presentation.supportedRuntimeModes === undefined
255 ? {}
256 : { supportedRuntimeModes: [...input.presentation.supportedRuntimeModes] }),
257 enabled: input.enabled,
258 installed: input.probe.installed,
259 version: input.probe.version,
260 status: input.enabled ? input.probe.status : "disabled",
261 auth: input.probe.auth,
262 // Drivers with in-app setup replace these CLI-owned defaults.
263 setup: { canAuthenticate: false, canInstall: false },
264 checkedAt: input.checkedAt,
265 ...(input.probe.message ? { message: input.probe.message } : {}),
266 models: input.models,
267 ...(input.updateRequiredModels?.length
268 ? { updateRequiredModels: input.updateRequiredModels }
269 : {}),
270 slashCommands: [...(input.slashCommands ?? [])],
271 skills: [...(input.skills ?? [])],
272 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
273 ...(versionAdvisory ? { versionAdvisory } : {}),
274 };
276​
277export const collectStreamAsString = <E>(
278 stream: Stream.Stream<Uint8Array, E>,
279 options?: { readonly maxBytes?: number | undefined },
280): Effect.Effect<string, E> =>
281 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));