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

providerSnapshot.ts

256 lines8.9 KB

1import type {
2 CustomModelSetting,
3 ProviderDriverKind,
4 ModelCapabilities,
5 RuntimeMode,
6 ServerProvider,
7 ServerProviderAuth,
8 ServerProviderSkill,
9 ServerProviderSlashCommand,
10 ServerProviderModel,
11 ServerProviderState,
12 ServerProviderUsageLimits,
13} from "@t3tools/contracts";
14import * as Effect from "effect/Effect";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17import * as Stream from "effect/Stream";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19import { readCustomModelEntries } from "@t3tools/shared/model";
20import { isWindowsCommandNotFound } from "../processRunner.ts";
21import { createProviderVersionAdvisory } from "./providerMaintenance.ts";
22import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
23​
24export const DEFAULT_TIMEOUT_MS = 4_000;
25// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)
26export const AUTH_PROBE_TIMEOUT_MS = 10_000;
27​
28export const COMPACT_SLASH_COMMAND = {
29 name: "compact",
30 description: "Summarize the conversation and reduce context usage",
31} satisfies ServerProviderSlashCommand;
32​
33export interface CommandResult {
34 readonly stdout: string;
35 readonly stderr: string;
36 readonly code: number;
38​
39export class ProviderCommandNotFoundError extends Schema.TaggedError<ProviderCommandNotFoundError>()(
40 "ProviderCommandNotFoundError",
41 {
42 binaryPath: Schema.String,
43 exitCode: Schema.Number,
44 stdoutLength: Schema.Number,
45 stderrLength: Schema.Number,
46 },
47) {
48 override get message(): string {
49 return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;
50 }
52​
53const isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);
54​
55export interface ProviderProbeResult {
56 readonly installed: boolean;
57 readonly version: string | null;
58 readonly status: Exclude<ServerProviderState, "disabled">;
59 readonly auth: ServerProviderAuth;
60 readonly message?: string;
61 readonly usageLimits?: ServerProviderUsageLimits;
63​
64export interface ServerProviderPresentation {
65 readonly displayName: string;
66 readonly badgeLabel?: string;
67 readonly showInteractionModeToggle?: boolean;
68 readonly reportsContextWindow?: boolean;
69 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
70 readonly requiresNewThreadForModelChange?: boolean;
71 readonly supportsConversationRollback?: boolean;
73​
74export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
75​
76export function nonEmptyTrimmed(value: string | undefined): string | undefined {
77 if (!value) return undefined;
78 const trimmed = value.trim();
79 return trimmed.length > 0 ? trimmed : undefined;
81​
82export function isCommandMissingCause(error: unknown): boolean {
83 if (isProviderCommandNotFoundError(error)) return true;
84 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
86​
87export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
88 Effect.gen(function* () {
89 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
90 const child = yield* spawner.spawn(command);
91 const [stdout, stderr, exitCode] = yield* Effect.all(
92 [
93 collectStreamAsString(child.stdout),
94 collectStreamAsString(child.stderr),
95 child.exitCode.pipe(Effect.map(Number)),
96 ],
97 { concurrency: "unbounded" },
98 );
99​
100 const result: CommandResult = { stdout, stderr, code: exitCode };
101 if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
102 return yield* new ProviderCommandNotFoundError({
103 binaryPath,
104 exitCode,
105 stdoutLength: stdout.length,
106 stderrLength: stderr.length,
107 });
108 }
109 return result;
110 }).pipe(Effect.scoped);
111​
112/**
113 * Return the first semantic version found in CLI output, or null. Accepts a
114 * leading "v" (for example `opencode v2.0.3`).
115 */
116export function parseGenericCliVersion(output: string): string | null {
117 // "opencode v2.0.3"-style output: the optional "v" has to be consumed first,
118 // since "v2" itself contains no word boundary.
119 const match = output.match(/\bv?(\d+\.\d+\.\d+)\b/);
120 return match?.[1] ?? null;
122​
123/**
124 * Append the user's custom models after the built-ins. A custom entry that
125 * declares its own capabilities keeps them; a bare slug gets the driver's
126 * default set. Slugs that collide with a built-in are dropped.
127 */
128export function providerModelsFromSettings(
129 builtInModels: ReadonlyArray<ServerProviderModel>,
130 customModels: ReadonlyArray<CustomModelSetting>,
131 customModelCapabilities: ModelCapabilities,
132): ReadonlyArray<ServerProviderModel> {
133 const resolvedBuiltInModels = [...builtInModels];
134 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
135 const customEntries: ServerProviderModel[] = [];
136​
137 for (const entry of readCustomModelEntries(customModels)) {
138 if (seen.has(entry.slug)) {
139 continue;
140 }
141 seen.add(entry.slug);
142 customEntries.push({
143 slug: entry.slug,
144 name: entry.name,
145 isCustom: true,
146 capabilities: entry.capabilities ?? customModelCapabilities,
147 });
148 }
149​
150 return [...resolvedBuiltInModels, ...customEntries];
152​
153export function buildSelectOptionDescriptor(input: {
154 readonly id: string;
155 readonly label: string;
156 readonly options:
157 | ReadonlyArray<{
158 value: string;
159 label: string;
160 description?: string | undefined;
161 isDefault?: boolean | undefined;
162 }>
163 | undefined;
164 readonly description?: string;
165 readonly promptInjectedValues?: ReadonlyArray<string>;
166}) {
167 const options = (input.options ?? []).map((option) => ({
168 id: option.value,
169 label: option.label,
170 ...(option.description ? { description: option.description } : {}),
171 ...(option.isDefault ? { isDefault: true } : {}),
172 }));
173 const currentValue = options.find((option) => option.isDefault)?.id;
174 return {
175 id: input.id,
176 label: input.label,
177 type: "select" as const,
178 options,
179 ...(currentValue ? { currentValue } : {}),
180 ...(input.description ? { description: input.description } : {}),
181 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
182 ? { promptInjectedValues: [...input.promptInjectedValues] }
183 : {}),
184 };
186​
187export function buildBooleanOptionDescriptor(input: {
188 readonly id: string;
189 readonly label: string;
190 readonly currentValue?: boolean;
191 readonly description?: string;
192}) {
193 return {
194 id: input.id,
195 label: input.label,
196 type: "boolean" as const,
197 ...(input.description ? { description: input.description } : {}),
198 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
199 };
201​
202export function buildServerProvider(input: {
203 driver?: ProviderDriverKind;
204 presentation: ServerProviderPresentation;
205 enabled: boolean;
206 checkedAt: string;
207 models: ReadonlyArray<ServerProviderModel>;
208 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
209 skills?: ReadonlyArray<ServerProviderSkill>;
210 probe: ProviderProbeResult;
211}): ServerProviderDraft {
212 const versionAdvisory = input.driver
213 ? createProviderVersionAdvisory({
214 driver: input.driver,
215 currentVersion: input.probe.version,
216 checkedAt: input.checkedAt,
217 })
218 : undefined;
219 return {
220 displayName: input.presentation.displayName,
221 ...(typeof input.presentation.supportsConversationRollback === "boolean"
222 ? { supportsConversationRollback: input.presentation.supportsConversationRollback }
223 : {}),
224 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
225 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
226 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
227 : {}),
228 ...(typeof input.presentation.reportsContextWindow === "boolean"
229 ? { reportsContextWindow: input.presentation.reportsContextWindow }
230 : {}),
231 ...(input.presentation.supportedRuntimeModes === undefined
232 ? {}
233 : { supportedRuntimeModes: [...input.presentation.supportedRuntimeModes] }),
234 ...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
235 ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
236 : {}),
237 enabled: input.enabled,
238 installed: input.probe.installed,
239 version: input.probe.version,
240 status: input.enabled ? input.probe.status : "disabled",
241 auth: input.probe.auth,
242 checkedAt: input.checkedAt,
243 ...(input.probe.message ? { message: input.probe.message } : {}),
244 models: input.models,
245 slashCommands: [...(input.slashCommands ?? [])],
246 skills: [...(input.skills ?? [])],
247 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
248 ...(versionAdvisory ? { versionAdvisory } : {}),
249 };
251​
252export const collectStreamAsString = <E>(
253 stream: Stream.Stream<Uint8Array, E>,
254 options?: { readonly maxBytes?: number | undefined },
255): Effect.Effect<string, E> =>
256 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));