/** summary: "Loads workstation inference contracts, registers provider models, streams completions, and exposes status and refresh commands." read_when: - "Changing workstation contract validation, health checks, provider registration, model streaming, or lane-op commands." */ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { inheritedAuthorityTransportFromEnvironment, WORKBENCH_AUTHORITY_FD_ENV, WorkbenchInheritedAuthorityChannel, } from "./workstation-authority-channel.ts"; import { sendAudioTurn, sendWorkbenchAudioTurn } from "./workstation-inference-audio-turn.ts"; import { CANARY_CONTRACT_ENV, CONTRACT_ENV, CONTRACT_JSON_ENV, type ContractStatus, contractApiKey, DEFAULT_PROVIDER_ID, DEFAULT_PROVIDER_NAME, DEFAULT_WORKSTATION_ROOT, defaultContractPath, defaultHealthUrl, defaultInklingContractPath, INKLING_CONTRACT_ENV, LANE_OP_SCRIPT, normalizeBaseUrl, notifyOrLog, primeWorkstationHealth, providerModel, resolveContractStatus, WORKSTATION_API_ID, WORKSTATION_ROOT_ENV, type WorkstationInferenceContract, workstationProviderHotPathStatus, workstationRoot, } from "./workstation-inference-contract.ts"; import { quarantineCurrentAudio, streamWorkstationInference, } from "./workstation-inference-stream.ts"; export { sendWorkbenchAudioTurn } from "./workstation-inference-audio-turn.ts"; export { clearWorkstationContractCache, clearWorkstationHealthCache, clearWorkstationProviderCaches, primeWorkstationHealth, providerModel, refreshWorkstationContractGeneration, resolveContractStatus, workstationProviderHotPathStatus, } from "./workstation-inference-contract.ts"; export { streamWorkstationInference } from "./workstation-inference-stream.ts"; async function runLaneOp( pi: ExtensionAPI, args: string[], ): Promise<{ ok: true; stdout: string } | { ok: false; detail: string }> { const result = await pi.exec("python3", [LANE_OP_SCRIPT, ...args], { cwd: workstationRoot(), timeout: 60_000, }); if (result.code !== 0) { return { ok: false, detail: [ `lane-op exited ${result.code}`, result.stderr.trim() ? `stderr: ${result.stderr.trim()}` : undefined, result.stdout.trim() ? `stdout: ${result.stdout.trim()}` : undefined, ] .filter((line): line is string => Boolean(line)) .join("\n"), }; } return { ok: true, stdout: result.stdout.trim() }; } function statusText(status: ContractStatus): string { const contract = status.contract; const generation = status.generation; const unhealthy = status.health?.filter((entry) => entry.unhealthy).length ?? 0; const lines = [ `status: ${status.status}`, `summary: ${status.summary}`, status.source ? `source: ${status.source}` : undefined, status.detail ? `detail: ${status.detail}` : undefined, generation?.initialized ? `contract_generation: ${generation.generationId} (${generation.modelCount} models from ${generation.sourceCount} sources)` : "contract_generation: uninitialized", generation?.refreshInFlight ? "contract_refresh: in-flight" : undefined, generation?.lastRefreshError ? `contract_refresh_error: ${generation.lastRefreshError}` : undefined, status.health ? `health_cache: ${status.health.length} endpoints, ${unhealthy} unhealthy` : undefined, contract ? `provider: ${contract.provider_id ?? DEFAULT_PROVIDER_ID}` : undefined, contract ? `base_url: ${normalizeBaseUrl(contract.base_url)}` : undefined, contract ? `health_url: ${contract.health_url ?? defaultHealthUrl(contract)}` : undefined, contract ? `authority: ${contract.authority ?? "unspecified"}` : undefined, contract ? `family/surface: ${contract.family ?? "?"}/${contract.surface ?? "?"}` : undefined, contract ? `models: ${contract.models.map((model) => model.pi_model_id ?? model.id).join(", ")}` : undefined, contract?.recovery_hint ? `recovery_hint: ${contract.recovery_hint}` : undefined, ]; return lines.filter((line): line is string => Boolean(line)).join("\n"); } function registerContractProvider( pi: ExtensionAPI, contract: WorkstationInferenceContract, ): string { const providerId = contract.provider_id ?? DEFAULT_PROVIDER_ID; pi.registerProvider(providerId, { name: contract.provider_name ?? DEFAULT_PROVIDER_NAME, baseUrl: normalizeBaseUrl(contract.base_url), apiKey: contractApiKey(contract), api: WORKSTATION_API_ID, models: contract.models.map(providerModel), streamSimple: (model, context, options) => streamWorkstationInference(model, context, options, pi), }); return providerId; } export default async function (pi: ExtensionAPI) { try { await quarantineCurrentAudio(pi, "extension-reload-before-provider-dispatch"); } catch { // A failed disposition is indeterminate and never authorizes retry or release. } const initial = await resolveContractStatus({ checkHealth: false }); if (typeof pi.on === "function") { const dispose = (reason: string) => async () => { try { await quarantineCurrentAudio(pi, reason); } catch { // Lifecycle cleanup failure cannot grant provider or scheduler authority. } }; pi.on("agent_end", dispose("agent-ended-before-provider-dispatch")); pi.on("model_select", dispose("model-changed-before-provider-dispatch")); pi.on("session_before_switch", dispose("session-switched-before-provider-dispatch")); pi.on("session_shutdown", dispose("session-shutdown-before-provider-dispatch")); } pi.registerCommand("workstation-inference", { description: "Show read-only workstation inference provider status", handler: async (args, ctx) => { const trimmed = args.trim(); const firstSpace = trimmed.search(/\s/); const action = (firstSpace < 0 ? trimmed : trimmed.slice(0, firstSpace)).toLowerCase() || "status"; const actionArgs = firstSpace < 0 ? "" : trimmed.slice(firstSpace + 1).trim(); if (action === "help") { notifyOrLog( ctx, [ "/workstation-inference status Reload contracts and show blocking health status", "/workstation-inference hot-path Show in-memory generation and health-cache status", "/workstation-inference refresh Ask lane-op to refresh canonical and canary provider contracts", "/workstation-inference lane-status Show lane-op baseline-text status", "/workstation-inference contract Show the expected contract path/env", "/workstation-inference audio-send --handoff --scheduler-db