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
@@ -6,7 +6,7 @@ import { SpritesClient } from "@fly/sprites";
|
||||
|
||||
const DEFAULT_BASE_URL = "https://api.sprites.dev";
|
||||
const FLY_GRAPHQL_URL = "https://api.fly.io/graphql";
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const REQUEST_TIMEOUT_MS = 8_000;
|
||||
|
||||
interface PersistedSpritesTokenCache {
|
||||
keyHash: string;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { SpriteJob, SpriteJobKind, SpriteJobResult } from "../shared/contracts";
|
||||
|
||||
interface InternalJob extends SpriteJob {
|
||||
dedupeKey?: string;
|
||||
}
|
||||
|
||||
const FINISHED_JOB_TTL_MS = 15 * 60_000;
|
||||
const MAX_STORED_JOBS = 50;
|
||||
|
||||
function errMsg(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function toPublicJob(job: InternalJob): SpriteJob {
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
kind: job.kind,
|
||||
spriteName: job.spriteName,
|
||||
status: job.status,
|
||||
phase: job.phase,
|
||||
startedAt: job.startedAt,
|
||||
updatedAt: job.updatedAt,
|
||||
finishedAt: job.finishedAt,
|
||||
error: job.error,
|
||||
result: job.result,
|
||||
};
|
||||
}
|
||||
|
||||
export class SpriteJobManager {
|
||||
private readonly jobs = new Map<string, InternalJob>();
|
||||
|
||||
startJob<T extends SpriteJobResult>(options: {
|
||||
kind: SpriteJobKind;
|
||||
spriteName?: string | null;
|
||||
dedupeKey?: string;
|
||||
initialPhase: string;
|
||||
run: (ctx: {
|
||||
setPhase: (phase: string, spriteName?: string) => void;
|
||||
}) => Promise<T>;
|
||||
}): SpriteJob {
|
||||
this.prune();
|
||||
|
||||
if (options.dedupeKey) {
|
||||
for (const existing of this.jobs.values()) {
|
||||
if (existing.status === "running" && existing.dedupeKey === options.dedupeKey) {
|
||||
return toPublicJob(existing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const job: InternalJob = {
|
||||
jobId: `job_${randomBytes(6).toString("hex")}`,
|
||||
kind: options.kind,
|
||||
spriteName: options.spriteName?.trim() || null,
|
||||
status: "running",
|
||||
phase: options.initialPhase,
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
finishedAt: null,
|
||||
error: null,
|
||||
result: null,
|
||||
dedupeKey: options.dedupeKey,
|
||||
};
|
||||
|
||||
this.jobs.set(job.jobId, job);
|
||||
console.log(
|
||||
`[fly-sprites] job ${job.jobId} (${job.kind}${job.spriteName ? `:${job.spriteName}` : ""}) started: ${job.phase}`,
|
||||
);
|
||||
|
||||
const setPhase = (phase: string, spriteName?: string) => {
|
||||
if (job.status !== "running") return;
|
||||
job.phase = phase;
|
||||
if (spriteName?.trim()) {
|
||||
job.spriteName = spriteName.trim();
|
||||
}
|
||||
job.updatedAt = new Date().toISOString();
|
||||
};
|
||||
|
||||
void options
|
||||
.run({ setPhase })
|
||||
.then((result) => {
|
||||
const finishedAt = new Date().toISOString();
|
||||
job.status = "succeeded";
|
||||
job.phase = "Done";
|
||||
job.result = result;
|
||||
if ("spriteName" in result && result.spriteName) {
|
||||
job.spriteName = result.spriteName;
|
||||
} else if (result.kind === "create_sprite") {
|
||||
job.spriteName = result.sprite.name;
|
||||
}
|
||||
job.updatedAt = finishedAt;
|
||||
job.finishedAt = finishedAt;
|
||||
console.log(
|
||||
`[fly-sprites] job ${job.jobId} (${job.kind}${job.spriteName ? `:${job.spriteName}` : ""}) succeeded`,
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
const finishedAt = new Date().toISOString();
|
||||
const message = errMsg(error);
|
||||
job.status = "failed";
|
||||
job.phase = "Failed";
|
||||
job.error = message;
|
||||
job.updatedAt = finishedAt;
|
||||
job.finishedAt = finishedAt;
|
||||
console.error(
|
||||
`[fly-sprites] job ${job.jobId} (${job.kind}${job.spriteName ? `:${job.spriteName}` : ""}) failed: ${message}`,
|
||||
);
|
||||
});
|
||||
|
||||
return toPublicJob(job);
|
||||
}
|
||||
|
||||
getJob(jobId: string): SpriteJob | null {
|
||||
const job = this.jobs.get(jobId);
|
||||
return job ? toPublicJob(job) : null;
|
||||
}
|
||||
|
||||
listJobs(): SpriteJob[] {
|
||||
this.prune();
|
||||
return [...this.jobs.values()]
|
||||
.sort((a, b) => b.startedAt.localeCompare(a.startedAt))
|
||||
.map(toPublicJob);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.jobs.clear();
|
||||
}
|
||||
|
||||
private prune(): void {
|
||||
const now = Date.now();
|
||||
for (const [id, job] of this.jobs.entries()) {
|
||||
if (job.status !== "running" && job.finishedAt) {
|
||||
const age = now - Date.parse(job.finishedAt);
|
||||
if (age > FINISHED_JOB_TTL_MS) {
|
||||
this.jobs.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.jobs.size <= MAX_STORED_JOBS) return;
|
||||
const finished = [...this.jobs.values()]
|
||||
.filter((j) => j.status !== "running")
|
||||
.sort((a, b) => (a.finishedAt ?? a.updatedAt).localeCompare(b.finishedAt ?? b.updatedAt));
|
||||
for (const job of finished) {
|
||||
if (this.jobs.size <= MAX_STORED_JOBS) break;
|
||||
this.jobs.delete(job.jobId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,8 +49,9 @@ interface CachedSecret {
|
||||
}
|
||||
|
||||
const SECRET_CACHE_TTL_MS = 5 * 60_000;
|
||||
const SECRET_CACHE_TTL_COLD_MS = 30 * 60_000;
|
||||
const DISCOVERY_CACHE_TTL_MS = 60 * 60_000;
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const REQUEST_TIMEOUT_MS = 8_000;
|
||||
|
||||
function sessionFilePath(): string {
|
||||
const base = process.env.PASEO_HOME || path.join(homedir(), ".paseo");
|
||||
@@ -356,8 +357,8 @@ export class OpenBaoClient {
|
||||
].join("|");
|
||||
}
|
||||
|
||||
async getSecretToken(forceRefresh = false): Promise<string> {
|
||||
const settings = await this.getSettings();
|
||||
async getSecretToken(forceRefresh = false, settingsOverride?: FlySpritesSettings): Promise<string> {
|
||||
const settings = settingsOverride ?? (await this.getSettings());
|
||||
if (!settings.openbaoEnabled) {
|
||||
return "";
|
||||
}
|
||||
@@ -460,7 +461,7 @@ export class OpenBaoClient {
|
||||
cacheKey,
|
||||
token: found,
|
||||
pulledAt: new Date().toISOString(),
|
||||
expiresAtMs: Date.now() + SECRET_CACHE_TTL_MS,
|
||||
expiresAtMs: Date.now() + SECRET_CACHE_TTL_COLD_MS,
|
||||
};
|
||||
return found;
|
||||
}
|
||||
|
||||
+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);
|
||||
}
|
||||
@@ -136,6 +136,9 @@ export class SpritesManager {
|
||||
private readonly openbao: OpenBaoClient;
|
||||
private readonly tokenExchange = new FlyTokenExchange();
|
||||
private cachedClient: { key: string; client: SpritesClient } | null = null;
|
||||
private remoteSpritesCache: { at: number; key: string; value: SpriteSummary[] } | null = null;
|
||||
private remoteSpritesInFlight: { key: string; promise: Promise<SpriteSummary[]> } | null = null;
|
||||
private rawTokenCache: { at: number; value: { token: string; source: TokenSource; baseUrl: string; settings: FlySpritesSettings } } | null = null;
|
||||
private readonly workers = new Map<string, TrackedWorker>();
|
||||
private readonly listeners = new Set<(workers: WorkerSummary[]) => void>();
|
||||
private notifyTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -147,14 +150,32 @@ export class SpritesManager {
|
||||
|
||||
async clearExchangedTokenCache(): Promise<void> {
|
||||
this.cachedClient = null;
|
||||
this.rawTokenCache = null;
|
||||
this.remoteSpritesCache = null;
|
||||
await this.tokenExchange.clear();
|
||||
}
|
||||
|
||||
invalidateRemoteSpritesCache(): void {
|
||||
this.remoteSpritesCache = null;
|
||||
}
|
||||
|
||||
async resolveRawToken(): Promise<{
|
||||
token: string;
|
||||
source: TokenSource;
|
||||
baseUrl: string;
|
||||
settings: FlySpritesSettings;
|
||||
}> {
|
||||
if (this.rawTokenCache && Date.now() - this.rawTokenCache.at < 30_000) return this.rawTokenCache.value;
|
||||
const value = await this.resolveRawTokenUncached();
|
||||
this.rawTokenCache = { at: Date.now(), value };
|
||||
return value;
|
||||
}
|
||||
|
||||
private async resolveRawTokenUncached(): Promise<{
|
||||
token: string;
|
||||
source: TokenSource;
|
||||
baseUrl: string;
|
||||
settings: FlySpritesSettings;
|
||||
}> {
|
||||
const settings = await this.getSettings();
|
||||
const baseUrl = settings.baseUrl.trim() || "https://api.sprites.dev";
|
||||
@@ -257,7 +278,9 @@ export class SpritesManager {
|
||||
config?: Partial<SpriteConfig>;
|
||||
syncLocalPath?: string;
|
||||
remoteDir?: string;
|
||||
onProgress?: (phase: string, spriteName?: string) => void;
|
||||
} = {}): Promise<{ sprite: Sprite; created: boolean; syncedFiles?: number; remoteDir: string }> {
|
||||
options.onProgress?.("Authenticating with Fly Sprites…");
|
||||
const { client, settings } = await this.getClient();
|
||||
const remoteDir = options.remoteDir?.trim() || settings.defaultRemoteCwd.trim() || "/workspace";
|
||||
const name = options.name?.trim()
|
||||
@@ -267,6 +290,7 @@ export class SpritesManager {
|
||||
let sprite: Sprite | null = null;
|
||||
let created = false;
|
||||
if (options.name?.trim()) {
|
||||
options.onProgress?.(`Checking Fly Sprite ${name}…`, name);
|
||||
try {
|
||||
sprite = await client.getSprite(name);
|
||||
} catch {
|
||||
@@ -275,13 +299,16 @@ export class SpritesManager {
|
||||
}
|
||||
|
||||
if (!sprite) {
|
||||
options.onProgress?.(`Creating Fly Sprite ${name}…`, name);
|
||||
const spriteConfig = await this.buildSpriteConfig(options.config);
|
||||
sprite = await client.createSprite(name, spriteConfig);
|
||||
created = true;
|
||||
this.remoteSpritesCache = null;
|
||||
}
|
||||
|
||||
let syncedFiles: number | undefined;
|
||||
if (options.syncLocalPath?.trim()) {
|
||||
options.onProgress?.(`Syncing workspace to ${remoteDir}…`, sprite.name);
|
||||
const syncResult = await this.syncWorkspace(
|
||||
sprite.name,
|
||||
options.syncLocalPath.trim(),
|
||||
@@ -293,8 +320,23 @@ export class SpritesManager {
|
||||
return { sprite, created, syncedFiles, remoteDir };
|
||||
}
|
||||
|
||||
async listRemoteSprites(): Promise<SpriteSummary[]> {
|
||||
const { client, exchangedFromFlyMacaroon } = await this.getClient();
|
||||
async listRemoteSprites(options?: { forceRefresh?: boolean }): Promise<SpriteSummary[]> {
|
||||
const raw = await this.resolveRawToken();
|
||||
const key = `${raw.baseUrl}|${raw.source}|${raw.token.slice(0, 8)}|${raw.settings.flyOrgSlug}`;
|
||||
if (!options?.forceRefresh && this.remoteSpritesCache?.key === key && Date.now() - this.remoteSpritesCache.at < 30_000) {
|
||||
return this.remoteSpritesCache.value;
|
||||
}
|
||||
if (!options?.forceRefresh && this.remoteSpritesInFlight?.key === key) return this.remoteSpritesInFlight.promise;
|
||||
const promise = this.fetchRemoteSprites(options).then((value) => {
|
||||
this.remoteSpritesCache = { at: Date.now(), key, value };
|
||||
return value;
|
||||
});
|
||||
this.remoteSpritesInFlight = { key, promise };
|
||||
try { return await promise; } finally { if (this.remoteSpritesInFlight?.promise === promise) this.remoteSpritesInFlight = null; }
|
||||
}
|
||||
|
||||
private async fetchRemoteSprites(options?: { forceRefresh?: boolean }): Promise<SpriteSummary[]> {
|
||||
const { client, exchangedFromFlyMacaroon } = await this.getClient(options?.forceRefresh ? { forceExchangeRefresh: true } : undefined);
|
||||
try {
|
||||
const sprites = await client.listAllSprites();
|
||||
return sprites.map(toSpriteSummary);
|
||||
@@ -592,6 +634,7 @@ export class SpritesManager {
|
||||
}
|
||||
const { client } = await this.getClient();
|
||||
await client.deleteSprite(normalized);
|
||||
this.remoteSpritesCache = null;
|
||||
}
|
||||
|
||||
async listCheckpoints(spriteName: string): Promise<CheckpointSummary[]> {
|
||||
|
||||
Reference in new issue
Block a user