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/http";
27import { ChildProcess, ChildProcessSpawner } from "effect/process";
28
29import {
30 buildPiRpcLaunch,
31 resolvePiLaunchArgs,
32} from "../orchestration-v2/Adapters/piT3McpInjection.ts";
33import {
34 makePiRpcConnection,
35 piRecordField as recordField,
36 piRecordString as recordString,
37} from "../orchestration-v2/Adapters/PiRpc.ts";
38import {
39 buildServerProvider,
40 isCommandMissingCause,
41 parseGenericCliVersion,
42 providerModelsFromSettings,
43 spawnAndCollect,
44 type ServerProviderDraft,
45} from "./providerSnapshot.ts";
46import {
47 enrichProviderSnapshotWithVersionAdvisory,
48 type ProviderMaintenanceCapabilities,
49} from "./providerMaintenance.ts";
50import {
51 EMPTY_PI_MODEL_CAPABILITIES,
52 thinkingCapabilitiesForPiModel,
53} from "./piThinkingCapabilities.ts";
54import {
55 parsePiDiscoveredCommands,
56 withPiBuiltinSlashCommands,
57 type PiDiscoveredCommands,
58} from "./PiCommands.ts";
59
60const PI_PRESENTATION = {
61 displayName: "Pi",
62 showInteractionModeToggle: false,
63 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
64 // The adapter reports context usage from Pi's streaming usage while a
65 // turn runs, so clients can reserve the meter before the first settle.
66 reportsContextWindow: true,
67 requiresNewThreadForModelChange: false,
68} as const;
69
70const VERSION_PROBE_TIMEOUT_MS = 4_000;
71const PI_RPC_DISCOVERY_TIMEOUT_MS = 15_000;
72/**
73 * get_entries arrived in 0.80.3 and agent_settled landed in source at 0.80.4.
74 * Version 0.80.5 was the first published package containing both hooks. T3
75 * needs them for rollback boundaries and reliable turn terminalization.
76 */
77export const MINIMUM_PI_VERSION = "0.80.5";
78
79/** Deferring to the user's own settings.json default model. */
80const PI_DEFAULT_MODEL: ServerProviderModel = {
81 slug: "default",
82 name: "Pi default",
83 isCustom: false,
84 capabilities: EMPTY_PI_MODEL_CAPABILITIES,
85};
86
87interface PiDiscovery extends PiDiscoveredCommands {
88 readonly models: ReadonlyArray<ServerProviderModel>;
89 readonly authenticated: boolean;
90}
91
92function piModelsFromSettings(
93 customModels: ReadonlyArray<CustomModelSetting> | undefined,
94 discovered: ReadonlyArray<ServerProviderModel> = [],
95): ReadonlyArray<ServerProviderModel> {
96 return providerModelsFromSettings(
97 [PI_DEFAULT_MODEL, ...discovered],
98 customModels ?? [],
99 EMPTY_PI_MODEL_CAPABILITIES,
100 );
101}
102
103function parseDiscoveredModels(
104 data: unknown,
105 defaultThinkingLevel: unknown,
106): ReadonlyArray<ServerProviderModel> {
107 const models = recordField(data, "models");
108 if (!Array.isArray(models)) return [];
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) continue;
115 const slug = `${provider}/${id}`;
116 if (seen.has(slug)) continue;
117 seen.add(slug);
118 parsed.push({
119 slug,
120 name: recordString(model, "name") ?? slug,
121 isCustom: false,
122 capabilities: thinkingCapabilitiesForPiModel(model, defaultThinkingLevel),
123 });
124 }
125 return parsed;
126}
127
128const discoverPiViaRpc = (
129 piSettings: PiSettings,
130 environment: NodeJS.ProcessEnv,
131 launchArgs: ReadonlyArray<string>,
132 cwd?: string,
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 const stateData = yield* connection.request({ type: "get_state" });
154 const modelsData = yield* connection.request({ type: "get_available_models" });
155 const commandsData = yield* connection
156 .request({ type: "get_commands" })
157 .pipe(Effect.orElseSucceed(() => undefined));
158 const discoveredModels = parseDiscoveredModels(
159 modelsData,
160 recordString(stateData, "thinkingLevel"),
161 );
162 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
163 return {
164 models: discoveredModels,
165 slashCommands: withPiBuiltinSlashCommands(slashCommands),
166 skills,
167 authenticated: discoveredModels.length > 0,
168 } satisfies PiDiscovery;
169 }).pipe(Effect.scoped);
170
171const runPiVersionCommand = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>
172 Effect.gen(function* () {
173 const command = piSettings.binaryPath || "pi";
174 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
175 env: environment,
176 });
177 return yield* spawnAndCollect(
178 command,
179 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
180 env: environment,
181 shell: spawnCommand.shell,
182 }),
183 );
184 });
185
186export function buildInitialPiProviderSnapshot(
187 piSettings: PiSettings,
188): Effect.Effect<ServerProviderDraft> {
189 return Effect.gen(function* () {
190 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
191 const models = piModelsFromSettings(piSettings.customModels);
192 if (!piSettings.enabled) {
193 return buildServerProvider({
194 presentation: PI_PRESENTATION,
195 enabled: false,
196 checkedAt,
197 models,
198 probe: {
199 installed: false,
200 version: null,
201 status: "warning",
202 auth: { status: "unknown" },
203 message: "Pi is disabled in T3 Code settings.",
204 },
205 });
206 }
207 return buildServerProvider({
208 presentation: PI_PRESENTATION,
209 enabled: true,
210 checkedAt,
211 models,
212 probe: {
213 installed: true,
214 version: null,
215 status: "warning",
216 auth: { status: "unknown" },
217 message: "Checking Pi CLI availability...",
218 },
219 });
220 });
221}
222
223export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
224 piSettings: PiSettings,
225 environment: NodeJS.ProcessEnv = process.env,
226 cwd?: string,
227): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
228 const checkedAt = DateTime.formatIso(yield* DateTime.now);
229 const fallbackModels = piModelsFromSettings(piSettings.customModels);
230
231 if (!piSettings.enabled) {
232 return buildServerProvider({
233 presentation: PI_PRESENTATION,
234 enabled: false,
235 checkedAt,
236 models: fallbackModels,
237 probe: {
238 installed: false,
239 version: null,
240 status: "warning",
241 auth: { status: "unknown" },
242 message: "Pi is disabled in T3 Code settings.",
243 },
244 });
245 }
246
247 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
248 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
249 Effect.result,
250 );
251
252 if (Result.isFailure(versionResult)) {
253 const error = versionResult.failure;
254 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
255 return buildServerProvider({
256 presentation: PI_PRESENTATION,
257 enabled: piSettings.enabled,
258 checkedAt,
259 models: fallbackModels,
260 probe: {
261 installed: !isCommandMissingCause(error),
262 version: null,
263 status: "error",
264 auth: { status: "unknown" },
265 message: isCommandMissingCause(error)
266 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g @earendil-works/pi-coding-agent`."
267 : "Failed to execute Pi CLI health check.",
268 },
269 });
270 }
271
272 if (Option.isNone(versionResult.success)) {
273 return buildServerProvider({
274 presentation: PI_PRESENTATION,
275 enabled: piSettings.enabled,
276 checkedAt,
277 models: fallbackModels,
278 probe: {
279 installed: true,
280 version: null,
281 status: "error",
282 auth: { status: "unknown" },
283 message: "Pi CLI is installed but timed out while running `pi --version`.",
284 },
285 });
286 }
287
288 const versionOutput = versionResult.success.value;
289 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
290 if (versionOutput.code !== 0) {
291 return buildServerProvider({
292 presentation: PI_PRESENTATION,
293 enabled: piSettings.enabled,
294 checkedAt,
295 models: fallbackModels,
296 probe: {
297 installed: true,
298 version,
299 status: "error",
300 auth: { status: "unknown" },
301 message: "Pi CLI is installed but failed to run.",
302 },
303 });
304 }
305
306 if (version === null) {
307 return buildServerProvider({
308 presentation: PI_PRESENTATION,
309 enabled: piSettings.enabled,
310 checkedAt,
311 models: fallbackModels,
312 probe: {
313 installed: true,
314 version: null,
315 status: "error",
316 auth: { status: "unknown" },
317 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
318 },
319 });
320 }
321
322 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
323 return buildServerProvider({
324 presentation: PI_PRESENTATION,
325 enabled: piSettings.enabled,
326 checkedAt,
327 models: fallbackModels,
328 probe: {
329 installed: true,
330 version,
331 status: "error",
332 auth: { status: "unknown" },
333 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
334 },
335 });
336 }
337
338 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
339 if (!resolvedLaunchArgs.ok) {
340 return buildServerProvider({
341 presentation: PI_PRESENTATION,
342 enabled: piSettings.enabled,
343 checkedAt,
344 models: fallbackModels,
345 probe: {
346 installed: true,
347 version,
348 status: "error",
349 auth: { status: "unknown" },
350 message: resolvedLaunchArgs.message,
351 },
352 });
353 }
354
355 const discoveryExit = yield* discoverPiViaRpc(
356 piSettings,
357 environment,
358 resolvedLaunchArgs.args,
359 cwd,
360 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
361 if (Exit.isFailure(discoveryExit)) {
362 yield* Effect.logWarning("Pi RPC discovery failed.", {
363 errorTag: causeErrorTag(discoveryExit.cause),
364 });
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: "ready",
374 auth: { status: "unknown" },
375 message:
376 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
377 },
378 });
379 }
380 if (Option.isNone(discoveryExit.value)) {
381 return buildServerProvider({
382 presentation: PI_PRESENTATION,
383 enabled: piSettings.enabled,
384 checkedAt,
385 models: fallbackModels,
386 probe: {
387 installed: true,
388 version,
389 status: "ready",
390 auth: { status: "unknown" },
391 message:
392 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
393 },
394 });
395 }
396
397 const discovery = discoveryExit.value.value;
398 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
399 return buildServerProvider({
400 presentation: PI_PRESENTATION,
401 enabled: piSettings.enabled,
402 checkedAt,
403 models,
404 slashCommands: discovery.slashCommands,
405 skills: discovery.skills,
406 probe: {
407 installed: true,
408 version,
409 status: discovery.authenticated ? "ready" : "warning",
410 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
411 ...(discovery.authenticated
412 ? {}
413 : {
414 message:
415 "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",
416 }),
417 },
418 });
419});
420
421export const enrichPiSnapshot = (input: {
422 readonly snapshot: ServerProvider;
423 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
424 readonly enableProviderUpdateChecks?: boolean;
425 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
426 readonly httpClient: HttpClient.HttpClient;
427}): Effect.Effect<void> => {
428 const { snapshot, publishSnapshot } = input;
429 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
430 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
431 }).pipe(
432 Effect.provideService(HttpClient.HttpClient, input.httpClient),
433 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
434 Effect.catchCause((cause) =>
435 Effect.logWarning("Pi version advisory enrichment failed", {
436 errorTag: causeErrorTag(cause),
437 }),
438 ),
439 Effect.asVoid,
440 );
441};