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

status.ts

481 lines15.0 KB

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