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

PiProvider.ts

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