Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PiProvider.ts

442 lines13.7 KB

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;
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 );
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 subProvider: provider,
122 isCustom: false,
123 capabilities: thinkingCapabilitiesForPiModel(model, defaultThinkingLevel),
124 });
125 }
126 return parsed;
128​
129const discoverPiViaRpc = (
130 piSettings: PiSettings,
131 environment: NodeJS.ProcessEnv,
132 launchArgs: ReadonlyArray<string>,
133 cwd?: string,
134) =>
135 Effect.gen(function* () {
136 const launch = buildPiRpcLaunch({
137 launchArgs,
138 environment,
139 mcpSession: undefined,
140 extensionPath: undefined,
141 ephemeral: true,
142 });
143 const connection = yield* makePiRpcConnection({
144 command: piSettings.binaryPath || "pi",
145 args: launch.args,
146 cwd,
147 env: launch.env,
148 });
149 yield* Stream.fromQueue(connection.events).pipe(
150 Stream.runDrain,
151 Effect.ignore,
152 Effect.forkScoped,
153 );
154 const stateData = yield* connection.request({ type: "get_state" });
155 const modelsData = yield* connection.request({ type: "get_available_models" });
156 const commandsData = yield* connection
157 .request({ type: "get_commands" })
158 .pipe(Effect.orElseSucceed(() => undefined));
159 const discoveredModels = parseDiscoveredModels(
160 modelsData,
161 recordString(stateData, "thinkingLevel"),
162 );
163 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
164 return {
165 models: discoveredModels,
166 slashCommands: withPiBuiltinSlashCommands(slashCommands),
167 skills,
168 authenticated: discoveredModels.length > 0,
169 } satisfies PiDiscovery;
170 }).pipe(Effect.scoped);
171​
172const runPiVersionCommand = (piSettings: PiSettings, environment: NodeJS.ProcessEnv) =>
173 Effect.gen(function* () {
174 const command = piSettings.binaryPath || "pi";
175 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
176 env: environment,
177 });
178 return yield* spawnAndCollect(
179 command,
180 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
181 env: environment,
182 shell: spawnCommand.shell,
183 }),
184 );
185 });
186​
187export function buildInitialPiProviderSnapshot(
188 piSettings: PiSettings,
189): Effect.Effect<ServerProviderDraft> {
190 return Effect.gen(function* () {
191 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
192 const models = piModelsFromSettings(piSettings.customModels);
193 if (!piSettings.enabled) {
194 return buildServerProvider({
195 presentation: PI_PRESENTATION,
196 enabled: false,
197 checkedAt,
198 models,
199 probe: {
200 installed: false,
201 version: null,
202 status: "warning",
203 auth: { status: "unknown" },
204 message: "Pi is disabled in T3 Code settings.",
205 },
206 });
207 }
208 return buildServerProvider({
209 presentation: PI_PRESENTATION,
210 enabled: true,
211 checkedAt,
212 models,
213 probe: {
214 installed: true,
215 version: null,
216 status: "warning",
217 auth: { status: "unknown" },
218 message: "Checking Pi CLI availability...",
219 },
220 });
221 });
223​
224export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
225 piSettings: PiSettings,
226 environment: NodeJS.ProcessEnv = process.env,
227 cwd?: string,
228): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
229 const checkedAt = DateTime.formatIso(yield* DateTime.now);
230 const fallbackModels = piModelsFromSettings(piSettings.customModels);
231​
232 if (!piSettings.enabled) {
233 return buildServerProvider({
234 presentation: PI_PRESENTATION,
235 enabled: false,
236 checkedAt,
237 models: fallbackModels,
238 probe: {
239 installed: false,
240 version: null,
241 status: "warning",
242 auth: { status: "unknown" },
243 message: "Pi is disabled in T3 Code settings.",
244 },
245 });
246 }
247​
248 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
249 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
250 Effect.result,
251 );
252​
253 if (Result.isFailure(versionResult)) {
254 const error = versionResult.failure;
255 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
256 return buildServerProvider({
257 presentation: PI_PRESENTATION,
258 enabled: piSettings.enabled,
259 checkedAt,
260 models: fallbackModels,
261 probe: {
262 installed: !isCommandMissingCause(error),
263 version: null,
264 status: "error",
265 auth: { status: "unknown" },
266 message: isCommandMissingCause(error)
267 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g @earendil-works/pi-coding-agent`."
268 : "Failed to execute Pi CLI health check.",
269 },
270 });
271 }
272​
273 if (Option.isNone(versionResult.success)) {
274 return buildServerProvider({
275 presentation: PI_PRESENTATION,
276 enabled: piSettings.enabled,
277 checkedAt,
278 models: fallbackModels,
279 probe: {
280 installed: true,
281 version: null,
282 status: "error",
283 auth: { status: "unknown" },
284 message: "Pi CLI is installed but timed out while running `pi --version`.",
285 },
286 });
287 }
288​
289 const versionOutput = versionResult.success.value;
290 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
291 if (versionOutput.code !== 0) {
292 return buildServerProvider({
293 presentation: PI_PRESENTATION,
294 enabled: piSettings.enabled,
295 checkedAt,
296 models: fallbackModels,
297 probe: {
298 installed: true,
299 version,
300 status: "error",
301 auth: { status: "unknown" },
302 message: "Pi CLI is installed but failed to run.",
303 },
304 });
305 }
306​
307 if (version === null) {
308 return buildServerProvider({
309 presentation: PI_PRESENTATION,
310 enabled: piSettings.enabled,
311 checkedAt,
312 models: fallbackModels,
313 probe: {
314 installed: true,
315 version: null,
316 status: "error",
317 auth: { status: "unknown" },
318 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
319 },
320 });
321 }
322​
323 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
324 return buildServerProvider({
325 presentation: PI_PRESENTATION,
326 enabled: piSettings.enabled,
327 checkedAt,
328 models: fallbackModels,
329 probe: {
330 installed: true,
331 version,
332 status: "error",
333 auth: { status: "unknown" },
334 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
335 },
336 });
337 }
338​
339 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
340 if (!resolvedLaunchArgs.ok) {
341 return buildServerProvider({
342 presentation: PI_PRESENTATION,
343 enabled: piSettings.enabled,
344 checkedAt,
345 models: fallbackModels,
346 probe: {
347 installed: true,
348 version,
349 status: "error",
350 auth: { status: "unknown" },
351 message: resolvedLaunchArgs.message,
352 },
353 });
354 }
355​
356 const discoveryExit = yield* discoverPiViaRpc(
357 piSettings,
358 environment,
359 resolvedLaunchArgs.args,
360 cwd,
361 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
362 if (Exit.isFailure(discoveryExit)) {
363 yield* Effect.logWarning("Pi RPC discovery failed.", {
364 errorTag: causeErrorTag(discoveryExit.cause),
365 });
366 return buildServerProvider({
367 presentation: PI_PRESENTATION,
368 enabled: piSettings.enabled,
369 checkedAt,
370 models: fallbackModels,
371 probe: {
372 installed: true,
373 version,
374 status: "ready",
375 auth: { status: "unknown" },
376 message:
377 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
378 },
379 });
380 }
381 if (Option.isNone(discoveryExit.value)) {
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: "ready",
391 auth: { status: "unknown" },
392 message:
393 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
394 },
395 });
396 }
397​
398 const discovery = discoveryExit.value.value;
399 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
400 return buildServerProvider({
401 presentation: PI_PRESENTATION,
402 enabled: piSettings.enabled,
403 checkedAt,
404 models,
405 slashCommands: discovery.slashCommands,
406 skills: discovery.skills,
407 probe: {
408 installed: true,
409 version,
410 status: discovery.authenticated ? "ready" : "warning",
411 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
412 ...(discovery.authenticated
413 ? {}
414 : {
415 message:
416 "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",
417 }),
418 },
419 });
420});
421​
422export const enrichPiSnapshot = (input: {
423 readonly snapshot: ServerProvider;
424 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
425 readonly enableProviderUpdateChecks?: boolean;
426 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
427 readonly httpClient: HttpClient.HttpClient;
428}): Effect.Effect<void> => {
429 const { snapshot, publishSnapshot } = input;
430 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
431 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
432 }).pipe(
433 Effect.provideService(HttpClient.HttpClient, input.httpClient),
434 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
435 Effect.catchCause((cause) =>
436 Effect.logWarning("Pi version advisory enrichment failed", {
437 errorTag: causeErrorTag(cause),
438 }),
439 ),
440 Effect.asVoid,
441 );
442};