The best way to control Claude Code, Codex and more from any computer or phone

main
ts 347 lines 12.6 KB
Raw
1 import 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";
15 import * as Effect from "effect/Effect";
16 import * as PlatformError from "effect/PlatformError";
17 import * as Schema from "effect/Schema";
18 import * as Stream from "effect/Stream";
19 import * as ChildProcess from "effect/process/ChildProcess";
20 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21 import { readCustomModelEntries } from "@t3tools/shared/model";
22 import * as HostProcess from "@t3tools/shared/HostProcess";
23 import { createProviderVersionAdvisory } from "./maintenanceResolver.ts";
24 import { collectUint8StreamText } from "./collectStreamText.ts";
25
26 const 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
35 export 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
45 export const DEFAULT_TIMEOUT_MS = 4_000;
46 export const AUTH_PROBE_TIMEOUT_MS = 10_000;
47
48 export const resolveProviderProbeTimeoutMs = (
49 provider: string,
50 defaultTimeoutMs: number,
51 environment: NodeJS.ProcessEnv = process.env,
52 ): number => {
53 const timeoutMs = Number(environment[`T3CODE_${provider.toUpperCase()}_PROBE_TIMEOUT_MS`]);
54 // Overrides only extend: callers nest these deadlines and size optional work inside them
55 // against the defaults. Node timers overflow above a signed 32-bit delay.
56 return Number.isInteger(timeoutMs) && timeoutMs > defaultTimeoutMs && timeoutMs <= 2_147_483_647
57 ? timeoutMs
58 : defaultTimeoutMs;
59 };
60
61 export const COMPACT_SLASH_COMMAND = {
62 name: "compact",
63 description: "Summarize the conversation and reduce context usage",
64 } satisfies ServerProviderSlashCommand;
65
66 export interface CommandResult {
67 readonly stdout: string;
68 readonly stderr: string;
69 readonly code: number;
70 }
71
72 export class ProviderCommandNotFoundError extends Schema.TaggedError<ProviderCommandNotFoundError>()(
73 "ProviderCommandNotFoundError",
74 {
75 binaryPath: Schema.String,
76 exitCode: Schema.Number,
77 stdoutLength: Schema.Number,
78 stderrLength: Schema.Number,
79 },
80 ) {
81 override get message(): string {
82 return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;
83 }
84 }
85
86 const isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);
87
88 export class ProviderProbeOutputLimitError extends Schema.TaggedError<
89 ProviderProbeOutputLimitError,
90 { readonly brand: unique symbol }
91 >()("ProviderProbeOutputLimitError", {
92 stream: Schema.Literals(["stdout", "stderr"]),
93 maxBytes: Schema.Number,
94 }) {
95 override get message(): string {
96 return `Provider status check produced too much ${this.stream} (limit ${this.maxBytes} bytes). Check the configured executable or wrapper in this environment's terminal.`;
97 }
98 }
99
100 export interface ProviderProbeResult {
101 readonly installed: boolean;
102 readonly version: string | null;
103 readonly status: Exclude<ServerProviderState, "disabled">;
104 readonly auth: ServerProviderAuth;
105 readonly message?: string;
106 readonly usageLimits?: ServerProviderUsageLimits;
107 }
108
109 export interface ServerProviderPresentation {
110 readonly displayName: string;
111 readonly badgeLabel?: string;
112 readonly showInteractionModeToggle?: boolean;
113 readonly reportsContextWindow?: boolean;
114 readonly supportedRuntimeModes?: ReadonlyArray<RuntimeMode>;
115 readonly supportsConversationRollback?: boolean;
116 }
117
118 export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
119
120 export function nonEmptyTrimmed(value: string | undefined): string | undefined {
121 if (!value) return undefined;
122 const trimmed = value.trim();
123 return trimmed.length > 0 ? trimmed : undefined;
124 }
125
126 export function isCommandMissingCause(error: unknown): boolean {
127 if (isProviderCommandNotFoundError(error)) return true;
128 return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
129 }
130
131 /**
132 * Environment for background status probes. A mise shim for a missing tool would otherwise
133 * download it on every refresh and leave a partial download behind when the probe times out.
134 * Sessions and user-started commands keep the plain environment, so mise still installs there.
135 */
136 export function providerProbeEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
137 return { ...environment, MISE_OFFLINE: "1" };
138 }
139
140 // A timed-out probe interrupts the child with SIGTERM and then waits for it to exit,
141 // so a CLI that ignores SIGTERM would hold the caller's timeout open without this.
142 const PROBE_FORCE_KILL_AFTER = "1 second";
143 const MAX_PROBE_OUTPUT_BYTES = 8 * 1024 * 1024;
144
145 function withProbeForceKill(command: ChildProcess.Command): ChildProcess.Command {
146 if (!ChildProcess.isStandardCommand(command) || command.options.forceKillAfter !== undefined) {
147 return command;
148 }
149 return ChildProcess.make(command.command, command.args, {
150 ...command.options,
151 forceKillAfter: PROBE_FORCE_KILL_AFTER,
152 });
153 }
154
155 export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (
156 binaryPath: string,
157 command: ChildProcess.Command,
158 options?: { readonly maxStdoutBytes: number },
159 ) {
160 const maxStdoutBytes = options?.maxStdoutBytes ?? MAX_PROBE_OUTPUT_BYTES;
161 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
162 const child = yield* spawner.spawn(withProbeForceKill(command));
163 const [stdout, stderr, exitCode] = yield* Effect.all(
164 [
165 collectUint8StreamText({ stream: child.stdout, maxBytes: maxStdoutBytes }),
166 collectUint8StreamText({ stream: child.stderr, maxBytes: MAX_PROBE_OUTPUT_BYTES }),
167 child.exitCode.pipe(Effect.map(Number)),
168 ],
169 { concurrency: "unbounded" },
170 );
171
172 const oversized = stdout.truncated ? "stdout" : stderr.truncated ? "stderr" : undefined;
173 if (oversized !== undefined) {
174 return yield* new ProviderProbeOutputLimitError({
175 stream: oversized,
176 maxBytes: oversized === "stdout" ? maxStdoutBytes : MAX_PROBE_OUTPUT_BYTES,
177 });
178 }
179 const result: CommandResult = { stdout: stdout.text, stderr: stderr.text, code: exitCode };
180 if (yield* isWindowsCommandNotFound(exitCode, stderr.text)) {
181 return yield* new ProviderCommandNotFoundError({
182 binaryPath,
183 exitCode,
184 stdoutLength: stdout.text.length,
185 stderrLength: stderr.text.length,
186 });
187 }
188 return result;
189 }, Effect.scoped);
190
191 export function parseGenericCliVersion(output: string): string | null {
192 // Consume v before the digits; v2 has no internal word boundary.
193 const match = output.match(/\bv?(\d+\.\d+\.\d+)\b/);
194 return match?.[1] ?? null;
195 }
196
197 /** A failed `--version` run reports no version: its output can be a wrapper's, such as mise's. */
198 export function parseCliVersionResult(
199 result: CommandResult,
200 parse: (output: string) => string | null = parseGenericCliVersion,
201 ): string | null {
202 return result.code === 0 ? parse(`${result.stdout}\n${result.stderr}`) : null;
203 }
204
205 export function providerModelsFromSettings(
206 builtInModels: ReadonlyArray<ServerProviderModel>,
207 customModels: ReadonlyArray<CustomModelSetting>,
208 customModelCapabilities: ModelCapabilities | null,
209 ): ReadonlyArray<ServerProviderModel> {
210 const entries = readCustomModelEntries(customModels);
211 if (entries.length === 0) return builtInModels;
212
213 const nameOverrides = new Map(
214 entries.filter((entry) => entry.name !== entry.slug).map((entry) => [entry.slug, entry.name]),
215 );
216 const resolvedBuiltInModels = builtInModels.map((model) => {
217 const name = nameOverrides.get(model.slug);
218 if (!name) return model;
219 const { shortName: _shortName, ...rest } = model;
220 return { ...rest, name };
221 });
222 const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
223 const customEntries: ServerProviderModel[] = [];
224
225 for (const entry of entries) {
226 if (seen.has(entry.slug)) {
227 continue;
228 }
229 seen.add(entry.slug);
230 customEntries.push({
231 slug: entry.slug,
232 name: entry.name,
233 isCustom: true,
234 capabilities: entry.capabilities ?? customModelCapabilities,
235 });
236 }
237
238 return [...resolvedBuiltInModels, ...customEntries];
239 }
240
241 export function buildSelectOptionDescriptor(input: {
242 readonly id: string;
243 readonly label: string;
244 readonly options:
245 | ReadonlyArray<{
246 value: string;
247 label: string;
248 description?: string | undefined;
249 isDefault?: boolean | undefined;
250 }>
251 | undefined;
252 readonly description?: string;
253 readonly promptInjectedValues?: ReadonlyArray<string>;
254 }) {
255 const options = (input.options ?? []).map((option) => ({
256 id: option.value,
257 label: option.label,
258 ...(option.description ? { description: option.description } : {}),
259 ...(option.isDefault ? { isDefault: true } : {}),
260 }));
261 const currentValue = options.find((option) => option.isDefault)?.id;
262 return {
263 id: input.id,
264 label: input.label,
265 type: "select" as const,
266 options,
267 ...(currentValue ? { currentValue } : {}),
268 ...(input.description ? { description: input.description } : {}),
269 ...(input.promptInjectedValues && input.promptInjectedValues.length > 0
270 ? { promptInjectedValues: [...input.promptInjectedValues] }
271 : {}),
272 };
273 }
274
275 export function buildBooleanOptionDescriptor(input: {
276 readonly id: string;
277 readonly label: string;
278 readonly currentValue?: boolean;
279 readonly description?: string;
280 }) {
281 return {
282 id: input.id,
283 label: input.label,
284 type: "boolean" as const,
285 ...(input.description ? { description: input.description } : {}),
286 ...(typeof input.currentValue === "boolean" ? { currentValue: input.currentValue } : {}),
287 };
288 }
289
290 export function buildServerProvider(input: {
291 driver?: ProviderDriverKind;
292 presentation: ServerProviderPresentation;
293 enabled: boolean;
294 checkedAt: string;
295 models: ReadonlyArray<ServerProviderModel>;
296 updateRequiredModels?: ReadonlyArray<ServerProviderUpdateRequiredModel>;
297 slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;
298 skills?: ReadonlyArray<ServerProviderSkill>;
299 probe: ProviderProbeResult;
300 }): ServerProviderDraft {
301 const versionAdvisory = input.driver
302 ? createProviderVersionAdvisory({
303 driver: input.driver,
304 currentVersion: input.probe.version,
305 checkedAt: input.checkedAt,
306 })
307 : undefined;
308 return {
309 displayName: input.presentation.displayName,
310 ...(typeof input.presentation.supportsConversationRollback === "boolean"
311 ? { supportsConversationRollback: input.presentation.supportsConversationRollback }
312 : {}),
313 ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),
314 ...(typeof input.presentation.showInteractionModeToggle === "boolean"
315 ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
316 : {}),
317 ...(typeof input.presentation.reportsContextWindow === "boolean"
318 ? { reportsContextWindow: input.presentation.reportsContextWindow }
319 : {}),
320 ...(input.presentation.supportedRuntimeModes === undefined
321 ? {}
322 : { supportedRuntimeModes: [...input.presentation.supportedRuntimeModes] }),
323 enabled: input.enabled,
324 installed: input.probe.installed,
325 version: input.probe.version,
326 status: input.enabled ? input.probe.status : "disabled",
327 auth: input.probe.auth,
328 // Drivers with in-app setup replace these CLI-owned defaults.
329 setup: { canAuthenticate: false, canInstall: false },
330 checkedAt: input.checkedAt,
331 ...(input.probe.message ? { message: input.probe.message } : {}),
332 models: input.models,
333 ...(input.updateRequiredModels?.length
334 ? { updateRequiredModels: input.updateRequiredModels }
335 : {}),
336 slashCommands: [...(input.slashCommands ?? [])],
337 skills: [...(input.skills ?? [])],
338 ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),
339 ...(versionAdvisory ? { versionAdvisory } : {}),
340 };
341 }
342
343 export const collectStreamAsString = <E>(
344 stream: Stream.Stream<Uint8Array, E>,
345 options?: { readonly maxBytes?: number | undefined },
346 ): Effect.Effect<string, E> =>
347 collectUint8StreamText({ stream, ...options }).pipe(Effect.map((collected) => collected.text));