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