feat: add async Sprite job manager with progress polling
- Add SpriteJobManager and job RPCs (start/get/list) for connect, launch, create, and sync operations - Time-box status RPC with 5s remote timeout and lazy remote fetching - Cache remote sprites, raw token, and host/agent lists to avoid redundant API calls - Harden sprite host exec timeouts, JSON parsing, and npm install with --no-audit --no-fund - UI: poll active jobs with phase updates in workers screen - Reduce token exchange and OpenBao request timeout to 8s
This commit is contained in:
1 parent
32c02cb3cd
commit
36d88ef168
8 files changed
+1142
-186
No files matched your search
+201
-67
@@ -41,6 +41,22 @@ export function getHostSpriteName(host: HostSummary): string {
|
||||
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,
|
||||
@@ -53,20 +69,76 @@ function toSpriteHostSummary(host: HostSummary): SpriteHostSummary {
|
||||
}
|
||||
|
||||
function parseJsonObjectFromOutput(raw: string): Record<string, unknown> | null {
|
||||
const start = raw.indexOf("{");
|
||||
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 (start === -1 || end <= start) return null;
|
||||
if (end === -1) return null;
|
||||
|
||||
// Prefer JSON objects starting at the beginning of a line (avoids matching `{...}` inside log lines).
|
||||
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 {
|
||||
return JSON.parse(raw.slice(start, end + 1)) as Record<string, unknown>;
|
||||
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;
|
||||
}
|
||||
|
||||
async function execSpriteBash(sprite: Sprite, script: string): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
||||
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", ["-lc", fullScript]);
|
||||
const res = await sprite.execFile("bash", ["-lc", fullScript], {
|
||||
timeout: options?.timeoutMs ?? 60_000,
|
||||
});
|
||||
return {
|
||||
exitCode: res.exitCode ?? 0,
|
||||
stdout: typeof res.stdout === "string" ? res.stdout : res.stdout.toString("utf8"),
|
||||
@@ -85,25 +157,31 @@ async function execSpriteBash(sprite: Sprite, script: string): Promise<{ exitCod
|
||||
}
|
||||
}
|
||||
|
||||
async function ensurePaseoCliInSprite(sprite: Sprite): Promise<string> {
|
||||
const check = await execSpriteBash(sprite, "command -v paseo || true");
|
||||
const existingBin = check.stdout.trim().split(/\r?\n/).find(Boolean);
|
||||
async function ensurePaseoCliInSprite(
|
||||
sprite: Sprite,
|
||||
onProgress?: (phase: string) => void,
|
||||
): Promise<string> {
|
||||
onProgress?.("Checking Paseo CLI in Sprite…");
|
||||
const check = await execSpriteBash(sprite, "command -v paseo || 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 @getpaseo/cli >/tmp/paseo-install.log 2>&1; then',
|
||||
'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 @getpaseo/cli >>/tmp/paseo-install.log 2>&1 || { cat /tmp/paseo-install.log >&2; exit 1; }',
|
||||
' npm install -g --no-audit --no-fund @getpaseo/cli >>/tmp/paseo-install.log 2>&1 || { cat /tmp/paseo-install.log >&2; exit 1; }',
|
||||
"fi",
|
||||
"command -v paseo",
|
||||
].join("\n"),
|
||||
{ timeoutMs: 180_000 },
|
||||
);
|
||||
|
||||
const installedBin = installRes.stdout.trim().split(/\r?\n/).find(Boolean);
|
||||
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}`}`);
|
||||
@@ -112,7 +190,7 @@ async function ensurePaseoCliInSprite(sprite: Sprite): Promise<string> {
|
||||
}
|
||||
|
||||
async function readPairingConnectionInSprite(sprite: Sprite): Promise<string> {
|
||||
const res = await execSpriteBash(sprite, "paseo daemon pair --relay --json");
|
||||
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}`}`);
|
||||
@@ -128,12 +206,24 @@ async function readPairingConnectionInSprite(sprite: Sprite): Promise<string> {
|
||||
}
|
||||
|
||||
async function isSpriteDaemonReachable(sprite: Sprite): Promise<boolean> {
|
||||
const res = await execSpriteBash(sprite, "paseo daemon status --json 2>/dev/null || true");
|
||||
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 drainServiceStream(stream: Awaited<ReturnType<Sprite["createService"]>>): Promise<void> {
|
||||
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") {
|
||||
@@ -143,18 +233,29 @@ async function drainServiceStream(stream: Awaited<ReturnType<Sprite["createServi
|
||||
} catch {
|
||||
// Ignore stream timeout/close after service start.
|
||||
} finally {
|
||||
stream.close();
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
stream.close();
|
||||
} catch {
|
||||
// Ignore already-closed stream.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureSpriteDaemonRunning(sprite: Sprite, paseoBin: string): Promise<void> {
|
||||
async function ensureSpriteDaemonRunning(
|
||||
sprite: Sprite,
|
||||
paseoBin: string,
|
||||
onProgress?: (phase: string) => void,
|
||||
): Promise<void> {
|
||||
onProgress?.("Checking Paseo daemon in Sprite…");
|
||||
if (await isSpriteDaemonReachable(sprite)) return;
|
||||
|
||||
onProgress?.("Starting Paseo daemon in Sprite…");
|
||||
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";
|
||||
? `${PATH_PREAMBLE}; export PATH=${shellQuote(binDir)}:"$PATH"; exec paseo daemon run`
|
||||
: `${PATH_PREAMBLE}; exec paseo daemon run`;
|
||||
|
||||
let serviceStarted = false;
|
||||
try {
|
||||
@@ -183,6 +284,7 @@ async function ensureSpriteDaemonRunning(sprite: Sprite, paseoBin: string): Prom
|
||||
}
|
||||
|
||||
if (serviceStarted) {
|
||||
onProgress?.("Waiting for Paseo daemon in Sprite…");
|
||||
const deadline = Date.now() + 20_000;
|
||||
while (Date.now() < deadline) {
|
||||
if (await isSpriteDaemonReachable(sprite)) return;
|
||||
@@ -190,7 +292,10 @@ async function ensureSpriteDaemonRunning(sprite: Sprite, paseoBin: string): Prom
|
||||
}
|
||||
}
|
||||
|
||||
const startRes = await execSpriteBash(sprite, "paseo start --timeout 30 --json");
|
||||
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}`}`);
|
||||
@@ -200,13 +305,13 @@ async function ensureSpriteDaemonRunning(sprite: Sprite, paseoBin: string): Prom
|
||||
async function waitForHostOnline(
|
||||
paseo: PaseoApi,
|
||||
registrationId: string,
|
||||
timeoutMs = 25_000,
|
||||
timeoutMs = 35_000,
|
||||
): Promise<HostSummary> {
|
||||
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);
|
||||
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) {
|
||||
@@ -228,6 +333,7 @@ export async function ensureSpriteHost(options: {
|
||||
spriteName?: string;
|
||||
syncLocalPath?: string;
|
||||
remoteDir?: string;
|
||||
onProgress?: (phase: string, spriteName?: string) => void;
|
||||
}): Promise<{
|
||||
spriteName: string;
|
||||
serverId: string;
|
||||
@@ -239,10 +345,13 @@ export async function ensureSpriteHost(options: {
|
||||
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) {
|
||||
@@ -255,10 +364,12 @@ export async function ensureSpriteHost(options: {
|
||||
};
|
||||
}
|
||||
|
||||
const paseoBin = await ensurePaseoCliInSprite(sprite);
|
||||
const paseoBin = await ensurePaseoCliInSprite(sprite, progress);
|
||||
progress("Reading relay pairing offer from Sprite…");
|
||||
const connection = await readPairingConnectionInSprite(sprite);
|
||||
await ensureSpriteDaemonRunning(sprite, paseoBin);
|
||||
await ensureSpriteDaemonRunning(sprite, paseoBin, progress);
|
||||
|
||||
progress("Registering Sprite host with Paseo…");
|
||||
let registration: HostSummary;
|
||||
if (existing) {
|
||||
registration = await options.paseo.hosts.update(existing.registrationId, {
|
||||
@@ -275,11 +386,16 @@ export async function ensureSpriteHost(options: {
|
||||
metadata: { provider: "fly-sprites", spriteName: sprite.name },
|
||||
});
|
||||
}
|
||||
invalidateSpriteHostsCache(options.paseo);
|
||||
|
||||
const online =
|
||||
registration.status === "online" && registration.serverId
|
||||
? registration
|
||||
: await waitForHostOnline(options.paseo, registration.registrationId);
|
||||
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,
|
||||
@@ -361,6 +477,7 @@ export async function launchSpriteAgent(options: {
|
||||
remoteDir?: string;
|
||||
provider?: string;
|
||||
background?: boolean;
|
||||
onProgress?: (phase: string, spriteName?: string) => void;
|
||||
}): Promise<{
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
@@ -375,10 +492,14 @@ export async function launchSpriteAgent(options: {
|
||||
spriteName: options.spriteName,
|
||||
syncLocalPath: options.syncLocalPath,
|
||||
remoteDir: options.remoteDir,
|
||||
onProgress: options.onProgress,
|
||||
});
|
||||
|
||||
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) =>
|
||||
@@ -392,12 +513,14 @@ export async function launchSpriteAgent(options: {
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -407,6 +530,7 @@ export async function launchSpriteAgent(options: {
|
||||
prompt: options.prompt?.trim() || undefined,
|
||||
background: options.background,
|
||||
});
|
||||
invalidateSpriteHostsCache(options.paseo);
|
||||
|
||||
return {
|
||||
agentId: handle.id,
|
||||
@@ -425,47 +549,56 @@ 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,
|
||||
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);
|
||||
}
|
||||
} 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 };
|
||||
}),
|
||||
);
|
||||
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(
|
||||
@@ -480,4 +613,5 @@ export async function removeSpriteHostRegistration(
|
||||
for (const host of matches) {
|
||||
await paseo.hosts.remove(host.registrationId).catch(() => undefined);
|
||||
}
|
||||
invalidateSpriteHostsCache(paseo);
|
||||
}
|
||||
Reference in new issue
Block a user