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

status.ts

480 lines15.0 KB

1import {
2 type CustomModelSetting,
3 type ServerProvider,
4 type ServerProviderModel,
5} from "@t3tools/contracts";
6import type { PiSettings } from "../settings.ts";
7import { causeErrorTag } from "@t3tools/shared/observability";
8import { resolveSpawnCommand } from "@t3tools/shared/shell";
9import { compareSemverVersions } from "@t3tools/shared/semver";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Stream from "effect/Stream";
13import * as Exit from "effect/Exit";
14import * as Option from "effect/Option";
15import * as Result from "effect/Result";
16import * as HttpClient from "effect/http/HttpClient";
17import * as ChildProcess from "effect/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19​
20import { buildPiRpcLaunch, resolvePiLaunchArgs } from "./mcpInjection.ts";
21import {
22 makePiRpcConnection,
23 PiRpcError,
24 PiRpcTimeoutError,
25 piRecordField as recordField,
26 piRecordString as recordString,
27} from "./rpc.ts";
28import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
29import {
30 buildServerProvider,
31 isCommandMissingCause,
32 parseGenericCliVersion,
33 providerModelsFromSettings,
34 spawnAndCollect,
35 type ServerProviderDraft,
36} from "@t3tools/provider-core/server/snapshotProbe";
37import {
38 enrichProviderSnapshotWithVersionAdvisory,
39 type ProviderMaintenanceCapabilities,
40} from "@t3tools/provider-core/server/maintenanceResolver";
41import {
42 EMPTY_PI_MODEL_CAPABILITIES,
43 thinkingCapabilitiesForPiModel,
44} from "./thinkingCapabilities.ts";
45import {
46 parsePiDiscoveredCommands,
47 withPiBuiltinSlashCommands,
48 type PiDiscoveredCommands,
49} from "./commands.ts";
50​
51const PI_PRESENTATION = {
52 displayName: "Pi",
53 showInteractionModeToggle: false,
54 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
55 reportsContextWindow: true,
56 requiresNewThreadForModelChange: false,
57} as const;
58​
59const VERSION_PROBE_TIMEOUT_MS = 4_000;
60const PI_RPC_DISCOVERY_TIMEOUT_MS = 30_000;
61/**
62 * get_entries arrived in 0.80.3 and agent_settled landed in source at 0.80.4.
63 * Version 0.80.5 was the first published package containing both hooks.
64 */
65export const MINIMUM_PI_VERSION = "0.80.5";
66​
67const PI_DEFAULT_MODEL: ServerProviderModel = {
68 slug: "default",
69 name: "Pi default",
70 isCustom: false,
71 capabilities: EMPTY_PI_MODEL_CAPABILITIES,
72};
73​
74interface PiDiscovery extends PiDiscoveredCommands {
75 readonly models: ReadonlyArray<ServerProviderModel>;
76 readonly authenticated: boolean;
78​
79function piModelsFromSettings(
80 customModels: ReadonlyArray<CustomModelSetting> | undefined,
81 discovered: ReadonlyArray<ServerProviderModel> = [],
82): ReadonlyArray<ServerProviderModel> {
83 return providerModelsFromSettings(
84 [PI_DEFAULT_MODEL, ...discovered],
85 customModels ?? [],
86 EMPTY_PI_MODEL_CAPABILITIES,
87 );
89​
90function parseDiscoveredModels(
91 data: unknown,
92 state: unknown,
93): Result.Result<ReadonlyArray<ServerProviderModel>, PiRpcError> {
94 const models = recordField(data, "models");
95 if (!Array.isArray(models)) {
96 return Result.fail(
97 new PiRpcError({ operation: "get_available_models", detail: "Invalid model inventory" }),
98 );
99 }
100 const activeModel = recordField(state, "model");
101 const activeProvider = recordString(activeModel, "provider");
102 const activeModelId = recordString(activeModel, "id");
103 const seen = new Set<string>();
104 const parsed: Array<ServerProviderModel> = [];
105 for (const model of models) {
106 const provider = recordString(model, "provider");
107 const id = recordString(model, "id");
108 if (provider === undefined || id === undefined || provider.trim() === "" || id.trim() === "") {
109 return Result.fail(
110 new PiRpcError({ operation: "get_available_models", detail: "Invalid model identity" }),
111 );
112 }
113 const slug = `${provider}/${id}`;
114 if (seen.has(slug)) continue;
115 seen.add(slug);
116 parsed.push({
117 slug,
118 name: recordString(model, "name") ?? slug,
119 subProvider: provider,
120 isCustom: false,
121 capabilities: thinkingCapabilitiesForPiModel(
122 model,
123 provider === activeProvider && id === activeModelId
124 ? recordString(state, "thinkingLevel")
125 : undefined,
126 ),
127 });
128 }
129 return Result.succeed(parsed);
131​
132const makePiDiscoveryConnection = Effect.fnUntraced(function* (
133 piSettings: PiSettings,
134 environment: NodeJS.ProcessEnv,
135 launchArgs: ReadonlyArray<string>,
136 cwd?: string,
137) {
138 const launch = buildPiRpcLaunch({
139 launchArgs,
140 environment,
141 mcpSession: undefined,
142 extensionPath: undefined,
143 ephemeral: true,
144 });
145 const connection = yield* makePiRpcConnection({
146 command: piSettings.binaryPath || "pi",
147 args: launch.args,
148 cwd,
149 env: launch.env,
150 });
151 yield* Stream.fromQueue(connection.events).pipe(
152 Stream.runDrain,
153 Effect.ignore,
154 Effect.forkScoped,
155 );
156 return connection;
157});
158​
159const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (
160 piSettings: PiSettings,
161 environment: NodeJS.ProcessEnv,
162 launchArgs: ReadonlyArray<string>,
163 cwd?: string,
164) {
165 const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
166 const stateData = yield* connection.request({ type: "get_state" });
167 const modelsData = yield* connection.request({ type: "get_available_models" });
168 const commandsData = yield* connection
169 .request({ type: "get_commands" })
170 .pipe(Effect.orElseSucceed(() => undefined));
171 const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
172 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
173 return {
174 models: discoveredModels,
175 slashCommands: withPiBuiltinSlashCommands(slashCommands),
176 skills,
177 authenticated: discoveredModels.length > 0,
178 } satisfies PiDiscovery;
179}, Effect.scoped);
180​
181export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
182 function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {
183 const launchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
184 if (!launchArgs.ok) {
185 return yield* new PiRpcError({ operation: "launch", detail: launchArgs.message });
186 }
187 const connection = yield* makePiDiscoveryConnection(
188 piSettings,
189 environment,
190 launchArgs.args,
191 cwd,
192 );
193 // A failed read must not replace a previously usable workspace catalog with an empty one.
194 const commandsData = yield* connection.request({ type: "get_commands" });
195 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
196 return { slashCommands: withPiBuiltinSlashCommands(slashCommands), skills };
197 },
198 Effect.scoped,
199 Effect.timeoutOrElse({
200 duration: PI_RPC_DISCOVERY_TIMEOUT_MS,
201 orElse: () =>
202 Effect.fail(
203 new PiRpcTimeoutError({ operation: "discovery", timeoutMs: PI_RPC_DISCOVERY_TIMEOUT_MS }),
204 ),
205 }),
206);
207​
208const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (
209 piSettings: PiSettings,
210 environment: NodeJS.ProcessEnv,
211) {
212 const command = piSettings.binaryPath || "pi";
213 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
214 env: environment,
215 });
216 return yield* spawnAndCollect(
217 command,
218 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
219 env: environment,
220 shell: spawnCommand.shell,
221 }),
222 );
223});
224​
225export const buildInitialPiProviderSnapshot = Effect.fn(
226 "PiProviderStatus.buildInitialPiProviderSnapshot",
227)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {
228 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
229 const models = piModelsFromSettings(piSettings.customModels);
230 if (!piSettings.enabled) {
231 return buildServerProvider({
232 presentation: PI_PRESENTATION,
233 enabled: false,
234 checkedAt,
235 models,
236 probe: {
237 installed: false,
238 version: null,
239 status: "warning",
240 auth: { status: "unknown" },
241 message: "Pi is disabled in T3 Code settings.",
242 },
243 });
244 }
245 return buildServerProvider({
246 presentation: PI_PRESENTATION,
247 enabled: true,
248 checkedAt,
249 models,
250 probe: {
251 installed: true,
252 version: null,
253 status: "warning",
254 auth: { status: "unknown" },
255 message: "Checking Pi CLI availability...",
256 },
257 });
258});
259​
260export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
261 piSettings: PiSettings,
262 environment: NodeJS.ProcessEnv = process.env,
263 cwd?: string,
264): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
265 const checkedAt = DateTime.formatIso(yield* DateTime.now);
266 const fallbackModels = piModelsFromSettings(piSettings.customModels);
267​
268 if (!piSettings.enabled) {
269 return buildServerProvider({
270 presentation: PI_PRESENTATION,
271 enabled: false,
272 checkedAt,
273 models: fallbackModels,
274 probe: {
275 installed: false,
276 version: null,
277 status: "warning",
278 auth: { status: "unknown" },
279 message: "Pi is disabled in T3 Code settings.",
280 },
281 });
282 }
283​
284 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
285 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
286 Effect.result,
287 );
288​
289 if (Result.isFailure(versionResult)) {
290 const error = versionResult.failure;
291 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
292 return buildServerProvider({
293 presentation: PI_PRESENTATION,
294 enabled: piSettings.enabled,
295 checkedAt,
296 models: fallbackModels,
297 probe: {
298 installed: !isCommandMissingCause(error),
299 version: null,
300 status: "error",
301 auth: { status: "unknown" },
302 message: isCommandMissingCause(error)
303 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`."
304 : "Failed to execute Pi CLI health check.",
305 },
306 });
307 }
308​
309 if (Option.isNone(versionResult.success)) {
310 return buildServerProvider({
311 presentation: PI_PRESENTATION,
312 enabled: piSettings.enabled,
313 checkedAt,
314 models: fallbackModels,
315 probe: {
316 installed: true,
317 version: null,
318 status: "error",
319 auth: { status: "unknown" },
320 message: "Pi CLI is installed but timed out while running `pi --version`.",
321 },
322 });
323 }
324​
325 const versionOutput = versionResult.success.value;
326 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
327 if (versionOutput.code !== 0) {
328 return buildServerProvider({
329 presentation: PI_PRESENTATION,
330 enabled: piSettings.enabled,
331 checkedAt,
332 models: fallbackModels,
333 probe: {
334 installed: true,
335 version,
336 status: "error",
337 auth: { status: "unknown" },
338 message: "Pi CLI is installed but failed to run.",
339 },
340 });
341 }
342​
343 if (version === null) {
344 return buildServerProvider({
345 presentation: PI_PRESENTATION,
346 enabled: piSettings.enabled,
347 checkedAt,
348 models: fallbackModels,
349 probe: {
350 installed: true,
351 version: null,
352 status: "error",
353 auth: { status: "unknown" },
354 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
355 },
356 });
357 }
358​
359 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
360 return buildServerProvider({
361 presentation: PI_PRESENTATION,
362 enabled: piSettings.enabled,
363 checkedAt,
364 models: fallbackModels,
365 probe: {
366 installed: true,
367 version,
368 status: "error",
369 auth: { status: "unknown" },
370 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
371 },
372 });
373 }
374​
375 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
376 if (!resolvedLaunchArgs.ok) {
377 return buildServerProvider({
378 presentation: PI_PRESENTATION,
379 enabled: piSettings.enabled,
380 checkedAt,
381 models: fallbackModels,
382 probe: {
383 installed: true,
384 version,
385 status: "error",
386 auth: { status: "unknown" },
387 message: resolvedLaunchArgs.message,
388 },
389 });
390 }
391​
392 const discoveryExit = yield* discoverPiViaRpc(
393 piSettings,
394 environment,
395 resolvedLaunchArgs.args,
396 cwd,
397 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
398 if (Exit.isFailure(discoveryExit)) {
399 yield* Effect.logWarning("Pi RPC discovery failed.", {
400 errorTag: causeErrorTag(discoveryExit.cause),
401 });
402 return buildServerProvider({
403 presentation: PI_PRESENTATION,
404 enabled: piSettings.enabled,
405 checkedAt,
406 models: fallbackModels,
407 probe: {
408 installed: true,
409 version,
410 status: "ready",
411 auth: { status: "unknown" },
412 message:
413 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
414 },
415 });
416 }
417 if (Option.isNone(discoveryExit.value)) {
418 return buildServerProvider({
419 presentation: PI_PRESENTATION,
420 enabled: piSettings.enabled,
421 checkedAt,
422 models: fallbackModels,
423 probe: {
424 installed: true,
425 version,
426 status: "ready",
427 auth: { status: "unknown" },
428 message:
429 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
430 },
431 });
432 }
433​
434 const discovery = discoveryExit.value.value;
435 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
436 return buildServerProvider({
437 presentation: PI_PRESENTATION,
438 enabled: piSettings.enabled,
439 checkedAt,
440 models,
441 slashCommands: discovery.slashCommands,
442 skills: discovery.skills,
443 probe: {
444 installed: true,
445 version,
446 status: discovery.authenticated ? "ready" : "warning",
447 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
448 ...(discovery.authenticated
449 ? {}
450 : {
451 message:
452 "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",
453 }),
454 },
455 });
456});
457​
458export const enrichPiSnapshot = (input: {
459 readonly snapshot: ServerProvider;
460 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
461 readonly enableProviderUpdateChecks?: boolean;
462 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
463}): Effect.Effect<
464 void,
465 never,
466 HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions
467> => {
468 const { snapshot, publishSnapshot } = input;
469 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
470 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
471 }).pipe(
472 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
473 Effect.catchCause((cause) =>
474 Effect.logWarning("Pi version advisory enrichment failed", {
475 errorTag: causeErrorTag(cause),
476 }),
477 ),
478 Effect.asVoid,
479 );
480};