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

status.ts

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