import type { PaseoApi } from "@getpaseo/client"; import type { HostSummary } from "@getpaseo/protocol/hosts"; import type { Sprite } from "@fly/sprites"; import type { SpriteAgentSummary, SpriteHostSummary } from "../shared/contracts"; import { shellQuote, type SpritesManager } from "./sprites-manager"; const PREFERRED_PROVIDERS = [ "claude", "codex", "opencode", "pi", "antigravity", "omp", "muse", ]; const PATH_PREAMBLE = [ 'export PATH="$HOME/.npm-global/bin:$HOME/.local/bin:/usr/local/bin:$PATH"', 'for d in "$HOME"/.nvm/versions/node/*/bin "$HOME/.volta/bin" "$HOME/.local/share/mise/shims"; do [ -d "$d" ] && PATH="$d:$PATH"; done', "export PATH", ].join("; "); export function spriteHostSourceKey(spriteName: string): string { return `fly-sprite:${spriteName}`; } export function isSpriteHost(host: HostSummary): boolean { return ( host.source.key.startsWith("fly-sprite:") || host.metadata?.provider === "fly-sprites" ); } export function getHostSpriteName(host: HostSummary): string { if (typeof host.metadata?.spriteName === "string" && host.metadata.spriteName.trim()) { return host.metadata.spriteName.trim(); } if (host.source.key.startsWith("fly-sprite:")) { return host.source.key.slice("fly-sprite:".length); } return host.label || host.serverId || host.registrationId; } function toSpriteHostSummary(host: HostSummary): SpriteHostSummary { return { registrationId: host.registrationId, serverId: host.serverId, label: host.label ?? getHostSpriteName(host), spriteName: getHostSpriteName(host), status: host.status, error: host.error?.message ?? null, }; } function parseJsonObjectFromOutput(raw: string): Record | null { const start = raw.indexOf("{"); const end = raw.lastIndexOf("}"); if (start === -1 || end <= start) return null; try { return JSON.parse(raw.slice(start, end + 1)) as Record; } catch { return null; } } async function execSpriteBash(sprite: Sprite, script: string): Promise<{ exitCode: number; stdout: string; stderr: string }> { const fullScript = `${PATH_PREAMBLE}\n${script}`; try { const res = await sprite.execFile("bash", ["-lc", fullScript]); return { exitCode: res.exitCode ?? 0, stdout: typeof res.stdout === "string" ? res.stdout : res.stdout.toString("utf8"), stderr: typeof res.stderr === "string" ? res.stderr : res.stderr.toString("utf8"), }; } catch (error) { const execErr = error as { exitCode?: number; stdout?: string; stderr?: string; message?: string }; if (typeof execErr.exitCode === "number") { return { exitCode: execErr.exitCode, stdout: execErr.stdout ?? "", stderr: execErr.stderr ?? execErr.message ?? "", }; } throw error; } } async function ensurePaseoCliInSprite(sprite: Sprite): Promise { const check = await execSpriteBash(sprite, "command -v paseo || true"); const existingBin = check.stdout.trim().split(/\r?\n/).find(Boolean); if (existingBin) return existingBin; const installRes = await execSpriteBash( sprite, [ 'if ! command -v npm >/dev/null 2>&1; then echo "npm is required to install @getpaseo/cli inside the Sprite" >&2; exit 1; fi', 'if ! npm install -g @getpaseo/cli >/tmp/paseo-install.log 2>&1; then', ' mkdir -p "$HOME/.npm-global/bin"', ' npm config set prefix "$HOME/.npm-global"', ' npm install -g @getpaseo/cli >>/tmp/paseo-install.log 2>&1 || { cat /tmp/paseo-install.log >&2; exit 1; }', "fi", "command -v paseo", ].join("\n"), ); const installedBin = installRes.stdout.trim().split(/\r?\n/).find(Boolean); if (installRes.exitCode !== 0 || !installedBin) { const detail = (installRes.stderr || installRes.stdout).trim(); throw new Error(`Could not install @getpaseo/cli inside Sprite ${sprite.name}: ${detail || `exit ${installRes.exitCode}`}`); } return installedBin; } async function readPairingConnectionInSprite(sprite: Sprite): Promise { const res = await execSpriteBash(sprite, "paseo daemon pair --relay --json"); if (res.exitCode !== 0) { const detail = (res.stderr || res.stdout).trim(); throw new Error(`Failed to get relay pairing offer from Sprite ${sprite.name}: ${detail || `exit ${res.exitCode}`}`); } const parsed = parseJsonObjectFromOutput(res.stdout); const connectionUri = typeof parsed?.connectionUri === "string" ? parsed.connectionUri.trim() : ""; const url = typeof parsed?.url === "string" ? parsed.url.trim() : ""; const connection = connectionUri || url; if (!connection) { throw new Error(`Sprite ${sprite.name} did not return a Paseo pairing URL.`); } return connection; } async function isSpriteDaemonReachable(sprite: Sprite): Promise { const res = await execSpriteBash(sprite, "paseo daemon status --json 2>/dev/null || true"); const parsed = parseJsonObjectFromOutput(res.stdout); return parsed?.connectedDaemon === "reachable"; } async function drainServiceStream(stream: Awaited>): Promise { try { for await (const event of stream) { if (event.type === "started" || event.type === "complete" || event.type === "error") { break; } } } catch { // Ignore stream timeout/close after service start. } finally { stream.close(); } } async function ensureSpriteDaemonRunning(sprite: Sprite, paseoBin: string): Promise { if (await isSpriteDaemonReachable(sprite)) return; const lastSlash = paseoBin.lastIndexOf("/"); const binDir = lastSlash > 0 ? paseoBin.slice(0, lastSlash) : ""; const serviceCmd = binDir ? `export PATH=${shellQuote(binDir)}:"$PATH"; exec paseo daemon run` : "exec paseo daemon run"; let serviceStarted = false; try { const existing = await sprite.getService("paseo").catch(() => null); if (!existing) { const stream = await sprite.createService( "paseo", { cmd: "bash", args: ["-lc", serviceCmd], httpPort: 6767, }, "3s", ); await drainServiceStream(stream); serviceStarted = true; } else if (existing.state?.status !== "running") { const stream = await sprite.startService("paseo", "3s"); await drainServiceStream(stream); serviceStarted = true; } else { serviceStarted = true; } } catch { serviceStarted = false; } if (serviceStarted) { const deadline = Date.now() + 20_000; while (Date.now() < deadline) { if (await isSpriteDaemonReachable(sprite)) return; await new Promise((r) => setTimeout(r, 750)); } } const startRes = await execSpriteBash(sprite, "paseo start --timeout 30 --json"); if (startRes.exitCode !== 0 && !(await isSpriteDaemonReachable(sprite))) { const detail = (startRes.stderr || startRes.stdout).trim(); throw new Error(`Failed to start Paseo daemon inside Sprite ${sprite.name}: ${detail || `exit ${startRes.exitCode}`}`); } } async function waitForHostOnline( paseo: PaseoApi, registrationId: string, timeoutMs = 25_000, ): Promise { const deadline = Date.now() + timeoutMs; let last: HostSummary | undefined; while (Date.now() < deadline) { const dir = await paseo.hosts.list(); const found = dir.hosts.find((h) => h.registrationId === registrationId); if (found) { last = found; if (found.status === "online" && found.serverId) { return found; } if (found.status === "error" && found.error) { throw new Error(`Sprite host connection error: ${found.error.message}`); } } await new Promise((r) => setTimeout(r, 600)); } const detail = last?.error?.message ? ` (${last.error.message})` : ` (status: ${last?.status ?? "unknown"})`; throw new Error(`Timed out waiting for Sprite host to come online${detail}`); } export async function ensureSpriteHost(options: { manager: SpritesManager; paseo: PaseoApi; spriteName?: string; syncLocalPath?: string; remoteDir?: string; }): Promise<{ spriteName: string; serverId: string; registrationId: string; remoteDir: string; syncedFiles?: number; }> { const ensured = await options.manager.ensureSprite({ name: options.spriteName, syncLocalPath: options.syncLocalPath, remoteDir: options.remoteDir, }); const sprite = ensured.sprite; const sourceKey = spriteHostSourceKey(sprite.name); const dir = await options.paseo.hosts.list(); const existing = dir.hosts.find((h) => h.source.key === sourceKey); if (existing && existing.enabled && existing.status === "online" && existing.serverId) { return { spriteName: sprite.name, serverId: existing.serverId, registrationId: existing.registrationId, remoteDir: ensured.remoteDir, syncedFiles: ensured.syncedFiles, }; } const paseoBin = await ensurePaseoCliInSprite(sprite); const connection = await readPairingConnectionInSprite(sprite); await ensureSpriteDaemonRunning(sprite, paseoBin); let registration: HostSummary; if (existing) { registration = await options.paseo.hosts.update(existing.registrationId, { connection, enabled: true, label: sprite.name, metadata: { provider: "fly-sprites", spriteName: sprite.name }, }); } else { registration = await options.paseo.hosts.add({ connection, label: sprite.name, sourceKey, metadata: { provider: "fly-sprites", spriteName: sprite.name }, }); } const online = registration.status === "online" && registration.serverId ? registration : await waitForHostOnline(options.paseo, registration.registrationId); return { spriteName: sprite.name, serverId: online.serverId!, registrationId: online.registrationId, remoteDir: ensured.remoteDir, syncedFiles: ensured.syncedFiles, }; } async function resolveProviderOnSprite( spritePaseo: PaseoApi, cwd: string, requested?: string, ): Promise { const trimmed = requested?.trim(); if (trimmed && trimmed.toLowerCase() !== "auto" && trimmed.includes("/")) { return trimmed; } const snap = await spritePaseo.providers .waitForReady({ cwd, timeoutMs: 15_000 }) .catch(() => spritePaseo.providers.snapshot({ cwd })); const entries = snap.entries ?? []; const findModel = async (entry: (typeof entries)[number]): Promise => { const models = entry.models?.length ? entry.models : await spritePaseo.providers .listModels(entry.provider, { cwd }) .then((r) => r.models ?? []) .catch(() => []); const chosen = models.find((m) => m.isDefault) ?? models[0]; return chosen ? `${entry.provider}/${chosen.id}` : null; }; if (trimmed && trimmed.toLowerCase() !== "auto") { const matched = entries.find((e) => e.provider === trimmed); if (!matched) { throw new Error(`Provider "${trimmed}" is not available on this Sprite host.`); } const model = await findModel(matched); if (!model) { throw new Error(`Provider "${trimmed}" has no models available on this Sprite host.`); } return model; } const available = entries.filter( (e) => e.status === "ready" && e.enabled !== false && e.provider !== "fly-sprites", ); available.sort((a, b) => { const ai = PREFERRED_PROVIDERS.indexOf(a.provider); const bi = PREFERRED_PROVIDERS.indexOf(b.provider); return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi); }); for (const entry of available) { const model = await findModel(entry); if (model) return model; } const diagnostics = entries .filter((e) => e.enabled !== false) .map((e) => `${e.provider}: ${e.status}${e.error ? ` (${e.error})` : ""}`) .join("; "); throw new Error( `No coding agent provider is available inside the Sprite yet. ${diagnostics || "Install/authenticate Claude Code, Codex, or another Paseo provider on the Sprite."}`, ); } export async function launchSpriteAgent(options: { manager: SpritesManager; paseo: PaseoApi; spriteName?: string; title?: string; prompt?: string; syncLocalPath?: string; remoteDir?: string; provider?: string; background?: boolean; }): Promise<{ agentId: string; serverId: string; spriteName: string; provider: string; remoteDir: string; syncedFiles?: number; }> { const host = await ensureSpriteHost({ manager: options.manager, paseo: options.paseo, spriteName: options.spriteName, syncLocalPath: options.syncLocalPath, remoteDir: options.remoteDir, }); const spritePaseo = await options.paseo.hosts.client(host.serverId); try { const wsList = await spritePaseo.workspaces.list(); const existingWs = wsList.entries.find( (ws) => !ws.archivingAt && (ws.workspaceDirectory === host.remoteDir || ws.projectRootPath === host.remoteDir), ); if (!existingWs) { await spritePaseo.workspaces.create({ source: { kind: "directory", path: host.remoteDir }, title: host.spriteName, }); } const providerModel = await resolveProviderOnSprite( spritePaseo, host.remoteDir, options.provider, ); const handle = await spritePaseo.agents.create({ config: { provider: providerModel, }, cwd: host.remoteDir, title: options.title?.trim() || undefined, prompt: options.prompt?.trim() || undefined, background: options.background, }); return { agentId: handle.id, serverId: host.serverId, spriteName: host.spriteName, provider: providerModel, remoteDir: host.remoteDir, syncedFiles: host.syncedFiles, }; } finally { await spritePaseo.dispose().catch(() => undefined); } } export async function listSpriteHostsWithAgents(paseo: PaseoApi): Promise<{ hosts: SpriteHostSummary[]; agents: SpriteAgentSummary[]; }> { const dir = await paseo.hosts.list(); const spriteHosts = dir.hosts.filter(isSpriteHost); const hosts = spriteHosts.map(toSpriteHostSummary); const agents: SpriteAgentSummary[] = []; await Promise.all( spriteHosts.map(async (host) => { if (host.status !== "online" || !host.serverId) return; const spriteName = getHostSpriteName(host); const client = await paseo.hosts.client(host.serverId).catch(() => null); if (!client) return; try { const listed = await client.agents.list(); for (const entry of listed.entries) { const a = entry.agent; if (a.archivedAt) continue; agents.push({ agentId: a.id, serverId: host.serverId, hostLabel: host.label ?? spriteName, spriteName, title: a.title ?? null, status: a.status, provider: a.provider, model: a.model ?? null, cwd: a.cwd, lastError: typeof a.lastError === "string" ? a.lastError : null, pendingPermissionsCount: a.pendingPermissions?.length ?? 0, updatedAt: a.updatedAt, }); } } catch { // Ignore transient host read errors when listing. } finally { await client.dispose().catch(() => undefined); } }), ); agents.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); return { hosts, agents }; } export async function removeSpriteHostRegistration( paseo: PaseoApi, spriteName: string, ): Promise { const dir = await paseo.hosts.list(); const sourceKey = spriteHostSourceKey(spriteName); const matches = dir.hosts.filter( (h) => h.source.key === sourceKey || h.metadata?.spriteName === spriteName, ); for (const host of matches) { await paseo.hosts.remove(host.registrationId).catch(() => undefined); } }