Open History to see the last commit
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;
86}
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 );
97}
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);
139}
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 });
154 const connection = yield* makePiRpcConnection({
155 command: piSettings.binaryPath || "pi",
156 args: launch.args,
157 cwd,
158 env: launch.env,
159 });
160 yield* Stream.fromQueue(connection.events).pipe(
161 Stream.runDrain,
162 Effect.ignore,
163 Effect.forkScoped,
164 );
165 return connection;
166});
167
168const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (
169 piSettings: PiSettings,
170 environment: NodeJS.ProcessEnv,
171 launchArgs: ReadonlyArray<string>,
172 cwd?: string,
173) {
174 const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
175 const stateData = yield* connection.request({ type: "get_state" });
176 const modelsData = yield* connection.request({ type: "get_available_models" });
177 const commandsData = yield* connection
178 .request({ type: "get_commands" })
179 .pipe(Effect.orElseSucceed(() => undefined));
180 const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
181 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
182 // Pi lists only models of providers it holds credentials for, including extension, virtual and
183 // --api-key ones. Turns need only the provider's credentials, so uncatalogued model ids still run.
184 const activeModel = recordField(stateData, "model");
185 const activeProvider = recordString(activeModel, "provider");
186 const activeModelId = recordString(activeModel, "id");
187 return {
188 models: discoveredModels,
189 slashCommands: withPiBuiltinSlashCommands(slashCommands),
190 skills,
191 authenticated: discoveredModels.length > 0,
192 unavailableActiveModel:
193 activeProvider !== undefined &&
194 activeModelId !== undefined &&
195 !discoveredModels.some((model) => model.subProvider === activeProvider)
196 ? { provider: activeProvider, id: activeModelId }
197 : undefined,
198 } satisfies PiDiscovery;
199}, Effect.scoped);
200
201export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
202 function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {
203 const launchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
204 if (!launchArgs.ok) {
205 return yield* new PiRpcError({ operation: "launch", detail: launchArgs.message });
206 }
207 const connection = yield* makePiDiscoveryConnection(
208 piSettings,
209 environment,
210 launchArgs.args,
211 cwd,
212 );
213 // A failed read must not replace a previously usable workspace catalog with an empty one.
214 const commandsData = yield* connection.request({ type: "get_commands" });
215 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
216 return { slashCommands: withPiBuiltinSlashCommands(slashCommands), skills };
217 },
218 Effect.scoped,
219 Effect.timeoutOrElse({
220 duration: PI_RPC_DISCOVERY_TIMEOUT_MS,
221 orElse: () =>
222 Effect.fail(
223 new PiRpcTimeoutError({ operation: "discovery", timeoutMs: PI_RPC_DISCOVERY_TIMEOUT_MS }),
224 ),
225 }),
226);
227
228const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (
229 piSettings: PiSettings,
230 environment: NodeJS.ProcessEnv,
231) {
232 const command = piSettings.binaryPath || "pi";
233 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
234 env: environment,
235 });
236 return yield* spawnAndCollect(
237 command,
238 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
239 env: environment,
240 shell: spawnCommand.shell,
241 }),
242 );
243});
244
245/**
246 * Explains why Pi's active model cannot start a turn. On Pi versions with `auth check`, asks it
247 * whether credentials are missing, without refreshing or printing them. That command cannot see
248 * extension providers or a runtime --api-key, so it only refines Pi's own unavailable verdict,
249 * and is skipped when launch args supply the key.
250 */
251const describeUnavailablePiModel = Effect.fn("PiProviderStatus.describeUnavailablePiModel")(
252 function* (
253 piSettings: PiSettings,
254 environment: NodeJS.ProcessEnv,
255 version: string,
256 launchArgs: ReadonlyArray<string>,
257 model: { readonly provider: string; readonly id: string },
258 ) {
259 const label = `Pi default (${model.provider}/${model.id})`;
260 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.`;
261 if (
262 compareSemverVersions(version, PI_AUTH_CHECK_VERSION) < 0 ||
263 launchArgs.includes("--api-key")
264 ) {
265 return unavailable;
266 }
267 const command = piSettings.binaryPath || "pi";
268 const output = yield* resolveSpawnCommand(
269 command,
270 ["auth", "check", "--provider", model.provider, "--json", "--no-refresh"],
271 { env: environment },
272 ).pipe(
273 Effect.flatMap((spawnCommand) =>
274 spawnAndCollect(
275 command,
276 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
277 env: environment,
278 shell: spawnCommand.shell,
279 }),
280 ),
281 ),
282 Effect.timeout(DEFAULT_TIMEOUT_MS),
283 Effect.option,
284 );
285 const missingCredentials = Option.exists(
286 Option.flatMap(output, (result) => decodePiAuthCheck(result.stdout)),
287 (check) => check.reason === "credentials_not_configured",
288 );
289 return missingCredentials
290 ? `${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.`
291 : unavailable;
292 },
293);
294
295export const buildInitialPiProviderSnapshot = Effect.fn(
296 "PiProviderStatus.buildInitialPiProviderSnapshot",
297)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {
298 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
299 const models = piModelsFromSettings(piSettings.customModels);
300 if (!piSettings.enabled) {
301 return buildServerProvider({
302 presentation: PI_PRESENTATION,
303 enabled: false,
304 checkedAt,
305 models,
306 probe: {
307 installed: false,
308 version: null,
309 status: "warning",
310 auth: { status: "unknown" },
311 message: "Pi is disabled in T3 Code settings.",
312 },
313 });
314 }
315 return buildServerProvider({
316 presentation: PI_PRESENTATION,
317 enabled: true,
318 checkedAt,
319 models,
320 probe: {
321 installed: true,
322 version: null,
323 status: "warning",
324 auth: { status: "unknown" },
325 message: "Checking Pi CLI availability...",
326 },
327 });
328});
329
330export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
331 piSettings: PiSettings,
332 environment: NodeJS.ProcessEnv = process.env,
333 cwd?: string,
334): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
335 const checkedAt = DateTime.formatIso(yield* DateTime.now);
336 const fallbackModels = piModelsFromSettings(piSettings.customModels);
337
338 if (!piSettings.enabled) {
339 return buildServerProvider({
340 presentation: PI_PRESENTATION,
341 enabled: false,
342 checkedAt,
343 models: fallbackModels,
344 probe: {
345 installed: false,
346 version: null,
347 status: "warning",
348 auth: { status: "unknown" },
349 message: "Pi is disabled in T3 Code settings.",
350 },
351 });
352 }
353
354 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
355 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
356 Effect.result,
357 );
358
359 if (Result.isFailure(versionResult)) {
360 const error = versionResult.failure;
361 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
362 return buildServerProvider({
363 presentation: PI_PRESENTATION,
364 enabled: piSettings.enabled,
365 checkedAt,
366 models: fallbackModels,
367 probe: {
368 installed: !isCommandMissingCause(error),
369 version: null,
370 status: "error",
371 auth: { status: "unknown" },
372 message: isCommandMissingCause(error)
373 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`."
374 : "Failed to execute Pi CLI health check.",
375 },
376 });
377 }
378
379 if (Option.isNone(versionResult.success)) {
380 return buildServerProvider({
381 presentation: PI_PRESENTATION,
382 enabled: piSettings.enabled,
383 checkedAt,
384 models: fallbackModels,
385 probe: {
386 installed: true,
387 version: null,
388 status: "error",
389 auth: { status: "unknown" },
390 message: "Pi CLI is installed but timed out while running `pi --version`.",
391 },
392 });
393 }
394
395 const versionOutput = versionResult.success.value;
396 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
397 if (versionOutput.code !== 0) {
398 return buildServerProvider({
399 presentation: PI_PRESENTATION,
400 enabled: piSettings.enabled,
401 checkedAt,
402 models: fallbackModels,
403 probe: {
404 installed: true,
405 version,
406 status: "error",
407 auth: { status: "unknown" },
408 message: "Pi CLI is installed but failed to run.",
409 },
410 });
411 }
412
413 if (version === null) {
414 return buildServerProvider({
415 presentation: PI_PRESENTATION,
416 enabled: piSettings.enabled,
417 checkedAt,
418 models: fallbackModels,
419 probe: {
420 installed: true,
421 version: null,
422 status: "error",
423 auth: { status: "unknown" },
424 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
425 },
426 });
427 }
428
429 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
430 return buildServerProvider({
431 presentation: PI_PRESENTATION,
432 enabled: piSettings.enabled,
433 checkedAt,
434 models: fallbackModels,
435 probe: {
436 installed: true,
437 version,
438 status: "error",
439 auth: { status: "unknown" },
440 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
441 },
442 });
443 }
444
445 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
446 if (!resolvedLaunchArgs.ok) {
447 return buildServerProvider({
448 presentation: PI_PRESENTATION,
449 enabled: piSettings.enabled,
450 checkedAt,
451 models: fallbackModels,
452 probe: {
453 installed: true,
454 version,
455 status: "error",
456 auth: { status: "unknown" },
457 message: resolvedLaunchArgs.message,
458 },
459 });
460 }
461
462 const discoveryExit = yield* discoverPiViaRpc(
463 piSettings,
464 environment,
465 resolvedLaunchArgs.args,
466 cwd,
467 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
468 if (Exit.isFailure(discoveryExit)) {
469 yield* Effect.logWarning("Pi RPC discovery failed.", {
470 errorTag: causeErrorTag(discoveryExit.cause),
471 });
472 return buildServerProvider({
473 presentation: PI_PRESENTATION,
474 enabled: piSettings.enabled,
475 checkedAt,
476 models: fallbackModels,
477 probe: {
478 installed: true,
479 version,
480 status: "ready",
481 auth: { status: "unknown" },
482 message:
483 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
484 },
485 });
486 }
487 if (Option.isNone(discoveryExit.value)) {
488 return buildServerProvider({
489 presentation: PI_PRESENTATION,
490 enabled: piSettings.enabled,
491 checkedAt,
492 models: fallbackModels,
493 probe: {
494 installed: true,
495 version,
496 status: "ready",
497 auth: { status: "unknown" },
498 message:
499 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
500 },
501 });
502 }
503
504 const discovery = discoveryExit.value.value;
505 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
506 const message = !discovery.authenticated
507 ? "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent."
508 : discovery.unavailableActiveModel === undefined
509 ? undefined
510 : yield* describeUnavailablePiModel(
511 piSettings,
512 environment,
513 version,
514 resolvedLaunchArgs.args,
515 discovery.unavailableActiveModel,
516 );
517 return buildServerProvider({
518 presentation: PI_PRESENTATION,
519 enabled: piSettings.enabled,
520 checkedAt,
521 models,
522 slashCommands: discovery.slashCommands,
523 skills: discovery.skills,
524 probe: {
525 installed: true,
526 version,
527 // Other Pi models still work when only the default is unavailable, so keep the picker usable.
528 status: discovery.authenticated ? "ready" : "warning",
529 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
530 ...(message === undefined ? {} : { message }),
531 },
532 });
533});
534
535export const enrichPiSnapshot = (input: {
536 readonly snapshot: ServerProvider;
537 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
538 readonly enableProviderUpdateChecks?: boolean;
539 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
540}): Effect.Effect<
541 void,
542 never,
543 HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions
544> => {
545 const { snapshot, publishSnapshot } = input;
546 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
547 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
548 }).pipe(
549 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
550 Effect.catchCause((cause) =>
551 Effect.logWarning("Pi version advisory enrichment failed", {
552 errorTag: causeErrorTag(cause),
553 }),
554 ),
555 Effect.asVoid,
556 );
557};