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

status.ts

625 lines21.2 KB

1import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe";
2import {
3 type CustomModelSetting,
4 type ServerProvider,
5 type ServerProviderModel,
6} from "@t3tools/contracts";
7import type { PiSettings } from "../settings.ts";
8import { causeErrorTag } from "@t3tools/shared/observability";
9import { resolveSpawnCommand } from "@t3tools/shared/shell";
10import { compareSemverVersions } from "@t3tools/shared/semver";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Stream from "effect/Stream";
14import * as Exit from "effect/Exit";
15import * as Fiber from "effect/Fiber";
16import * as Option from "effect/Option";
17import * as Result from "effect/Result";
18import * as Schema from "effect/Schema";
19import * as HttpClient from "effect/http/HttpClient";
20import * as ChildProcess from "effect/process/ChildProcess";
21import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
22​
23import { buildPiRpcLaunch, resolvePiLaunchArgs } from "./mcpInjection.ts";
24import {
25 makePiRpcConnection,
26 PiRpcError,
27 PiRpcTimeoutError,
28 piRecordField as recordField,
29 piRecordString as recordString,
30} from "./rpc.ts";
31import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
32import {
33 buildServerProvider,
34 DEFAULT_TIMEOUT_MS,
35 isCommandMissingCause,
36 parseCliVersionResult,
37 providerModelsFromSettings,
38 providerProbeEnvironment,
39 spawnAndCollect,
40 type ServerProviderDraft,
41} from "@t3tools/provider-core/server/snapshotProbe";
42import {
43 enrichProviderSnapshotWithVersionAdvisory,
44 type ProviderMaintenanceCapabilities,
45} from "@t3tools/provider-core/server/maintenanceResolver";
46import { EMPTY_PI_MODEL_CAPABILITIES, piModelCapabilities } from "./modelCapabilities.ts";
47import {
48 parsePiDiscoveredCommands,
49 withPiBuiltinSlashCommands,
50 type PiDiscoveredCommands,
51} from "./commands.ts";
52​
53const PI_PRESENTATION = {
54 displayName: "Pi",
55 showInteractionModeToggle: false,
56 supportedRuntimeModes: ["approval-required", "auto-accept-edits", "full-access"],
57 reportsContextWindow: true,
58} as const;
59​
60const VERSION_PROBE_TIMEOUT_MS = 10_000;
61const PI_RPC_DISCOVERY_TIMEOUT_MS = 30_000;
62const PI_TEXT_GENERATION_DISCOVERY_TIMEOUT_MS = 5_000;
63// Earlier releases persist background set_thinking_level requests as the user's global default.
64export const MINIMUM_PI_VERSION = "0.84.3";
65​
66const decodePiAuthCheck = Schema.decodeUnknownOption(
67 Schema.fromJsonString(Schema.Struct({ reason: Schema.optional(Schema.String) })),
68);
69​
70const PI_DEFAULT_MODEL: ServerProviderModel = {
71 slug: "default",
72 name: "Pi default",
73 isCustom: false,
74 capabilities: EMPTY_PI_MODEL_CAPABILITIES,
75};
76​
77interface PiDiscovery extends PiDiscoveredCommands {
78 readonly models: ReadonlyArray<ServerProviderModel>;
79 readonly authenticated: boolean;
80 /** Pi's active model when Pi lists no model of its provider, so it cannot start a turn. */
81 readonly unavailableActiveModel: { readonly provider: string; readonly id: string } | undefined;
82 /** Pi without extensions can load no model, so text generation fails for every entry. */
83 readonly textGenerationUnavailable: boolean;
85​
86function piModelsFromSettings(
87 customModels: ReadonlyArray<CustomModelSetting> | undefined,
88 discovered: ReadonlyArray<ServerProviderModel> = [],
89): ReadonlyArray<ServerProviderModel> {
90 return providerModelsFromSettings(
91 [PI_DEFAULT_MODEL, ...discovered],
92 customModels ?? [],
93 EMPTY_PI_MODEL_CAPABILITIES,
94 );
96​
97function parseDiscoveredModels(
98 data: unknown,
99 state: unknown,
100): Result.Result<ReadonlyArray<ServerProviderModel>, PiRpcError> {
101 const models = recordField(data, "models");
102 if (!Array.isArray(models)) {
103 return Result.fail(
104 new PiRpcError({ operation: "get_available_models", detail: "Invalid model inventory" }),
105 );
106 }
107 const activeModel = recordField(state, "model");
108 const activeProvider = recordString(activeModel, "provider");
109 const activeModelId = recordString(activeModel, "id");
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 || provider.trim() === "" || id.trim() === "") {
116 return Result.fail(
117 new PiRpcError({ operation: "get_available_models", detail: "Invalid model identity" }),
118 );
119 }
120 const slug = `${provider}/${id}`;
121 if (seen.has(slug)) continue;
122 seen.add(slug);
123 parsed.push({
124 slug,
125 name: recordString(model, "name") ?? slug,
126 subProvider: provider,
127 isCustom: false,
128 capabilities: piModelCapabilities(
129 model,
130 provider === activeProvider && id === activeModelId
131 ? recordString(state, "thinkingLevel")
132 : undefined,
133 ),
134 });
135 }
136 return Result.succeed(parsed);
138​
139const makePiDiscoveryConnection = Effect.fnUntraced(function* (
140 piSettings: PiSettings,
141 environment: NodeJS.ProcessEnv,
142 launchArgs: ReadonlyArray<string>,
143 cwd?: string,
144 textGenerationLaunch = false,
145) {
146 const launch = buildPiRpcLaunch({
147 launchArgs,
148 environment,
149 mcpSession: undefined,
150 extensionPath: undefined,
151 ephemeral: true,
152 disableExtensions: textGenerationLaunch,
153 disableTools: textGenerationLaunch,
154 shortLived: true,
155 });
156 const connection = yield* makePiRpcConnection({
157 command: piSettings.binaryPath || "pi",
158 args: launch.args,
159 cwd,
160 env: launch.env,
161 });
162 yield* Stream.fromQueue(connection.events).pipe(
163 Stream.runDrain,
164 Effect.ignore,
165 Effect.forkScoped,
166 );
167 return connection;
168});
169​
170// Text generation runs Pi with --no-extensions, so it cannot load models that an
171// extension or package registers. Listing models with that launch tells them apart.
172const discoverPiTextGenerationModelSlugs = Effect.fn(
173 "PiProviderStatus.discoverPiTextGenerationModelSlugs",
174)(function* (
175 piSettings: PiSettings,
176 environment: NodeJS.ProcessEnv,
177 launchArgs: ReadonlyArray<string>,
178 cwd?: string,
179) {
180 const connection = yield* makePiDiscoveryConnection(
181 piSettings,
182 environment,
183 launchArgs,
184 cwd,
185 true,
186 );
187 const modelsData = yield* connection.request({ type: "get_available_models" });
188 const models = yield* Effect.fromResult(parseDiscoveredModels(modelsData, undefined));
189 return new Set(models.map((model) => model.slug));
190}, Effect.scoped);
191​
192const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function* (
193 piSettings: PiSettings,
194 environment: NodeJS.ProcessEnv,
195 launchArgs: ReadonlyArray<string>,
196 cwd?: string,
197) {
198 const timeoutMs = resolveProviderProbeTimeoutMs("pi", PI_RPC_DISCOVERY_TIMEOUT_MS, environment);
199 // This optional probe must finish before the normal discovery deadline so
200 // it cannot discard an otherwise usable catalog and authentication state.
201 const textGenerationModelSlugsFiber = yield* discoverPiTextGenerationModelSlugs(
202 piSettings,
203 environment,
204 launchArgs,
205 cwd,
206 ).pipe(
207 // Pi exits before answering when launch args name a provider only an extension registers.
208 Effect.catchIf(
209 (error) =>
210 error._tag === "PiRpcError" && (error.operation === "read" || error.operation === "exit"),
211 () => Effect.succeed(new Set<string>()),
212 ),
213 Effect.orElseSucceed(() => undefined),
214 Effect.timeoutOrElse({
215 duration: PI_TEXT_GENERATION_DISCOVERY_TIMEOUT_MS,
216 orElse: () => Effect.void,
217 }),
218 Effect.forkScoped,
219 );
220 const connection = yield* makePiDiscoveryConnection(piSettings, environment, launchArgs, cwd);
221 const stateData = yield* connection.request({ type: "get_state" }, timeoutMs);
222 const modelsData = yield* connection.request({ type: "get_available_models" }, timeoutMs);
223 const commandsData = yield* connection
224 .request({ type: "get_commands" }, timeoutMs)
225 .pipe(Effect.orElseSucceed(() => undefined));
226 const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));
227 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
228 const textGenerationModelSlugs = yield* Fiber.join(textGenerationModelSlugsFiber);
229 // Pi lists only models of providers it holds credentials for, including extension, virtual and
230 // --api-key ones. Turns need only the provider's credentials, so uncatalogued model ids still run.
231 const activeModel = recordField(stateData, "model");
232 const activeProvider = recordString(activeModel, "provider");
233 const activeModelId = recordString(activeModel, "id");
234 return {
235 models:
236 textGenerationModelSlugs === undefined
237 ? discoveredModels
238 : discoveredModels.map((model) =>
239 textGenerationModelSlugs.has(model.slug)
240 ? model
241 : { ...model, supportsTextGeneration: false },
242 ),
243 slashCommands: withPiBuiltinSlashCommands(slashCommands),
244 skills,
245 authenticated: discoveredModels.length > 0,
246 unavailableActiveModel:
247 activeProvider !== undefined &&
248 activeModelId !== undefined &&
249 !discoveredModels.some((model) => model.subProvider === activeProvider)
250 ? { provider: activeProvider, id: activeModelId }
251 : undefined,
252 textGenerationUnavailable: textGenerationModelSlugs?.size === 0,
253 } satisfies PiDiscovery;
254}, Effect.scoped);
255​
256export const discoverPiCommandsForCwd = Effect.fn("discoverPiCommandsForCwd")(
257 function* (piSettings: PiSettings, environment: NodeJS.ProcessEnv, cwd: string) {
258 const launchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
259 if (!launchArgs.ok) {
260 return yield* new PiRpcError({ operation: "launch", detail: launchArgs.message });
261 }
262 const connection = yield* makePiDiscoveryConnection(
263 piSettings,
264 providerProbeEnvironment(environment),
265 launchArgs.args,
266 cwd,
267 );
268 // A failed read must not replace a previously usable workspace catalog with an empty one.
269 const commandsData = yield* connection.request(
270 { type: "get_commands" },
271 resolveProviderProbeTimeoutMs("pi", PI_RPC_DISCOVERY_TIMEOUT_MS, environment),
272 );
273 const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);
274 return { slashCommands: withPiBuiltinSlashCommands(slashCommands), skills };
275 },
276 Effect.scoped,
277 (effect, _settings, environment) => {
278 const timeoutMs = resolveProviderProbeTimeoutMs("pi", PI_RPC_DISCOVERY_TIMEOUT_MS, environment);
279 return effect.pipe(
280 Effect.timeoutOrElse({
281 duration: timeoutMs,
282 orElse: () => Effect.fail(new PiRpcTimeoutError({ operation: "discovery", timeoutMs })),
283 }),
284 );
285 },
286);
287​
288export const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(function* (
289 piSettings: PiSettings,
290 environment: NodeJS.ProcessEnv,
291 cwd?: string,
292) {
293 const command = piSettings.binaryPath || "pi";
294 const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
295 env: environment,
296 });
297 return yield* spawnAndCollect(
298 command,
299 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
300 env: environment,
301 shell: spawnCommand.shell,
302 ...(cwd === undefined ? {} : { cwd }),
303 }),
304 );
305});
306​
307/**
308 * Explains why Pi's active model cannot start a turn. Asks `pi auth check` whether credentials
309 * are missing, without refreshing or printing them. That command cannot see
310 * extension providers or a runtime --api-key, so it only refines Pi's own unavailable verdict,
311 * and is skipped when launch args supply the key.
312 */
313const describeUnavailablePiModel = Effect.fn("PiProviderStatus.describeUnavailablePiModel")(
314 function* (
315 piSettings: PiSettings,
316 environment: NodeJS.ProcessEnv,
317 launchArgs: ReadonlyArray<string>,
318 model: { readonly provider: string; readonly id: string },
319 ) {
320 const label = `Pi default (${model.provider}/${model.id})`;
321 const unavailable = `${label} uses ${model.provider}, which has no available models in Pi. Choose another model, or check that provider's setup and the Pi launch arguments.`;
322 if (launchArgs.includes("--api-key")) {
323 return unavailable;
324 }
325 const command = piSettings.binaryPath || "pi";
326 const output = yield* resolveSpawnCommand(
327 command,
328 ["auth", "check", "--provider", model.provider, "--json", "--no-refresh"],
329 { env: environment },
330 ).pipe(
331 Effect.flatMap((spawnCommand) =>
332 spawnAndCollect(
333 command,
334 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
335 env: environment,
336 shell: spawnCommand.shell,
337 }),
338 ),
339 ),
340 Effect.timeout(resolveProviderProbeTimeoutMs("pi", DEFAULT_TIMEOUT_MS, environment)),
341 Effect.option,
342 );
343 const missingCredentials = Option.exists(
344 Option.flatMap(output, (result) => decodePiAuthCheck(result.stdout)),
345 (check) => check.reason === "credentials_not_configured",
346 );
347 return missingCredentials
348 ? `${label} has no credentials configured for ${model.provider}. Choose another model, or run \`pi\` in a terminal and use /login or configure its API key.`
349 : unavailable;
350 },
351);
352​
353export const buildInitialPiProviderSnapshot = Effect.fn(
354 "PiProviderStatus.buildInitialPiProviderSnapshot",
355)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {
356 const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
357 const models = piModelsFromSettings(piSettings.customModels);
358 if (!piSettings.enabled) {
359 return buildServerProvider({
360 presentation: PI_PRESENTATION,
361 enabled: false,
362 checkedAt,
363 models,
364 probe: {
365 installed: false,
366 version: null,
367 status: "warning",
368 auth: { status: "unknown" },
369 message: "Pi is disabled in T3 Code settings.",
370 },
371 });
372 }
373 return buildServerProvider({
374 presentation: PI_PRESENTATION,
375 enabled: true,
376 checkedAt,
377 models,
378 probe: {
379 installed: true,
380 version: null,
381 status: "warning",
382 auth: { status: "unknown" },
383 message: "Checking Pi CLI availability...",
384 },
385 });
386});
387​
388export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(function* (
389 piSettings: PiSettings,
390 environment: NodeJS.ProcessEnv = process.env,
391 cwd?: string,
392): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
393 const checkedAt = DateTime.formatIso(yield* DateTime.now);
394 const fallbackModels = piModelsFromSettings(piSettings.customModels);
395​
396 if (!piSettings.enabled) {
397 return buildServerProvider({
398 presentation: PI_PRESENTATION,
399 enabled: false,
400 checkedAt,
401 models: fallbackModels,
402 probe: {
403 installed: false,
404 version: null,
405 status: "warning",
406 auth: { status: "unknown" },
407 message: "Pi is disabled in T3 Code settings.",
408 },
409 });
410 }
411​
412 const probeEnvironment = providerProbeEnvironment(environment);
413 const versionResult = yield* runPiVersionCommand(piSettings, probeEnvironment).pipe(
414 Effect.timeoutOption(
415 resolveProviderProbeTimeoutMs("pi", VERSION_PROBE_TIMEOUT_MS, environment),
416 ),
417 Effect.result,
418 );
419​
420 if (Result.isFailure(versionResult)) {
421 const error = versionResult.failure;
422 yield* Effect.logWarning("Pi CLI health check failed.", { errorTag: error._tag });
423 return buildServerProvider({
424 presentation: PI_PRESENTATION,
425 enabled: piSettings.enabled,
426 checkedAt,
427 models: fallbackModels,
428 probe: {
429 installed: !isCommandMissingCause(error),
430 version: null,
431 status: "error",
432 auth: { status: "unknown" },
433 message: isCommandMissingCause(error)
434 ? "Pi CLI (`pi`) is not installed or not on PATH. Install with `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`."
435 : "Failed to execute Pi CLI health check.",
436 },
437 });
438 }
439​
440 if (Option.isNone(versionResult.success)) {
441 return buildServerProvider({
442 presentation: PI_PRESENTATION,
443 enabled: piSettings.enabled,
444 checkedAt,
445 models: fallbackModels,
446 probe: {
447 installed: true,
448 version: null,
449 status: "error",
450 auth: { status: "unknown" },
451 message: "Pi CLI is installed but timed out while running `pi --version`.",
452 },
453 });
454 }
455​
456 const versionOutput = versionResult.success.value;
457 const version = parseCliVersionResult(versionOutput);
458 if (versionOutput.code !== 0) {
459 return buildServerProvider({
460 presentation: PI_PRESENTATION,
461 enabled: piSettings.enabled,
462 checkedAt,
463 models: fallbackModels,
464 probe: {
465 installed: true,
466 version,
467 status: "error",
468 auth: { status: "unknown" },
469 message: "Pi CLI is installed but failed to run.",
470 },
471 });
472 }
473​
474 if (version === null) {
475 return buildServerProvider({
476 presentation: PI_PRESENTATION,
477 enabled: piSettings.enabled,
478 checkedAt,
479 models: fallbackModels,
480 probe: {
481 installed: true,
482 version: null,
483 status: "error",
484 auth: { status: "unknown" },
485 message: `T3 Code could not determine the Pi version. Pi ${MINIMUM_PI_VERSION} or newer is required.`,
486 },
487 });
488 }
489​
490 if (compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
491 return buildServerProvider({
492 presentation: PI_PRESENTATION,
493 enabled: piSettings.enabled,
494 checkedAt,
495 models: fallbackModels,
496 probe: {
497 installed: true,
498 version,
499 status: "error",
500 auth: { status: "unknown" },
501 message: `Pi ${version} is unsupported. Update to Pi ${MINIMUM_PI_VERSION} or newer.`,
502 },
503 });
504 }
505​
506 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
507 if (!resolvedLaunchArgs.ok) {
508 return buildServerProvider({
509 presentation: PI_PRESENTATION,
510 enabled: piSettings.enabled,
511 checkedAt,
512 models: fallbackModels,
513 probe: {
514 installed: true,
515 version,
516 status: "error",
517 auth: { status: "unknown" },
518 message: resolvedLaunchArgs.message,
519 },
520 });
521 }
522​
523 const discoveryExit = yield* discoverPiViaRpc(
524 piSettings,
525 probeEnvironment,
526 resolvedLaunchArgs.args,
527 cwd,
528 ).pipe(
529 Effect.timeoutOption(
530 resolveProviderProbeTimeoutMs("pi", PI_RPC_DISCOVERY_TIMEOUT_MS, environment),
531 ),
532 Effect.exit,
533 );
534 if (Exit.isFailure(discoveryExit)) {
535 yield* Effect.logWarning("Pi RPC discovery failed.", {
536 errorTag: causeErrorTag(discoveryExit.cause),
537 });
538 return buildServerProvider({
539 presentation: PI_PRESENTATION,
540 enabled: piSettings.enabled,
541 checkedAt,
542 models: fallbackModels,
543 probe: {
544 installed: true,
545 version,
546 status: "ready",
547 auth: { status: "unknown" },
548 message:
549 "Pi is available, but T3 Code could not refresh its models and commands. The live session will retry startup.",
550 },
551 });
552 }
553 if (Option.isNone(discoveryExit.value)) {
554 return buildServerProvider({
555 presentation: PI_PRESENTATION,
556 enabled: piSettings.enabled,
557 checkedAt,
558 models: fallbackModels,
559 probe: {
560 installed: true,
561 version,
562 status: "ready",
563 auth: { status: "unknown" },
564 message:
565 "Pi is available, but model and command discovery needs interactive input. The live session will handle it.",
566 },
567 });
568 }
569​
570 const discovery = discoveryExit.value.value;
571 const models = piModelsFromSettings(piSettings.customModels, discovery.models);
572 const message = !discovery.authenticated
573 ? "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent."
574 : discovery.unavailableActiveModel === undefined
575 ? undefined
576 : yield* describeUnavailablePiModel(
577 piSettings,
578 probeEnvironment,
579 resolvedLaunchArgs.args,
580 discovery.unavailableActiveModel,
581 );
582 return {
583 ...buildServerProvider({
584 presentation: PI_PRESENTATION,
585 enabled: piSettings.enabled,
586 checkedAt,
587 models,
588 slashCommands: discovery.slashCommands,
589 skills: discovery.skills,
590 probe: {
591 installed: true,
592 version,
593 // Other Pi models still work when only the default is unavailable, so keep the picker usable.
594 status: discovery.authenticated ? "ready" : "warning",
595 auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },
596 ...(message === undefined ? {} : { message }),
597 },
598 }),
599 ...(discovery.textGenerationUnavailable ? { supportsTextGeneration: false } : {}),
600 };
601});
602​
603export const enrichPiSnapshot = (input: {
604 readonly snapshot: ServerProvider;
605 readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
606 readonly enableProviderUpdateChecks?: boolean;
607 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
608}): Effect.Effect<
609 void,
610 never,
611 HttpClient.HttpClient | ProviderLatestVersions.ProviderLatestVersions
612> => {
613 const { snapshot, publishSnapshot } = input;
614 return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {
615 enableProviderUpdateChecks: input.enableProviderUpdateChecks,
616 }).pipe(
617 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
618 Effect.catchCause((cause) =>
619 Effect.logWarning("Pi version advisory enrichment failed", {
620 errorTag: causeErrorTag(cause),
621 }),
622 ),
623 Effect.asVoid,
624 );
625};