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