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