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