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

status.ts

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