Files
fly-sprites-workers/server/sprite-hosts.ts
T

673 lines
23 KiB
TypeScript

import type { PluginHandlerContext } from "@getpaseo/plugin/server";
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";
type PaseoApi = PluginHandlerContext["paseo"];
const PREFERRED_PROVIDERS = [
"antigravity",
"claude",
"codex",
"opencode",
"pi",
"omp",
"muse",
];
const PATH_PREAMBLE = [
'export PATH="$HOME/.npm-global/bin:$HOME/.local/bin:/.sprite/bin:/usr/local/bin:$PATH"',
'for d in /.sprite/languages/node/nvm/versions/node/*/bin "$HOME"/.nvm/versions/node/*/bin "$HOME/.volta/bin" "$HOME/.local/share/mise/shims"; do [ -d "$d" ] && PATH="$d:$PATH"; done',
"export PATH",
].join("; ");
const RESOLVE_PASEO_BIN_SNIPPET = [
'PASEO_BIN="$(command -v paseo 2>/dev/null || true)"',
'if [ -z "$PASEO_BIN" ] && command -v npm >/dev/null 2>&1; then',
' _npm_prefix="$(npm prefix -g 2>/dev/null || true)"',
' if [ -n "$_npm_prefix" ] && [ -x "$_npm_prefix/bin/paseo" ]; then',
' PASEO_BIN="$_npm_prefix/bin/paseo"',
" fi",
"fi",
'if [ -n "$PASEO_BIN" ] && [ ! -e "$HOME/.local/bin/paseo" ]; then',
' mkdir -p "$HOME/.local/bin" && ln -sf "$PASEO_BIN" "$HOME/.local/bin/paseo" 2>/dev/null || true',
"fi",
].join("\n");
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;
}
// Time-box a promise so a hung host can't stall status RPC.
function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<T> {
return Promise.race([
promise,
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms)),
]);
}
const HOST_AGENTS_CACHE_TTL_MS = 8_000;
const hostAgentsCache = new WeakMap<object, { at: number; value: { hosts: SpriteHostSummary[]; agents: SpriteAgentSummary[] } }>();
const hostAgentsInFlight = new WeakMap<object, Promise<{ hosts: SpriteHostSummary[]; agents: SpriteAgentSummary[] }>>();
export function invalidateSpriteHostsCache(paseo: PaseoApi): void {
hostAgentsCache.delete(paseo as object);
}
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<string, unknown> | null {
const trimmed = raw.trim();
if (!trimmed) return null;
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
// Fall through to scan for embedded JSON object.
}
}
const end = raw.lastIndexOf("}");
if (end === -1) return null;
const candidateStarts: number[] = [];
let idx = raw.indexOf("{");
while (idx !== -1 && idx < end) {
if (idx === 0 || raw[idx - 1] === "\n" || raw[idx - 1] === "\r") {
candidateStarts.push(idx);
}
idx = raw.indexOf("{", idx + 1);
}
for (let i = candidateStarts.length - 1; i >= 0; i--) {
try {
const parsed = JSON.parse(raw.slice(candidateStarts[i], end + 1));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
// Try earlier start position.
}
}
const first = raw.indexOf("{");
if (first === -1 || end <= first) return null;
try {
const parsed = JSON.parse(raw.slice(first, end + 1));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
return null;
}
return null;
}
function findAbsolutePathLine(stdout: string): string | undefined {
const lines = stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i].startsWith("/")) return lines[i];
}
return lines[lines.length - 1];
}
async function execSpriteBash(
sprite: Sprite,
script: string,
options?: { timeoutMs?: number },
): Promise<{ exitCode: number; stdout: string; stderr: string }> {
const fullScript = `${PATH_PREAMBLE}\n${script}`;
try {
const res = await sprite.execFile("bash", ["-c", fullScript], {
timeout: options?.timeoutMs ?? 60_000,
});
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,
onProgress?: (phase: string) => void,
): Promise<string> {
onProgress?.("Checking Paseo CLI in Sprite…");
const check = await execSpriteBash(
sprite,
`${RESOLVE_PASEO_BIN_SNIPPET}\n[ -n "$PASEO_BIN" ] && printf '%s\\n' "$PASEO_BIN" || true`,
{ timeoutMs: 25_000 },
);
const existingBin = findAbsolutePathLine(check.stdout);
if (existingBin) return existingBin;
onProgress?.("Installing @getpaseo/cli in Sprite (this may take a minute)…");
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 --no-audit --no-fund @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 --no-audit --no-fund @getpaseo/cli >>/tmp/paseo-install.log 2>&1 || { cat /tmp/paseo-install.log >&2; exit 1; }',
"fi",
"hash -r 2>/dev/null || true",
RESOLVE_PASEO_BIN_SNIPPET,
'if [ -z "$PASEO_BIN" ]; then',
' echo "paseo binary not found after npm install (npm prefix -g: $(npm prefix -g 2>/dev/null || echo unknown))" >&2',
' tail -n 30 /tmp/paseo-install.log >&2 || true',
" exit 1",
"fi",
'printf "%s\\n" "$PASEO_BIN"',
].join("\n"),
{ timeoutMs: 180_000 },
);
const installedBin = findAbsolutePathLine(installRes.stdout);
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<string> {
const res = await execSpriteBash(sprite, "paseo daemon pair --relay --json", { timeoutMs: 30_000 });
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<boolean> {
const res = await execSpriteBash(sprite, "paseo daemon status --json 2>/dev/null || true", {
timeoutMs: 15_000,
});
const parsed = parseJsonObjectFromOutput(res.stdout);
return parsed?.connectedDaemon === "reachable";
}
async function restartSpriteDaemonWorker(sprite: Sprite): Promise<void> {
await execSpriteBash(sprite, "paseo restart 2>/dev/null || true", { timeoutMs: 25_000 }).catch(
() => undefined,
);
const deadline = Date.now() + 15_000;
while (Date.now() < deadline) {
if (await isSpriteDaemonReachable(sprite)) return;
await new Promise((r) => setTimeout(r, 600));
}
}
async function drainServiceStream(
stream: Awaited<ReturnType<Sprite["createService"]>>,
timeoutMs = 6_000,
): Promise<void> {
const timer = setTimeout(() => {
try {
stream.close();
} catch {
// Ignore close errors on timeout.
}
}, timeoutMs);
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 {
clearTimeout(timer);
try {
stream.close();
} catch {
// Ignore already-closed stream.
}
}
}
async function ensureSpriteDaemonRunning(
sprite: Sprite,
paseoBin: string,
onProgress?: (phase: string) => void,
options?: { restartIfRunning?: boolean },
): Promise<void> {
onProgress?.("Checking Paseo daemon in Sprite…");
if (await isSpriteDaemonReachable(sprite)) {
if (options?.restartIfRunning) {
onProgress?.("Refreshing Paseo providers in Sprite…");
await restartSpriteDaemonWorker(sprite);
}
return;
}
onProgress?.("Starting Paseo daemon in Sprite…");
const lastSlash = paseoBin.lastIndexOf("/");
const binDir = lastSlash > 0 ? paseoBin.slice(0, lastSlash) : "";
const serviceCmd = binDir
? `${PATH_PREAMBLE}; export PATH=${shellQuote(binDir)}:"$PATH"; exec paseo daemon run`
: `${PATH_PREAMBLE}; 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: ["-c", 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) {
onProgress?.("Waiting for Paseo daemon in Sprite…");
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
if (await isSpriteDaemonReachable(sprite)) return;
await new Promise((r) => setTimeout(r, 750));
}
}
onProgress?.("Starting Paseo daemon directly in Sprite…");
const startRes = await execSpriteBash(sprite, "paseo start --timeout 30 --json", {
timeoutMs: 45_000,
});
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 = 35_000,
): Promise<HostSummary> {
const deadline = Date.now() + timeoutMs;
let last: HostSummary | undefined;
while (Date.now() < deadline) {
const dir = await withTimeout(paseo.hosts.list(), 5_000, null).catch(() => null);
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;
onProgress?: (phase: string, spriteName?: string) => void;
onHostReady?: (spriteName: string) => void;
}): 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,
onProgress: options.onProgress,
});
const sprite = ensured.sprite;
const sourceKey = spriteHostSourceKey(sprite.name);
const progress = (phase: string) => options.onProgress?.(phase, sprite.name);
progress("Checking existing Paseo host…");
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) {
if (ensured.antigravityAuthChanged) {
progress("Refreshing Paseo providers in Sprite…");
await restartSpriteDaemonWorker(sprite);
await waitForHostOnline(options.paseo, existing.registrationId, 20_000).catch(() => existing);
}
options.onHostReady?.(sprite.name);
return {
spriteName: sprite.name,
serverId: existing.serverId,
registrationId: existing.registrationId,
remoteDir: ensured.remoteDir,
syncedFiles: ensured.syncedFiles,
};
}
const paseoBin = await ensurePaseoCliInSprite(sprite, progress);
progress("Reading relay pairing offer from Sprite…");
const connection = await readPairingConnectionInSprite(sprite);
await ensureSpriteDaemonRunning(sprite, paseoBin, progress, {
restartIfRunning: ensured.antigravityAuthChanged,
});
progress("Registering Sprite host with Paseo…");
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 },
});
}
invalidateSpriteHostsCache(options.paseo);
options.onHostReady?.(sprite.name);
let online: HostSummary;
if (registration.status === "online" && registration.serverId) {
online = registration;
} else {
progress("Waiting for Sprite host to come online…");
online = await waitForHostOnline(options.paseo, registration.registrationId);
}
invalidateSpriteHostsCache(options.paseo);
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<string> {
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<string | null> => {
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;
onProgress?: (phase: string, spriteName?: string) => void;
onHostReady?: (spriteName: string) => void;
}): 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,
onProgress: options.onProgress,
onHostReady: options.onHostReady,
});
const progress = (phase: string) => options.onProgress?.(phase, host.spriteName);
progress("Connecting to Sprite host…");
const spritePaseo = await options.paseo.hosts.client(host.serverId);
try {
progress("Preparing workspace on Sprite…");
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,
});
}
progress("Resolving coding agent provider…");
const providerModel = await resolveProviderOnSprite(
spritePaseo,
host.remoteDir,
options.provider,
);
progress(`Launching ${providerModel} agent…`);
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,
});
invalidateSpriteHostsCache(options.paseo);
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 cached = hostAgentsCache.get(paseo as object);
if (cached && Date.now() - cached.at < HOST_AGENTS_CACHE_TTL_MS) return cached.value;
const inFlight = hostAgentsInFlight.get(paseo as object);
if (inFlight) return inFlight;
const work = (async (): Promise<{ hosts: SpriteHostSummary[]; agents: SpriteAgentSummary[] }> => {
const dir = await withTimeout(paseo.hosts.list(), 3_000, { hosts: [] } as never);
const spriteHosts = dir.hosts.filter(isSpriteHost);
const hosts = spriteHosts.map(toSpriteHostSummary);
const perHost = await Promise.all(
spriteHosts.map(async (host): Promise<SpriteAgentSummary[]> => {
const serverId = host.serverId;
if (host.status !== "online" || !serverId) return [];
const spriteName = getHostSpriteName(host);
const client = await withTimeout(paseo.hosts.client(serverId), 2_500, null).catch(() => null);
if (!client) return [];
try {
const listed = await withTimeout(client.agents.list(), 2_500, { entries: [] } as never);
return listed.entries.flatMap((entry) => {
const a = entry.agent;
if (a.archivedAt) return [];
return [{
agentId: a.id,
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 {
return [];
} finally {
await client.dispose().catch(() => undefined);
}
}),
);
const agents = perHost.flat();
agents.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
const value = { hosts, agents };
hostAgentsCache.set(paseo as object, { at: Date.now(), value });
return value;
})();
hostAgentsInFlight.set(paseo as object, work);
try { return await work; } finally { hostAgentsInFlight.delete(paseo as object); }
}
export async function removeSpriteHostRegistration(
paseo: PaseoApi,
spriteName: string,
): Promise<void> {
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);
}
invalidateSpriteHostsCache(paseo);
}