Open History to see the last commit
1import {
2 type CustomModelSetting,
3 type ServerProvider,
4 type ServerProviderModel,
5} from "@t3tools/contracts";
6import type { PiSettings } from "../settings.ts";
7import { causeErrorTag } from "@t3tools/shared/observability";
8import { resolveSpawnCommand } from "@t3tools/shared/shell";
9import { compareSemverVersions } from "@t3tools/shared/semver";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Stream from "effect/Stream";
13import * as Exit from "effect/Exit";
14import * as Option from "effect/Option";
15import * as Result from "effect/Result";
16import * as HttpClient from "effect/http/HttpClient";
17import * as ChildProcess from "effect/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19
20import { buildPiRpcLaunch, resolvePiLaunchArgs } from "./mcpInjection.ts";
21import {
22 makePiRpcConnection,
23 PiRpcError,
24 PiRpcTimeoutError,
25 piRecordField as recordField,
26 piRecordString as recordString,
27} from "./rpc.ts";
28import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
29import {
30 buildServerProvider,
31 isCommandMissingCause,
32 parseGenericCliVersion,
33 providerModelsFromSettings,
34 spawnAndCollect,
35 type ServerProviderDraft,
36} from "@t3tools/provider-core/server/snapshotProbe";
37import {
38 enrichProviderSnapshotWithVersionAdvisory,
39 type ProviderMaintenanceCapabilities,
40} from "@t3tools/provider-core/server/maintenanceResolver";
41import {
42 EMPTY_PI_MODEL_CAPABILITIES,
43 thinkingCapabilitiesForPiModel,
44} from "./thinkingCapabilities.ts";
45import {
46 parsePiDiscoveredCommands,
47 withPiBuiltinSlashCommands,
48 type PiDiscoveredCommands,
49} from "./commands.ts";
50
51const PI_PRESENTATION = {
52 displayName: "Pi",
53 showInteractionModeToggle: false,
54 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
55 reportsContextWindow: true,
56} as const;
57
58const VERSION_PROBE_TIMEOUT_MS = 4_000;
59const PI_RPC_DISCOVERY_TIMEOUT_MS = 30_000;
60/**
61 * get_entries arrived in 0.80.3 and agent_settled landed in source at 0.80.4.
62 * Version 0.80.5 was the first published package containing both hooks.
63 */
64export const MINIMUM_PI_VERSION = "0.80.5";
65
66const PI_DEFAULT_MODEL: ServerProviderModel = {
67 slug: "default",
68 name: "Pi default",
69 isCustom: false,
70 capabilities: EMPTY_PI_MODEL_CAPABILITIES,
71};
72
73interface PiDiscovery extends PiDiscoveredCommands {
74 readonly models: ReadonlyArray<ServerProviderModel>;
75 readonly authenticated: boolean;
76}
77
78function piModelsFromSettings(
79 customModels: ReadonlyArray<CustomModelSetting> | undefined,
80 discovered: ReadonlyArray<ServerProviderModel> = [],
81): ReadonlyArray<ServerProviderModel> {
82 return providerModelsFromSettings(
83 [PI_DEFAULT_MODEL, ...discovered],
84 customModels ?? [],
85 EMPTY_PI_MODEL_CAPABILITIES,
86 );
87}
88
89function parseDiscoveredModels(
90 data: unknown,
91 state: unknown,
92): Result.Result<ReadonlyArray<ServerProviderModel>, PiRpcError> {
93 const models = recordField(data, "models");
94 if (!Array.isArray(models)) {
95 return Result.fail(
96 new PiRpcError({ operation: "get_available_models", detail: "Invalid model inventory" }),
97 );
98 }
99 const activeModel = recordField(state, "model");
100 const activeProvider = recordString(activeModel, "provider");
101 const activeModelId = recordString(activeModel, "id");
102 const seen = new Set<string>();
103 const parsed: Array<ServerProviderModel> = [];
104 for (const model of models) {
105 const provider = recordString(model, "provider");
106 const id = recordString(model, "id");
107 if (provider === undefined || id === undefined || provider.trim() === "" || id.trim() === "") {
108 return Result.fail(
109 new PiRpcError({ operation: "get_available_models", detail: "Invalid model identity" }),
110 );
111 }
112 const slug = `${provider}/${id}`;
113 if (seen.has(slug)) continue;
114 seen.add(slug);
115 parsed.push({
116 slug,
117 name: recordString(model, "name") ?? slug,
118 subProvider: provider,
119 isCustom: false,
120 capabilities: thinkingCapabilitiesForPiModel(
121 model,
122 provider === activeProvider && id === activeModelId
123 ? recordString(state, "thinkingLevel")
124 : undefined,
125 ),
126 });
127 }
128 return Result.succeed(parsed);
129}
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 = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (
159 piSettings: PiSettings,
160 environment: NodeJS.ProcessEnv,
161 launchArgs: ReadonlyArray<string>,
162 cwd?: string,
163) {
164 const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
165 const stateData = yield* connection.request({ type: "get_state" });
166 const modelsData = yield* connection.request({ type: "get_available_models" });
167 const commandsData = yield* connection
168 .request({ type: "get_commands" })
169 .pipe(Effect.orElseSucceed(() => undefined));
170 const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
171 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
172 return {
173 models: discoveredModels,
174 slashCommands: withPiBuiltinSlashCommands(slashCommands),
175 skills,
176 authenticated: discoveredModels.length > 0,
177 } satisfies PiDiscovery;
178}, Effect.scoped);
179
180export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
181 function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {
182 const launchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
183 if (!launchArgs.ok) {
184 return yield* new PiRpcError({ operation: "launch", detail: launchArgs.message });
185 }
186 const connection = yield* makePiDiscoveryConnection(
187 piSettings,
188 environment,
189 launchArgs.args,
190 cwd,
191 );
192 // A failed read must not replace a previously usable workspace catalog with an empty one.
193 const commandsData = yield* connection.request({ type: "get_commands" });
194 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
195 return { slashCommands: withPiBuiltinSlashCommands(slashCommands), skills };
196 },
197 Effect.scoped,
198 Effect.timeoutOrElse({
199 duration: PI_RPC_DISCOVERY_TIMEOUT_MS,
200 orElse: () =>
201 Effect.fail(
202 new PiRpcTimeoutError({ operation: "discovery", timeoutMs: PI_RPC_DISCOVERY_TIMEOUT_MS }),
203 ),
204 }),
205);
206
207const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (
208 piSettings: PiSettings,
209 environment: NodeJS.ProcessEnv,
210) {
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 const buildInitialPiProviderSnapshot = Effect.fn(
225 "PiProviderStatus.buildInitialPiProviderSnapshot",
226)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {
227 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
228 const models = piModelsFromSettings(piSettings.customModels);
229 if (!piSettings.enabled) {
230 return buildServerProvider({
231 presentation: PI_PRESENTATION,
232 enabled: false,
233 checkedAt,
234 models,
235 probe: {
236 installed: false,
237 version: null,
238 status: "warning",
239 auth: { status: "unknown" },
240 message: "Pi is disabled in T3 Code settings.",
241 },
242 });
243 }
244 return buildServerProvider({
245 presentation: PI_PRESENTATION,
246 enabled: true,
247 checkedAt,
248 models,
249 probe: {
250 installed: true,
251 version: null,
252 status: "warning",
253 auth: { status: "unknown" },
254 message: "Checking Pi CLI availability...",
255 },
256 });
257});
258
259export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
260 piSettings: PiSettings,
261 environment: NodeJS.ProcessEnv = process.env,
262 cwd?: string,
263): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
264 const checkedAt = DateTime.formatIso(yield* DateTime.now);
265 const fallbackModels = piModelsFromSettings(piSettings.customModels);
266
267 if (!piSettings.enabled) {
268 return buildServerProvider({
269 presentation: PI_PRESENTATION,
270 enabled: false,
271 checkedAt,
272 models: fallbackModels,
273 probe: {
274 installed: false,
275 version: null,
276 status: "warning",
277 auth: { status: "unknown" },
278 message: "Pi is disabled in T3 Code settings.",
279 },
280 });
281 }
282
283 const versionResult = yield* runPiVersionCommand(piSettings, environment).pipe(
284 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
285 Effect.result,
286 );
287
288 if (Result.isFailure(versionResult)) {
289 const error = versionResult.failure;
290 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
291 return buildServerProvider({
292 presentation: PI_PRESENTATION,
293 enabled: piSettings.enabled,
294 checkedAt,
295 models: fallbackModels,
296 probe: {
297 installed: !isCommandMissingCause(error),
298 version: null,
299 status: "error",
300 auth: { status: "unknown" },
301 message: isCommandMissingCause(error)
302 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`."
303 : "Failed to execute Pi CLI health check.",
304 },
305 });
306 }
307
308 if (Option.isNone(versionResult.success)) {
309 return buildServerProvider({
310 presentation: PI_PRESENTATION,
311 enabled: piSettings.enabled,
312 checkedAt,
313 models: fallbackModels,
314 probe: {
315 installed: true,
316 version: null,
317 status: "error",
318 auth: { status: "unknown" },
319 message: "Pi CLI is installed but timed out while running `pi --version`.",
320 },
321 });
322 }
323
324 const versionOutput = versionResult.success.value;
325 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
326 if (versionOutput.code !== 0) {
327 return buildServerProvider({
328 presentation: PI_PRESENTATION,
329 enabled: piSettings.enabled,
330 checkedAt,
331 models: fallbackModels,
332 probe: {
333 installed: true,
334 version,
335 status: "error",
336 auth: { status: "unknown" },
337 message: "Pi CLI is installed but failed to run.",
338 },
339 });
340 }
341
342 if (version === null) {
343 return buildServerProvider({
344 presentation: PI_PRESENTATION,
345 enabled: piSettings.enabled,
346 checkedAt,
347 models: fallbackModels,
348 probe: {
349 installed: true,
350 version: null,
351 status: "error",
352 auth: { status: "unknown" },
353 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
354 },
355 });
356 }
357
358 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
359 return buildServerProvider({
360 presentation: PI_PRESENTATION,
361 enabled: piSettings.enabled,
362 checkedAt,
363 models: fallbackModels,
364 probe: {
365 installed: true,
366 version,
367 status: "error",
368 auth: { status: "unknown" },
369 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
370 },
371 });
372 }
373
374 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
375 if (!resolvedLaunchArgs.ok) {
376 return buildServerProvider({
377 presentation: PI_PRESENTATION,
378 enabled: piSettings.enabled,
379 checkedAt,
380 models: fallbackModels,
381 probe: {
382 installed: true,
383 version,
384 status: "error",
385 auth: { status: "unknown" },
386 message: resolvedLaunchArgs.message,
387 },
388 });
389 }
390
391 const discoveryExit = yield* discoverPiViaRpc(
392 piSettings,
393 environment,
394 resolvedLaunchArgs.args,
395 cwd,
396 ).pipe(Effect.timeoutOption(PI_RPC_DISCOVERY_TIMEOUT_MS), Effect.exit);
397 if (Exit.isFailure(discoveryExit)) {
398 yield* Effect.logWarning("Pi RPC discovery failed.", {
399 errorTag: causeErrorTag(discoveryExit.cause),
400 });
401 return buildServerProvider({
402 presentation: PI_PRESENTATION,
403 enabled: piSettings.enabled,
404 checkedAt,
405 models: fallbackModels,
406 probe: {
407 installed: true,
408 version,
409 status: "ready",
410 auth: { status: "unknown" },
411 message:
412 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
413 },
414 });
415 }
416 if (Option.isNone(discoveryExit.value)) {
417 return buildServerProvider({
418 presentation: PI_PRESENTATION,
419 enabled: piSettings.enabled,
420 checkedAt,
421 models: fallbackModels,
422 probe: {
423 installed: true,
424 version,
425 status: "ready",
426 auth: { status: "unknown" },
427 message:
428 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
429 },
430 });
431 }
432
433 const discovery = discoveryExit.value.value;
434 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
435 return buildServerProvider({
436 presentation: PI_PRESENTATION,
437 enabled: piSettings.enabled,
438 checkedAt,
439 models,
440 slashCommands: discovery.slashCommands,
441 skills: discovery.skills,
442 probe: {
443 installed: true,
444 version,
445 status: discovery.authenticated ? "ready" : "warning",
446 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
447 ...(discovery.authenticated
448 ? {}
449 : {
450 message:
451 "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",
452 }),
453 },
454 });
455});
456
457export const enrichPiSnapshot = (input: {
458 readonly snapshot: ServerProvider;
459 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
460 readonly enableProviderUpdateChecks?: boolean;
461 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
462}): Effect.Effect<
463 void,
464 never,
465 HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions
466> => {
467 const { snapshot, publishSnapshot } = input;
468 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
469 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
470 }).pipe(
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};