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

status.ts

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