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

providerSnapshot.ts

251 lines8.7 KB

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