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 PiSettings,
14 type ServerProvider,
15 type ServerProviderModel,
16} from "@t3tools/contracts";
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/unstable/http";
27import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
28
29import { buildPiRpcLaunch, resolvePiLaunchArgs } from "../piT3McpInjection.ts";
30import {
31 makePiRpcConnection,
32 PiRpcError,
33 piRecordField as recordField,
34 piRecordString as recordString,
35} from "../PiRpc.ts";
36import {
37 buildServerProvider,
38 isCommandMissingCause,
39 parseGenericCliVersion,
40 providerModelsFromSettings,
41 spawnAndCollect,
42 type ServerProviderDraft,
43 type ServerProviderPresentation,
44} from "../providerSnapshot.ts";
45import {
46 enrichProviderSnapshotWithVersionAdvisory,
47 type ProviderMaintenanceCapabilities,
48} from "../providerMaintenance.ts";
49import {
50 EMPTY_PI_MODEL_CAPABILITIES,
51 thinkingCapabilitiesForPiModel,
52} from "./piThinkingCapabilities.ts";
53import {
54 parsePiDiscoveredCommands,
55 withPiBuiltinSlashCommands,
56 type PiDiscoveredCommands,
57} from "../PiCommands.ts";
58
59const PI_PRESENTATION = {
60 displayName: "Pi",
61 badgeLabel: "Early Access",
62 showInteractionModeToggle: false,
63 // The adapter reports context usage from each Pi response while a turn
64 // runs, so clients can reserve the meter before the first settle.
65 reportsContextWindow: true,
66 requiresNewThreadForModelChange: false,
67} as const satisfies ServerProviderPresentation;
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 isCustom: false,
121 capabilities: thinkingCapabilitiesForPiModel(model, defaultThinkingLevel),
122 });
123 }
124 return parsed;
125}
126
127/** A scoped `pi --mode rpc --no-session` whose session events are drained unread. */
128const openPiDiscoveryConnection = (
129 piSettings: PiSettings,
130 environment: NodeJS.ProcessEnv,
131 launchArgs: ReadonlyArray<string>,
132 cwd: string | undefined,
133) =>
134 Effect.gen(function* () {
135 const launch = buildPiRpcLaunch({
136 launchArgs,
137 environment,
138 mcpSession: undefined,
139 extensionPath: undefined,
140 ephemeral: true,
141 });
142 const connection = yield* makePiRpcConnection({
143 command: piSettings.binaryPath || "pi",
144 args: launch.args,
145 cwd,
146 env: launch.env,
147 });
148 yield* Stream.fromQueue(connection.events).pipe(
149 Stream.runDrain,
150 Effect.ignore,
151 Effect.forkScoped,
152 );
153 return connection;
154 });
155
156const discoverPiViaRpc = (
157 piSettings: PiSettings,
158 environment: NodeJS.ProcessEnv,
159 launchArgs: ReadonlyArray<string>,
160 cwd?: string,
161) =>
162 Effect.gen(function* () {
163 const connection = yield* openPiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
164 const stateData = yield* connection.request({ type: "get_state" });
165 const modelsData = yield* connection.request({ type: "get_available_models" });
166 const commandsData = yield* connection
167 .request({ type: "get_commands" })
168 .pipe(Effect.orElseSucceed(() => undefined));
169 const discoveredModels = parseDiscoveredModels(
170 modelsData,
171 recordString(stateData, "thinkingLevel"),
172 );
173 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
174 return {
175 models: discoveredModels,
176 slashCommands: withPiBuiltinSlashCommands(slashCommands),
177 skills,
178 authenticated: discoveredModels.length > 0,
179 } satisfies PiDiscovery;
180 }).pipe(Effect.scoped);
181
182/**
183 * The commands and skills Pi sees in one workspace, including project skills.
184 * Used by the driver's `snapshotForCwd`; health and models stay on the
185 * machine-wide snapshot. Fails instead of returning an empty list, so a failed
186 * probe keeps the machine-wide commands.
187 */
188export const discoverPiWorkspaceCommands = (
189 piSettings: PiSettings,
190 environment: NodeJS.ProcessEnv,
191 cwd: string,
192) =>
193 Effect.gen(function* () {
194 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
195 if (!resolvedLaunchArgs.ok) {
196 return yield* new PiRpcError({ operation: "spawn", detail: "invalid launch arguments" });
197 }
198 const connection = yield* openPiDiscoveryConnection(
199 piSettings,
200 environment,
201 resolvedLaunchArgs.args,
202 cwd,
203 );
204 const { slashCommands, skills } = parsePiDiscoveredCommands(
205 yield* connection.request({ type: "get_commands" }),
206 );
207 return {
208 slashCommands: withPiBuiltinSlashCommands(slashCommands),
209 skills,
210 } satisfies PiDiscoveredCommands;
211 }).pipe(Effect.scoped, Effect.timeout(PI_RPC_DISCOVERY_TIMEOUT_MS));
212
213const runPiVersionCommand = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>
214 Effect.gen(function* () {
215 const command = piSettings.binaryPath || "pi";
216 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
217 env: environment,
218 });
219 return yield* spawnAndCollect(
220 command,
221 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
222 env: environment,
223 shell: spawnCommand.shell,
224 }),
225 );
226 });
227
228export function buildInitialPiProviderSnapshot(
229 piSettings: PiSettings,
230): Effect.Effect<ServerProviderDraft> {
231 return Effect.gen(function* () {
232 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
233 const models = piModelsFromSettings(piSettings.customModels);
234 if (!piSettings.enabled) {
235 return buildServerProvider({
236 presentation: PI_PRESENTATION,
237 enabled: false,
238 checkedAt,
239 models,
240 probe: {
241 installed: false,
242 version: null,
243 status: "warning",
244 auth: { status: "unknown" },
245 message: "Pi is disabled in T3 Code settings.",
246 },
247 });
248 }
249 return buildServerProvider({
250 presentation: PI_PRESENTATION,
251 enabled: true,
252 checkedAt,
253 models,
254 probe: {
255 installed: true,
256 version: null,
257 status: "warning",
258 auth: { status: "unknown" },
259 message: "Checking Pi CLI availability...",
260 },
261 });
262 });
263}
264
265export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
266 piSettings: PiSettings,
267 environment: NodeJS.ProcessEnv = process.env,
268 cwd?: string,
269): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
270 const checkedAt = DateTime.formatIso(yield* DateTime.now);
271 const fallbackModels = piModelsFromSettings(piSettings.customModels);
272
273 if (!piSettings.enabled) {
274 return buildServerProvider({
275 presentation: PI_PRESENTATION,
276 enabled: false,
277 checkedAt,
278 models: fallbackModels,
279 probe: {
280 installed: false,
281 version: null,
282 status: "warning",
283 auth: { status: "unknown" },
284 message: "Pi is disabled in T3 Code settings.",
285 },
286 });
287 }
288
289 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
290 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
291 Effect.result,
292 );
293
294 if (Result.isFailure(versionResult)) {
295 const error = versionResult.failure;
296 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
297 return buildServerProvider({
298 presentation: PI_PRESENTATION,
299 enabled: piSettings.enabled,
300 checkedAt,
301 models: fallbackModels,
302 probe: {
303 installed: !isCommandMissingCause(error),
304 version: null,
305 status: "error",
306 auth: { status: "unknown" },
307 message: isCommandMissingCause(error)
308 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g @earendil-works/pi-coding-agent`."
309 : "Failed to execute Pi CLI health check.",
310 },
311 });
312 }
313
314 if (Option.isNone(versionResult.success)) {
315 return buildServerProvider({
316 presentation: PI_PRESENTATION,
317 enabled: piSettings.enabled,
318 checkedAt,
319 models: fallbackModels,
320 probe: {
321 installed: true,
322 version: null,
323 status: "error",
324 auth: { status: "unknown" },
325 message: "Pi CLI is installed but timed out while running `pi --version`.",
326 },
327 });
328 }
329
330 const versionOutput = versionResult.success.value;
331 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
332 if (versionOutput.code !== 0) {
333 return buildServerProvider({
334 presentation: PI_PRESENTATION,
335 enabled: piSettings.enabled,
336 checkedAt,
337 models: fallbackModels,
338 probe: {
339 installed: true,
340 version,
341 status: "error",
342 auth: { status: "unknown" },
343 message: "Pi CLI is installed but failed to run.",
344 },
345 });
346 }
347
348 if (version === null) {
349 return buildServerProvider({
350 presentation: PI_PRESENTATION,
351 enabled: piSettings.enabled,
352 checkedAt,
353 models: fallbackModels,
354 probe: {
355 installed: true,
356 version: null,
357 status: "error",
358 auth: { status: "unknown" },
359 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
360 },
361 });
362 }
363
364 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
365 return buildServerProvider({
366 presentation: PI_PRESENTATION,
367 enabled: piSettings.enabled,
368 checkedAt,
369 models: fallbackModels,
370 probe: {
371 installed: true,
372 version,
373 status: "error",
374 auth: { status: "unknown" },
375 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
376 },
377 });
378 }
379
380 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
381 if (!resolvedLaunchArgs.ok) {
382 return buildServerProvider({
383 presentation: PI_PRESENTATION,
384 enabled: piSettings.enabled,
385 checkedAt,
386 models: fallbackModels,
387 probe: {
388 installed: true,
389 version,
390 status: "error",
391 auth: { status: "unknown" },
392 message: resolvedLaunchArgs.message,
393 },
394 });
395 }
396
397 const discoveryExit = yield* discoverPiViaRpc(
398 piSettings,
399 environment,
400 resolvedLaunchArgs.args,
401 cwd,
402 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
403 if (Exit.isFailure(discoveryExit)) {
404 yield* Effect.logWarning("Pi RPC discovery failed.", {
405 errorTag: causeErrorTag(discoveryExit.cause),
406 });
407 return buildServerProvider({
408 presentation: PI_PRESENTATION,
409 enabled: piSettings.enabled,
410 checkedAt,
411 models: fallbackModels,
412 probe: {
413 installed: true,
414 version,
415 status: "ready",
416 auth: { status: "unknown" },
417 message:
418 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
419 },
420 });
421 }
422 if (Option.isNone(discoveryExit.value)) {
423 return buildServerProvider({
424 presentation: PI_PRESENTATION,
425 enabled: piSettings.enabled,
426 checkedAt,
427 models: fallbackModels,
428 probe: {
429 installed: true,
430 version,
431 status: "ready",
432 auth: { status: "unknown" },
433 message:
434 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
435 },
436 });
437 }
438
439 const discovery = discoveryExit.value.value;
440 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
441 return buildServerProvider({
442 presentation: PI_PRESENTATION,
443 enabled: piSettings.enabled,
444 checkedAt,
445 models,
446 slashCommands: discovery.slashCommands,
447 skills: discovery.skills,
448 probe: {
449 installed: true,
450 version,
451 status: discovery.authenticated ? "ready" : "warning",
452 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
453 ...(discovery.authenticated
454 ? {}
455 : {
456 message:
457 "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",
458 }),
459 },
460 });
461});
462
463export const enrichPiSnapshot = (input: {
464 readonly snapshot: ServerProvider;
465 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
466 readonly enableProviderUpdateChecks?: boolean;
467 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
468}): Effect.Effect<void, never, HttpClient.HttpClient> => {
469 const { snapshot, publishSnapshot } = input;
470 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
471 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
472 }).pipe(
473 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
474 Effect.catchCause((cause) =>
475 Effect.logWarning("Pi version advisory enrichment failed", {
476 errorTag: causeErrorTag(cause),
477 }),
478 ),
479 Effect.asVoid,
480 );
481};