Replace forever-on heartbeat billing with a finite lease system: callers request a window of Sprite time and renew as needed; on expiry the heartbeat session stops and the Sprite auto-pauses. - SpriteLeaseStore (server/sprite-lease-store.ts): refcounted leases with TTL clamping ([60s, 8h], default 15min) persisted to sprite-leases.json - SpriteHostKeepalive reimplemented on leases; legacy keepalive-hosts manifest seeds one final window then clears - Provider: session.open acquires, session.prompt renews, session.close releases - sprite_* tools and RPCs acquire/renew/release via sprites.lease.acquire/renew/release/list - destroy/archive release leases before deleting Sprites - Settings: defaultLeaseMinutes (1-480, default 30), schema v2
418 lines
17 KiB
TypeScript
418 lines
17 KiB
TypeScript
import { defineAgentTool, type AgentToolDefinition } from "@getpaseo/plugin/server";
|
|
import { z } from "zod";
|
|
import type { FlySpritesProviderRegistration } from "./provider";
|
|
import {
|
|
launchSpriteAgent,
|
|
listSpriteHostsWithAgents,
|
|
removeSpriteHostRegistration,
|
|
} from "./sprite-hosts";
|
|
import type { SpritesManager } from "./sprites-manager";
|
|
|
|
function textResult(text: string, structuredContent?: unknown, isError = false) {
|
|
return {
|
|
text,
|
|
structuredContent,
|
|
...(isError ? { isError: true } : {}),
|
|
};
|
|
}
|
|
|
|
function errorMessage(err: unknown): string {
|
|
return err instanceof Error ? err.message : String(err);
|
|
}
|
|
|
|
export interface SpriteAgentToolHooks {
|
|
onHostReady?: (spriteName: string) => void;
|
|
onHostRemoved?: (spriteName: string) => void;
|
|
acquireLease?: (
|
|
spriteName: string,
|
|
holder: { kind: string; id: string },
|
|
options?: { ttlMs?: number; reason?: string },
|
|
) => Promise<unknown>;
|
|
renewLease?: (leaseId: string, ttlMs?: number) => unknown;
|
|
releaseLease?: (leaseId: string) => unknown;
|
|
releaseHolder?: (holder: { kind: string; id: string }) => void;
|
|
releaseAll?: (spriteName: string) => void;
|
|
}
|
|
|
|
export function createSpriteAgentTools(
|
|
manager: SpritesManager,
|
|
_provider: FlySpritesProviderRegistration,
|
|
hooks?: SpriteAgentToolHooks,
|
|
): AgentToolDefinition[] {
|
|
const spriteListTool = defineAgentTool({
|
|
name: "sprite_list",
|
|
title: "List Fly Sprites & Managed Agents",
|
|
description:
|
|
"List remote Fly Sprites, connected Sprite Paseo hosts, and managed agents running on those Sprite hosts.",
|
|
input: z.object({
|
|
includeRemote: z.boolean().optional().default(true),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
const [{ hosts, agents }, sprites] = await Promise.all([
|
|
listSpriteHostsWithAgents(context.paseo),
|
|
input.includeRemote ? manager.listRemoteSprites() : Promise.resolve([]),
|
|
]);
|
|
return textResult(
|
|
JSON.stringify({ sprites, hosts, agents }, null, 2),
|
|
{ sprites, hosts, agents },
|
|
);
|
|
} catch (err) {
|
|
return textResult(`Failed to list Fly Sprites: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteCreateTool = defineAgentTool({
|
|
name: "sprite_create",
|
|
title: "Create Fly Sprite",
|
|
description:
|
|
"Create or reuse a Fly Sprite microVM and optionally sync the current workspace directory into /workspace.",
|
|
input: z.object({
|
|
name: z.string().optional().describe("Optional sprite name. Generated automatically if omitted."),
|
|
syncWorkspace: z
|
|
.boolean()
|
|
.optional()
|
|
.default(true)
|
|
.describe("Sync this agent's local workspace files into the Sprite."),
|
|
remoteDir: z.string().optional().describe("Destination directory inside the Sprite (defaults to /workspace)."),
|
|
region: z.string().optional(),
|
|
ramMB: z.number().int().positive().optional(),
|
|
cpus: z.number().int().positive().optional(),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
const result = await manager.ensureSprite({
|
|
name: input.name,
|
|
config: {
|
|
region: input.region,
|
|
ramMB: input.ramMB,
|
|
cpus: input.cpus,
|
|
},
|
|
syncLocalPath: input.syncWorkspace ? context.agent.cwd : undefined,
|
|
remoteDir: input.remoteDir,
|
|
});
|
|
await hooks?.acquireLease?.(result.sprite.name, { kind: "tool", id: context.agent.id ?? "sprite_create" }, { reason: "sprite_create" }).catch(() => undefined);
|
|
return textResult(
|
|
`Sprite ${result.sprite.name} ready (${result.created ? "created" : "existing"}, remoteDir=${result.remoteDir}${
|
|
result.syncedFiles !== undefined ? `, syncedFiles=${result.syncedFiles}` : ""
|
|
}).`,
|
|
{
|
|
spriteName: result.sprite.name,
|
|
created: result.created,
|
|
remoteDir: result.remoteDir,
|
|
syncedFiles: result.syncedFiles,
|
|
},
|
|
);
|
|
} catch (err) {
|
|
return textResult(`Failed to create sprite: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteSpawnAgentTool = defineAgentTool({
|
|
name: "sprite_spawn_agent",
|
|
title: "Spawn Managed Agent on Sprite Host",
|
|
description:
|
|
"Provision/connect a Fly Sprite as its own Paseo host and launch a managed Paseo agent directly under that Sprite host.",
|
|
input: z.object({
|
|
prompt: z.string().optional().describe("Initial prompt or task for the managed agent."),
|
|
title: z.string().optional().describe("Optional display title for the agent."),
|
|
spriteName: z.string().optional().describe("Target Fly Sprite name; provisions a new Sprite if omitted."),
|
|
cwd: z.string().optional().describe("Local workspace directory to sync into /workspace (defaults to caller's cwd)."),
|
|
remoteDir: z.string().optional().describe("Workspace directory inside the Sprite (defaults to /workspace)."),
|
|
provider: z.string().optional().describe("Optional provider or provider/model on the Sprite host (defaults to auto)."),
|
|
syncWorkspace: z.boolean().optional().default(true).describe("Sync the local workspace into the Sprite before launching."),
|
|
background: z.boolean().optional().default(false).describe("Hide from Paseo tabs/lists when true."),
|
|
waitForFinish: z.boolean().optional().default(false).describe("Wait for the initial turn to finish before returning."),
|
|
timeoutMs: z.number().int().positive().optional().default(300_000),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
const launched = await launchSpriteAgent({
|
|
manager,
|
|
paseo: context.paseo,
|
|
spriteName: input.spriteName,
|
|
title: input.title,
|
|
prompt: input.prompt,
|
|
syncLocalPath: input.syncWorkspace ? (input.cwd?.trim() || context.agent.cwd) : undefined,
|
|
remoteDir: input.remoteDir,
|
|
provider: input.provider,
|
|
background: input.background,
|
|
onHostReady: hooks?.onHostReady,
|
|
});
|
|
|
|
await hooks?.acquireLease?.(launched.spriteName, { kind: "agent", id: launched.agentId }, { reason: "sprite_spawn_agent" }).catch(() => undefined);
|
|
|
|
let waitResult: unknown;
|
|
if (input.waitForFinish && input.prompt) {
|
|
const spritePaseo = await context.paseo.hosts.client(launched.serverId);
|
|
try {
|
|
waitResult = await spritePaseo.agents.ref(launched.agentId).waitForFinish(input.timeoutMs);
|
|
} finally {
|
|
await spritePaseo.dispose().catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
return textResult(
|
|
`Managed agent ${launched.agentId} ready under Sprite host ${launched.spriteName} (${launched.serverId}, provider=${launched.provider}).`,
|
|
{
|
|
...launched,
|
|
waitResult,
|
|
},
|
|
);
|
|
} catch (err) {
|
|
return textResult(`Failed to spawn managed agent: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteAgentStatusTool = defineAgentTool({
|
|
name: "sprite_agent_status",
|
|
title: "Check Managed Sprite Agent Status",
|
|
description: "List managed agents across Sprite hosts or inspect one agent's state and latest turn output.",
|
|
input: z.object({
|
|
agentId: z.string().optional().describe("Agent ID returned by sprite_spawn_agent. Omit to list all Sprite-hosted agents."),
|
|
serverId: z.string().optional().describe("Optional Sprite host serverId if known."),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
const { hosts, agents } = await listSpriteHostsWithAgents(context.paseo);
|
|
if (!input.agentId) {
|
|
return textResult(JSON.stringify({ hosts, agents }, null, 2), { hosts, agents });
|
|
}
|
|
|
|
const matchedServerId =
|
|
input.serverId?.trim() ||
|
|
agents.find((a) => a.agentId === input.agentId)?.serverId;
|
|
if (!matchedServerId) {
|
|
return textResult(`Unknown Sprite agent: ${input.agentId}`, undefined, true);
|
|
}
|
|
|
|
const spritePaseo = await context.paseo.hosts.client(matchedServerId);
|
|
try {
|
|
const ref = spritePaseo.agents.ref(input.agentId);
|
|
const refreshed = await ref.refresh();
|
|
if (!refreshed) {
|
|
return textResult(`Unknown agent: ${input.agentId}`, undefined, true);
|
|
}
|
|
const timeline = await ref.timeline
|
|
.refetch({ direction: "tail", limit: 1, wholeTurns: true })
|
|
.catch(() => null);
|
|
return textResult(
|
|
JSON.stringify(
|
|
{
|
|
serverId: matchedServerId,
|
|
agentId: refreshed.agent.id,
|
|
title: refreshed.agent.title ?? null,
|
|
status: refreshed.agent.status,
|
|
provider: refreshed.agent.provider,
|
|
model: refreshed.agent.model ?? null,
|
|
lastError: refreshed.agent.lastError ?? null,
|
|
latestEntries: timeline?.entries ?? [],
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
{
|
|
serverId: matchedServerId,
|
|
agent: refreshed.agent,
|
|
latestEntries: timeline?.entries ?? [],
|
|
},
|
|
);
|
|
} finally {
|
|
await spritePaseo.dispose().catch(() => undefined);
|
|
}
|
|
} catch (err) {
|
|
return textResult(`Failed to inspect agent: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteAgentSendTool = defineAgentTool({
|
|
name: "sprite_agent_send",
|
|
title: "Send Message to Managed Sprite Agent",
|
|
description: "Send a follow-up prompt or instruction to an existing managed agent on a Sprite host.",
|
|
input: z.object({
|
|
agentId: z.string().describe("Target managed agent ID."),
|
|
serverId: z.string().optional().describe("Sprite host serverId (resolved automatically if omitted)."),
|
|
prompt: z.string().describe("Message or instruction to send."),
|
|
waitForFinish: z.boolean().optional().default(false),
|
|
timeoutMs: z.number().int().positive().optional().default(300_000),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
let serverId = input.serverId?.trim();
|
|
if (!serverId) {
|
|
const { agents } = await listSpriteHostsWithAgents(context.paseo);
|
|
serverId = agents.find((a) => a.agentId === input.agentId)?.serverId;
|
|
}
|
|
if (!serverId) {
|
|
return textResult(`Unknown Sprite agent: ${input.agentId}`, undefined, true);
|
|
}
|
|
|
|
const spritePaseo = await context.paseo.hosts.client(serverId);
|
|
try {
|
|
const ref = spritePaseo.agents.ref(input.agentId);
|
|
await hooks?.acquireLease?.(
|
|
(await listSpriteHostsWithAgents(context.paseo)).hosts.find((h) => h.serverId === serverId)?.spriteName ?? "",
|
|
{ kind: "agent", id: input.agentId },
|
|
{ reason: "sprite_agent_send" },
|
|
).catch(() => undefined);
|
|
if (input.waitForFinish) {
|
|
const result = await ref.run(input.prompt, { timeoutMs: input.timeoutMs });
|
|
return textResult(`Agent ${input.agentId} finished turn.`, { serverId, agentId: input.agentId, result });
|
|
}
|
|
await ref.send(input.prompt);
|
|
return textResult(`Sent message to agent ${input.agentId}.`, { serverId, agentId: input.agentId, sent: true });
|
|
} finally {
|
|
await spritePaseo.dispose().catch(() => undefined);
|
|
}
|
|
} catch (err) {
|
|
return textResult(`Failed to message agent: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteAgentStopTool = defineAgentTool({
|
|
name: "sprite_agent_stop",
|
|
title: "Interrupt or Archive Managed Sprite Agent",
|
|
description: "Interrupt a running managed Sprite agent (via reload) or archive it.",
|
|
input: z.object({
|
|
agentId: z.string().describe("Target managed agent ID."),
|
|
serverId: z.string().optional().describe("Sprite host serverId (resolved automatically if omitted)."),
|
|
action: z.enum(["interrupt", "archive"]).optional().default("archive"),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
let serverId = input.serverId?.trim();
|
|
if (!serverId) {
|
|
const { agents } = await listSpriteHostsWithAgents(context.paseo);
|
|
serverId = agents.find((a) => a.agentId === input.agentId)?.serverId;
|
|
}
|
|
if (!serverId) {
|
|
return textResult(`Unknown Sprite agent: ${input.agentId}`, undefined, true);
|
|
}
|
|
|
|
const spritePaseo = await context.paseo.hosts.client(serverId);
|
|
try {
|
|
const ref = spritePaseo.agents.ref(input.agentId);
|
|
if (input.action === "interrupt") {
|
|
await ref.reload();
|
|
return textResult(`Interrupted and reloaded agent ${input.agentId}.`, { serverId, agentId: input.agentId, action: "interrupt" });
|
|
}
|
|
const archived = await ref.archive();
|
|
hooks?.releaseHolder?.({ kind: "agent", id: input.agentId });
|
|
return textResult(`Archived agent ${input.agentId} at ${archived.archivedAt}.`, {
|
|
serverId,
|
|
agentId: input.agentId,
|
|
action: "archive",
|
|
archivedAt: archived.archivedAt,
|
|
});
|
|
} finally {
|
|
await spritePaseo.dispose().catch(() => undefined);
|
|
}
|
|
} catch (err) {
|
|
return textResult(`Failed to ${input.action} agent: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteExecTool = defineAgentTool({
|
|
name: "sprite_exec",
|
|
title: "Execute Command on Fly Sprite",
|
|
description:
|
|
"Run a synchronous shell command inside an existing Fly Sprite and return stdout, stderr, and exitCode.",
|
|
input: z.object({
|
|
spriteName: z.string().describe("Target Fly Sprite name."),
|
|
command: z.string().describe("Shell command to execute via bash -lc."),
|
|
cwd: z.string().optional().describe("Working directory inside the Sprite."),
|
|
timeoutMs: z.number().int().positive().optional().default(120_000),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
await hooks?.acquireLease?.(input.spriteName, { kind: "tool", id: context.agent.id ?? "sprite_exec" }, { reason: "sprite_exec" }).catch(() => undefined);
|
|
const res = await manager.execCommand({
|
|
spriteName: input.spriteName,
|
|
command: input.command,
|
|
cwd: input.cwd,
|
|
timeoutMs: input.timeoutMs,
|
|
});
|
|
const summary = [
|
|
`exitCode: ${res.exitCode}`,
|
|
res.stdout ? `stdout:\n${res.stdout}` : "",
|
|
res.stderr ? `stderr:\n${res.stderr}` : "",
|
|
]
|
|
.filter(Boolean)
|
|
.join("\n\n");
|
|
return textResult(summary, res, res.exitCode !== 0);
|
|
} catch (err) {
|
|
return textResult(`Exec failed: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteCheckpointTool = defineAgentTool({
|
|
name: "sprite_checkpoint",
|
|
title: "Manage Fly Sprite Checkpoints",
|
|
description: "Create, list, or restore copy-on-write checkpoints on a Fly Sprite.",
|
|
input: z.object({
|
|
action: z.enum(["create", "list", "restore"]),
|
|
spriteName: z.string(),
|
|
comment: z.string().optional().describe("Comment when action='create'."),
|
|
checkpointId: z.string().optional().describe("Checkpoint ID when action='restore'."),
|
|
}),
|
|
async execute(input) {
|
|
try {
|
|
if (input.action === "list") {
|
|
const checkpoints = await manager.listCheckpoints(input.spriteName);
|
|
return textResult(JSON.stringify(checkpoints, null, 2), { checkpoints });
|
|
}
|
|
if (input.action === "create") {
|
|
const messages = await manager.createCheckpoint(input.spriteName, input.comment);
|
|
return textResult(messages.join("\n") || "Checkpoint created.", { messages });
|
|
}
|
|
if (!input.checkpointId) {
|
|
return textResult("checkpointId is required for action='restore'.", undefined, true);
|
|
}
|
|
const messages = await manager.restoreCheckpoint(input.spriteName, input.checkpointId);
|
|
return textResult(messages.join("\n") || `Restored ${input.checkpointId}.`, { messages });
|
|
} catch (err) {
|
|
return textResult(`Checkpoint ${input.action} failed: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
const spriteDestroyTool = defineAgentTool({
|
|
name: "sprite_destroy",
|
|
title: "Delete Fly Sprite",
|
|
description: "Delete a Fly Sprite microVM and remove its Paseo host registration.",
|
|
input: z.object({
|
|
spriteName: z.string(),
|
|
}),
|
|
async execute(input, context) {
|
|
try {
|
|
hooks?.releaseAll?.(input.spriteName);
|
|
hooks?.onHostRemoved?.(input.spriteName);
|
|
await manager.deleteSprite(input.spriteName);
|
|
await removeSpriteHostRegistration(context.paseo, input.spriteName).catch(() => undefined);
|
|
return textResult(`Deleted sprite ${input.spriteName}.`, { spriteName: input.spriteName, deleted: true });
|
|
} catch (err) {
|
|
return textResult(`Failed to delete sprite: ${errorMessage(err)}`, undefined, true);
|
|
}
|
|
},
|
|
});
|
|
|
|
return [
|
|
spriteListTool,
|
|
spriteCreateTool,
|
|
spriteSpawnAgentTool,
|
|
spriteAgentStatusTool,
|
|
spriteAgentSendTool,
|
|
spriteAgentStopTool,
|
|
spriteExecTool,
|
|
spriteCheckpointTool,
|
|
spriteDestroyTool,
|
|
];
|
|
}
|