feat: add fly-sprites-workers Paseo plugin
This commit is contained in:
commit
0c4027ebe5
15 files changed
+7446
No files matched your search
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.verify/
|
||||
.DS_Store
|
||||
*.log
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Fly Sprites Workers
|
||||
|
||||
Spawn remote workers and isolated coding agent sessions on Fly.io Sprites microVMs directly from Paseo.
|
||||
|
||||
## Capabilities
|
||||
|
||||
1. **Native Paseo provider (`fly-sprites`)**: Open Paseo agents or subagents backed by Fly Sprites in either Shell Worker mode (direct `bash -lc` streaming) or Remote ACP Agent mode (e.g. `claude-code-acp` inside the Sprite over WebSocket stdio).
|
||||
2. **Injected agent tools (`sprite_*`)**: Local Paseo agents receive `sprite_list`, `sprite_create`, `sprite_spawn_worker`, `sprite_exec`, `sprite_worker_status`, `sprite_worker_stop`, `sprite_checkpoint`, and `sprite_destroy` to run parallel workers and snapshots.
|
||||
3. **Workers UI and workspace panel**: Create Sprites, sync the active workspace directory into `/workspace`, spawn background workers, watch live output, and create or restore checkpoints.
|
||||
|
||||
## Setup
|
||||
|
||||
Configure a Fly Sprites API token in **Settings > Fly Sprites Workers** or set `SPRITES_TOKEN` in the Paseo daemon environment.
|
||||
@@ -0,0 +1,311 @@
|
||||
import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
|
||||
import { useRpc, useSettings } from "@getpaseo/plugin/client";
|
||||
import {
|
||||
ScrollView,
|
||||
SettingsAction,
|
||||
SettingsCard,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
SettingsSelect,
|
||||
SettingsSwitch,
|
||||
useToast,
|
||||
} from "@getpaseo/plugin/client/ui";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { testConnectionRpc } from "../shared/contracts";
|
||||
import {
|
||||
defaultFlySpritesSettings,
|
||||
flySpritesSettings,
|
||||
type FlySpritesSettings,
|
||||
} from "../shared/settings";
|
||||
|
||||
const MODE_OPTIONS: readonly { label: string; value: FlySpritesSettings["defaultProviderMode"] }[] = [
|
||||
{ label: "Remote Shell Worker (bash -lc)", value: "shell" },
|
||||
{ label: "Remote ACP Agent (over WebSocket stdio)", value: "acp" },
|
||||
];
|
||||
|
||||
export function FlySpritesSettingsScreen({ theme, layout, host }: PluginSurfaceProps) {
|
||||
const settings = useSettings(flySpritesSettings);
|
||||
const testConnection = useRpc(testConnectionRpc);
|
||||
const toast = useToast();
|
||||
|
||||
const [draft, setDraft] = useState<FlySpritesSettings>(defaultFlySpritesSettings);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
|
||||
const readyRevision = settings.status === "ready" ? settings.revision : null;
|
||||
const readyValues = settings.status === "ready" ? settings.values : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (readyValues) {
|
||||
setDraft(readyValues);
|
||||
}
|
||||
}, [readyRevision, readyValues]);
|
||||
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
body: { padding: layout.compact ? 16 : 24, gap: 16 },
|
||||
muted: { color: theme.colors.foregroundMuted, fontSize: 13 },
|
||||
error: { color: theme.colors.statusDanger, fontSize: 13 },
|
||||
success: { color: theme.colors.statusSuccess, fontSize: 13 },
|
||||
}),
|
||||
[theme, layout.compact],
|
||||
);
|
||||
|
||||
if (settings.status === "loading") {
|
||||
return (
|
||||
<View style={[styles.screen, styles.body]}>
|
||||
<Text style={styles.muted}>Loading Fly Sprites settings for {host.label}…</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (settings.status === "error") {
|
||||
return (
|
||||
<View style={[styles.screen, styles.body]}>
|
||||
<Text style={styles.error}>Could not load settings: {settings.error}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isInvalid = settings.status === "invalid";
|
||||
const revision = settings.revision;
|
||||
const isDirty =
|
||||
settings.status === "ready" &&
|
||||
JSON.stringify(draft) !== JSON.stringify(settings.values);
|
||||
|
||||
async function saveDraft(next: FlySpritesSettings) {
|
||||
setStatusMessage(null);
|
||||
const ok = await settings.save(next, revision);
|
||||
if (ok) {
|
||||
setStatusMessage("Saved.");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReset() {
|
||||
setStatusMessage(null);
|
||||
const ok = await settings.reset();
|
||||
if (ok) {
|
||||
setDraft(defaultFlySpritesSettings);
|
||||
setStatusMessage("Reset to defaults.");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTest() {
|
||||
setTesting(true);
|
||||
setStatusMessage(null);
|
||||
try {
|
||||
if (isDirty) {
|
||||
await settings.save(draft, revision);
|
||||
}
|
||||
const res = await testConnection({});
|
||||
if (res.ok) {
|
||||
const msg = `Connected via ${res.source} token (${res.spriteCount} sprites).`;
|
||||
setStatusMessage(msg);
|
||||
toast.show(msg, { variant: "success" });
|
||||
} else {
|
||||
setStatusMessage(res.error);
|
||||
toast.error(res.error);
|
||||
}
|
||||
} catch (error) {
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
setStatusMessage(msg);
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.body}>
|
||||
<SettingsSection
|
||||
title="Fly Sprites authentication"
|
||||
info={<Text style={styles.muted}>Host settings for {host.label}. Leave token blank to use SPRITES_TOKEN.</Text>}
|
||||
>
|
||||
{isInvalid ? (
|
||||
<SettingsCard>
|
||||
<SettingsRow label="Invalid saved settings" error={settings.error} />
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
|
||||
<SettingsCard key={`auth-${revision}`}>
|
||||
<SettingsInput
|
||||
label="Sprites API token"
|
||||
hint="Used by the provider, agent tools, and worker manager."
|
||||
initialValue={draft.token}
|
||||
placeholder="SPRITES_TOKEN (leave blank to read host env)"
|
||||
secureTextEntry
|
||||
disabled={settings.saving}
|
||||
onChangeText={(token) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, token }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="API base URL"
|
||||
hint="Default: https://api.sprites.dev"
|
||||
initialValue={draft.baseUrl}
|
||||
placeholder="https://api.sprites.dev"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(baseUrl) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, baseUrl }));
|
||||
}}
|
||||
/>
|
||||
<SettingsAction
|
||||
label="Test Fly Sprites connection"
|
||||
hint="Verifies token access against the Sprites API."
|
||||
actionLabel={testing ? "Testing…" : "Test connection"}
|
||||
disabled={testing || settings.saving}
|
||||
onPress={() => void handleTest()}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Sprite defaults & provider">
|
||||
<SettingsCard key={`defaults-${revision}`}>
|
||||
<SettingsSelect
|
||||
label="Default provider mode"
|
||||
hint="How the Fly Sprites provider executes prompts when creating a new agent."
|
||||
value={draft.defaultProviderMode}
|
||||
disabled={settings.saving}
|
||||
options={MODE_OPTIONS}
|
||||
onValueChange={(defaultProviderMode) => {
|
||||
const next = { ...draft, defaultProviderMode };
|
||||
setDraft(next);
|
||||
void saveDraft(next);
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Remote ACP command"
|
||||
hint="Executed inside the Sprite when provider mode is ACP."
|
||||
initialValue={draft.acpCommand}
|
||||
placeholder="claude-code-acp"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(acpCommand) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, acpCommand }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Sprite name prefix"
|
||||
hint="Prefix for auto-generated worker sprites."
|
||||
initialValue={draft.spritePrefix}
|
||||
placeholder="paseo-worker-"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(spritePrefix) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, spritePrefix }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Default remote directory"
|
||||
hint="Working directory inside Sprites."
|
||||
initialValue={draft.defaultRemoteCwd}
|
||||
placeholder="/workspace"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(defaultRemoteCwd) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, defaultRemoteCwd }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Default region"
|
||||
hint="Optional Fly region slug (blank uses API default)."
|
||||
initialValue={draft.defaultRegion}
|
||||
placeholder="iad"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(defaultRegion) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, defaultRegion }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Default RAM (MB)"
|
||||
hint="0 uses Fly Sprites default sizing."
|
||||
initialValue={String(draft.defaultRamMB)}
|
||||
placeholder="0"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(val) => {
|
||||
const parsed = Number.parseInt(val.trim() || "0", 10);
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, defaultRamMB: Number.isFinite(parsed) && parsed >= 0 ? parsed : 0 }));
|
||||
}}
|
||||
/>
|
||||
<SettingsInput
|
||||
label="Default CPUs"
|
||||
hint="0 uses Fly Sprites default sizing."
|
||||
initialValue={String(draft.defaultCpus)}
|
||||
placeholder="0"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(val) => {
|
||||
const parsed = Number.parseInt(val.trim() || "0", 10);
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, defaultCpus: Number.isFinite(parsed) && parsed >= 0 ? parsed : 0 }));
|
||||
}}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Integration behavior">
|
||||
<SettingsCard key={`behavior-${revision}`}>
|
||||
<SettingsSwitch
|
||||
label="Inject sprite_* tools into Paseo agents"
|
||||
hint="Allows local agents to spawn parallel Fly Sprite workers and checkpoints."
|
||||
value={draft.injectAgentTools}
|
||||
disabled={settings.saving}
|
||||
onValueChange={(injectAgentTools) => {
|
||||
const next = { ...draft, injectAgentTools };
|
||||
setDraft(next);
|
||||
void saveDraft(next);
|
||||
}}
|
||||
/>
|
||||
<SettingsSwitch
|
||||
label="Sync local workspace on provider open"
|
||||
hint="Uploads workspace files to /workspace when a Fly Sprites session starts."
|
||||
value={draft.syncWorkspaceOnCreate}
|
||||
disabled={settings.saving}
|
||||
onValueChange={(syncWorkspaceOnCreate) => {
|
||||
const next = { ...draft, syncWorkspaceOnCreate };
|
||||
setDraft(next);
|
||||
void saveDraft(next);
|
||||
}}
|
||||
/>
|
||||
<SettingsSwitch
|
||||
label="Delete ephemeral sprites on archive"
|
||||
hint="Deletes the Sprite created by a Fly Sprites agent when that agent is archived."
|
||||
value={draft.autoCleanupOnArchive}
|
||||
disabled={settings.saving}
|
||||
onValueChange={(autoCleanupOnArchive) => {
|
||||
const next = { ...draft, autoCleanupOnArchive };
|
||||
setDraft(next);
|
||||
void saveDraft(next);
|
||||
}}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard>
|
||||
<SettingsAction
|
||||
label="Save settings"
|
||||
hint={isDirty ? "You have unsaved text or numeric changes." : "All text changes saved."}
|
||||
actionLabel={settings.saving ? "Saving…" : "Save"}
|
||||
disabled={settings.saving || (!isDirty && !isInvalid)}
|
||||
onPress={() => void saveDraft(draft)}
|
||||
/>
|
||||
<SettingsAction
|
||||
label="Reset settings"
|
||||
hint="Restore default Fly Sprites configuration."
|
||||
actionLabel="Reset"
|
||||
disabled={settings.saving}
|
||||
onPress={() => void handleReset()}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
{settings.saveError ? <Text style={styles.error}>{settings.saveError}</Text> : null}
|
||||
{statusMessage ? <Text style={styles.success}>{statusMessage}</Text> : null}
|
||||
</SettingsSection>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
import {
|
||||
type PluginHostProps,
|
||||
useRpc,
|
||||
useSubscription,
|
||||
useWorkspace,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { ScrollView, TextInput, copyText, useToast } from "@getpaseo/plugin/client/ui";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import {
|
||||
type CheckpointSummary,
|
||||
type SpriteSummary,
|
||||
type WorkerSummary,
|
||||
createCheckpointRpc,
|
||||
createSpriteRpc,
|
||||
destroySpriteRpc,
|
||||
listCheckpointsRpc,
|
||||
restoreCheckpointRpc,
|
||||
spawnWorkerRpc,
|
||||
statusRpc,
|
||||
stopWorkerRpc,
|
||||
syncWorkspaceRpc,
|
||||
watchWorkersSub,
|
||||
workerLogsRpc,
|
||||
} from "../shared/contracts";
|
||||
|
||||
interface WorkersScreenProps extends PluginHostProps {
|
||||
workspaceId?: string;
|
||||
}
|
||||
|
||||
export function FlySpritesWorkersScreen({ theme, layout, host, workspaceId }: WorkersScreenProps) {
|
||||
const workspace = useWorkspace(workspaceId ?? "");
|
||||
const toast = useToast();
|
||||
|
||||
const fetchStatus = useRpc(statusRpc);
|
||||
const createSprite = useRpc(createSpriteRpc);
|
||||
const syncWorkspace = useRpc(syncWorkspaceRpc);
|
||||
const spawnWorker = useRpc(spawnWorkerRpc);
|
||||
const stopWorker = useRpc(stopWorkerRpc);
|
||||
const fetchLogs = useRpc(workerLogsRpc);
|
||||
const destroySprite = useRpc(destroySpriteRpc);
|
||||
const listCheckpoints = useRpc(listCheckpointsRpc);
|
||||
const createCheckpoint = useRpc(createCheckpointRpc);
|
||||
const restoreCheckpoint = useRpc(restoreCheckpointRpc);
|
||||
|
||||
const [configured, setConfigured] = useState(false);
|
||||
const [tokenSource, setTokenSource] = useState<"settings" | "env" | "none">("none");
|
||||
const [remoteError, setRemoteError] = useState<string | null>(null);
|
||||
const [sprites, setSprites] = useState<SpriteSummary[]>([]);
|
||||
const [workers, setWorkers] = useState<WorkerSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const [spriteNameInput, setSpriteNameInput] = useState("");
|
||||
const [commandInput, setCommandInput] = useState("");
|
||||
const [syncPathInput, setSyncPathInput] = useState(workspace?.directory ?? "");
|
||||
const [syncBeforeSpawn, setSyncBeforeSpawn] = useState(Boolean(workspace?.directory));
|
||||
|
||||
const [selectedWorkerId, setSelectedWorkerId] = useState<string | null>(null);
|
||||
const [fullLogs, setFullLogs] = useState<string>("");
|
||||
const [checkpointsSprite, setCheckpointsSprite] = useState<string | null>(null);
|
||||
const [checkpoints, setCheckpoints] = useState<CheckpointSummary[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (workspace?.directory && !syncPathInput) {
|
||||
setSyncPathInput(workspace.directory);
|
||||
setSyncBeforeSpawn(true);
|
||||
}
|
||||
}, [workspace?.directory, syncPathInput]);
|
||||
|
||||
const watchInput = useMemo(() => ({}), []);
|
||||
useSubscription(watchWorkersSub, watchInput, (event) => {
|
||||
setWorkers(event.workers);
|
||||
});
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetchStatus({ includeRemote: true });
|
||||
setConfigured(res.configured);
|
||||
setTokenSource(res.tokenSource);
|
||||
setRemoteError(res.remoteError);
|
||||
setSprites(res.sprites);
|
||||
setWorkers(res.workers);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [fetchStatus, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const selectedWorker = useMemo(
|
||||
() => workers.find((w) => w.workerId === selectedWorkerId) ?? null,
|
||||
[workers, selectedWorkerId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedWorkerId) return;
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
const res = await fetchLogs({ workerId: selectedWorkerId }).catch(() => null);
|
||||
if (!cancelled && res?.ok) {
|
||||
setFullLogs(res.output);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedWorkerId, workers, fetchLogs]);
|
||||
|
||||
const handleCreateSprite = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await createSprite({
|
||||
name: spriteNameInput.trim() || undefined,
|
||||
syncLocalPath: syncBeforeSpawn && syncPathInput.trim() ? syncPathInput.trim() : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.show(`Sprite ${res.sprite.name} ready`, { variant: "success" });
|
||||
setSpriteNameInput(res.sprite.name);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSpawnWorker = async () => {
|
||||
const command = commandInput.trim();
|
||||
if (!command) {
|
||||
toast.error("Enter a worker command to run.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await spawnWorker({
|
||||
spriteName: spriteNameInput.trim() || undefined,
|
||||
command,
|
||||
syncLocalPath: syncBeforeSpawn && syncPathInput.trim() ? syncPathInput.trim() : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.show(`Spawned ${res.worker.workerId} on ${res.worker.spriteName}`, { variant: "success" });
|
||||
setSelectedWorkerId(res.worker.workerId);
|
||||
setCommandInput("");
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSyncSprite = async (name: string) => {
|
||||
const localPath = syncPathInput.trim();
|
||||
if (!localPath) {
|
||||
toast.error("Enter a local workspace path to sync.");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await syncWorkspace({ spriteName: name, localPath });
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.show(`Synced ${res.fileCount} files to ${name}:${res.remoteDir}`, { variant: "success" });
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCheckpoint = async (name: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await createCheckpoint({
|
||||
spriteName: name,
|
||||
comment: `paseo-${new Date().toISOString()}`,
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.show(`Checkpointed ${name}`, { variant: "success" });
|
||||
await handleLoadCheckpoints(name);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoadCheckpoints = async (name: string) => {
|
||||
setCheckpointsSprite(name);
|
||||
try {
|
||||
const res = await listCheckpoints({ spriteName: name });
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
setCheckpoints(res.checkpoints);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestoreCheckpoint = async (name: string, checkpointId: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await restoreCheckpoint({ spriteName: name, checkpointId });
|
||||
if (!res.ok) {
|
||||
toast.error(res.error);
|
||||
return;
|
||||
}
|
||||
toast.show(`Restored ${name} to ${checkpointId}`, { variant: "success" });
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDestroySprite = async (name: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await destroySprite({ spriteName: name });
|
||||
if (!res.ok) {
|
||||
toast.error(res.error ?? "Failed to delete sprite");
|
||||
return;
|
||||
}
|
||||
toast.show(`Deleted sprite ${name}`, { variant: "info" });
|
||||
if (checkpointsSprite === name) {
|
||||
setCheckpointsSprite(null);
|
||||
setCheckpoints([]);
|
||||
}
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
body: { padding: layout.compact ? 16 : 24, gap: 14 },
|
||||
headerRow: {
|
||||
flexDirection: "row" as const,
|
||||
justifyContent: "space-between" as const,
|
||||
alignItems: "center" as const,
|
||||
gap: 8,
|
||||
},
|
||||
title: { color: theme.colors.foreground, fontSize: 18, fontWeight: "600" as const },
|
||||
sectionTitle: { color: theme.colors.foreground, fontSize: 15, fontWeight: "600" as const, marginTop: 6 },
|
||||
muted: { color: theme.colors.foregroundMuted, fontSize: 12 },
|
||||
error: { color: theme.colors.statusDanger, fontSize: 12 },
|
||||
card: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderRadius: 10,
|
||||
padding: 12,
|
||||
gap: 8,
|
||||
},
|
||||
input: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
color: theme.colors.foreground,
|
||||
borderRadius: 8,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 8,
|
||||
fontSize: 13,
|
||||
},
|
||||
row: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 8, alignItems: "center" as const },
|
||||
btnPrimary: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
borderRadius: 8,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: 8,
|
||||
},
|
||||
btnPrimaryText: { color: theme.colors.accentForeground, fontSize: 12, fontWeight: "600" as const },
|
||||
btnSecondary: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: 8,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
},
|
||||
btnSecondaryText: { color: theme.colors.foreground, fontSize: 12, fontWeight: "500" as const },
|
||||
btnDanger: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.statusDanger,
|
||||
borderRadius: 8,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
},
|
||||
btnDangerText: { color: theme.colors.statusDanger, fontSize: 12, fontWeight: "500" as const },
|
||||
monoBox: {
|
||||
backgroundColor: theme.colors.surface0,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
borderRadius: 8,
|
||||
padding: 10,
|
||||
},
|
||||
monoText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: 12,
|
||||
fontFamily: "monospace",
|
||||
},
|
||||
}),
|
||||
[theme, layout.compact],
|
||||
);
|
||||
|
||||
const statusColor = (status: WorkerSummary["status"]) => {
|
||||
if (status === "completed") return theme.colors.statusSuccess;
|
||||
if (status === "failed") return theme.colors.statusDanger;
|
||||
if (status === "running" || status === "starting") return theme.colors.accent;
|
||||
return theme.colors.foregroundMuted;
|
||||
};
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.body}>
|
||||
<View style={styles.headerRow}>
|
||||
<View>
|
||||
<Text style={styles.title}>Fly Sprites Workers</Text>
|
||||
<Text style={styles.muted}>
|
||||
Host: {host.label} · Token: {tokenSource}
|
||||
{workspace ? ` · Workspace: ${workspace.name}` : ""}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable style={styles.btnSecondary} onPress={() => void refresh()} disabled={loading}>
|
||||
<Text style={styles.btnSecondaryText}>{loading ? "Refreshing…" : "Refresh"}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{!configured ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.error}>
|
||||
No Fly Sprites API token configured. Open Settings → Fly Sprites Workers or set SPRITES_TOKEN on the host.
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{remoteError ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.error}>Remote API error: {remoteError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.sectionTitle}>Spawn Worker / Create Sprite</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={spriteNameInput}
|
||||
onChangeText={setSpriteNameInput}
|
||||
placeholder="Sprite name (blank creates a new paseo-worker-* sprite)"
|
||||
placeholderTextColor={theme.colors.foregroundMuted}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={commandInput}
|
||||
onChangeText={setCommandInput}
|
||||
placeholder="Command to run (e.g. npm test, or claude -p '...')"
|
||||
placeholderTextColor={theme.colors.foregroundMuted}
|
||||
/>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={syncPathInput}
|
||||
onChangeText={setSyncPathInput}
|
||||
placeholder="Optional local folder to sync to /workspace"
|
||||
placeholderTextColor={theme.colors.foregroundMuted}
|
||||
/>
|
||||
<View style={styles.row}>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => setSyncBeforeSpawn((v) => !v)}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>
|
||||
{syncBeforeSpawn ? "Sync workspace: ON" : "Sync workspace: OFF"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => void handleCreateSprite()}
|
||||
disabled={busy || !configured}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Create Sprite</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnPrimary}
|
||||
onPress={() => void handleSpawnWorker()}
|
||||
disabled={busy || !configured}
|
||||
>
|
||||
<Text style={styles.btnPrimaryText}>Spawn Worker</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Text style={styles.sectionTitle}>Tracked Workers ({workers.length})</Text>
|
||||
{workers.length === 0 ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.muted}>No workers spawned on this daemon yet.</Text>
|
||||
</View>
|
||||
) : (
|
||||
workers.map((worker) => (
|
||||
<View key={worker.workerId} style={styles.card}>
|
||||
<View style={styles.headerRow}>
|
||||
<Text style={{ color: theme.colors.foreground, fontWeight: "600", fontSize: 13 }}>
|
||||
{worker.workerId} · {worker.spriteName}
|
||||
</Text>
|
||||
<Text style={{ color: statusColor(worker.status), fontSize: 12, fontWeight: "600" }}>
|
||||
{worker.status}
|
||||
{worker.exitCode !== null ? ` (${worker.exitCode})` : ""}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.muted} numberOfLines={2}>
|
||||
$ {worker.command}
|
||||
</Text>
|
||||
<Text style={styles.muted}>
|
||||
cwd: {worker.cwd} · started: {worker.startedAt}
|
||||
</Text>
|
||||
{worker.error ? <Text style={styles.error}>{worker.error}</Text> : null}
|
||||
<View style={styles.row}>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() =>
|
||||
setSelectedWorkerId((cur) => (cur === worker.workerId ? null : worker.workerId))
|
||||
}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>
|
||||
{selectedWorkerId === worker.workerId ? "Hide Logs" : "View Logs"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{worker.status === "running" || worker.status === "starting" ? (
|
||||
<Pressable
|
||||
style={styles.btnDanger}
|
||||
onPress={() => void stopWorker({ workerId: worker.workerId })}
|
||||
>
|
||||
<Text style={styles.btnDangerText}>Stop</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
{selectedWorker?.workerId === worker.workerId ? (
|
||||
<View style={styles.monoBox}>
|
||||
<View style={[styles.headerRow, { marginBottom: 6 }]}>
|
||||
<Text style={styles.muted}>Output ({worker.outputBytes} bytes)</Text>
|
||||
<Pressable
|
||||
onPress={() => {
|
||||
void copyText(fullLogs || worker.outputTail);
|
||||
toast.show("Copied worker output", { variant: "info" });
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: theme.colors.accent, fontSize: 12 }}>Copy</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<Text style={styles.monoText}>
|
||||
{fullLogs || worker.outputTail || "(no output yet)"}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
|
||||
<Text style={styles.sectionTitle}>Remote Fly Sprites ({sprites.length})</Text>
|
||||
{sprites.length === 0 ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.muted}>No Fly Sprites found.</Text>
|
||||
</View>
|
||||
) : (
|
||||
sprites.map((sprite) => (
|
||||
<View key={sprite.name} style={styles.card}>
|
||||
<View style={styles.headerRow}>
|
||||
<Text style={{ color: theme.colors.foreground, fontWeight: "600", fontSize: 13 }}>
|
||||
{sprite.name}
|
||||
</Text>
|
||||
<Text style={styles.muted}>
|
||||
{sprite.status}
|
||||
{sprite.primaryRegion ? ` · ${sprite.primaryRegion}` : ""}
|
||||
</Text>
|
||||
</View>
|
||||
{sprite.url ? <Text style={styles.muted}>{sprite.url}</Text> : null}
|
||||
<View style={styles.row}>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => setSpriteNameInput(sprite.name)}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Select</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => void handleSyncSprite(sprite.name)}
|
||||
disabled={busy}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Sync Here</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => void handleCheckpoint(sprite.name)}
|
||||
disabled={busy}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Checkpoint</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => void handleLoadCheckpoints(sprite.name)}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Checkpoints</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
style={styles.btnDanger}
|
||||
onPress={() => void handleDestroySprite(sprite.name)}
|
||||
disabled={busy}
|
||||
>
|
||||
<Text style={styles.btnDangerText}>Delete</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
{checkpointsSprite === sprite.name ? (
|
||||
<View style={styles.monoBox}>
|
||||
<Text style={[styles.muted, { marginBottom: 4 }]}>
|
||||
Checkpoints for {sprite.name} ({checkpoints.length})
|
||||
</Text>
|
||||
{checkpoints.length === 0 ? (
|
||||
<Text style={styles.muted}>No checkpoints.</Text>
|
||||
) : (
|
||||
checkpoints.map((cp) => (
|
||||
<View key={cp.id} style={[styles.headerRow, { paddingVertical: 4 }]}>
|
||||
<Text style={styles.muted}>
|
||||
{cp.id} {cp.comment ? `— ${cp.comment}` : ""}
|
||||
</Text>
|
||||
<Pressable
|
||||
style={styles.btnSecondary}
|
||||
onPress={() => void handleRestoreCheckpoint(sprite.name, cp.id)}
|
||||
disabled={busy}
|
||||
>
|
||||
<Text style={styles.btnSecondaryText}>Restore</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type {
|
||||
PluginClientContext,
|
||||
PluginSidebarItemProps,
|
||||
PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
import { FlySpritesSettingsScreen } from "./client/settings-screen";
|
||||
import { FlySpritesWorkersScreen } from "./client/workers-screen";
|
||||
|
||||
function WorkersSidebarItem({ currentScreen, openScreen }: PluginSidebarItemProps) {
|
||||
return (
|
||||
<SidebarRow
|
||||
icon="Cpu"
|
||||
active={currentScreen?.screenId === "workers"}
|
||||
onPress={() => openScreen({ screenId: "workers" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceWorkersPanel({ workspaceId, ...hostProps }: PluginWorkspacePanelProps) {
|
||||
return <FlySpritesWorkersScreen {...hostProps} workspaceId={workspaceId} />;
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addScreen({
|
||||
id: "workers",
|
||||
title: "Fly Sprites Workers",
|
||||
Component: FlySpritesWorkersScreen,
|
||||
});
|
||||
|
||||
client.addWorkspacePanel({
|
||||
id: "fly-sprites-workers",
|
||||
title: "Fly Sprites",
|
||||
icon: "Cpu",
|
||||
Component: WorkspaceWorkersPanel,
|
||||
});
|
||||
|
||||
client.addSidebarHeaderItem({
|
||||
id: "fly-sprites-workers",
|
||||
title: "Fly Sprites",
|
||||
Component: WorkersSidebarItem,
|
||||
});
|
||||
|
||||
client.addCommandCenterItem({
|
||||
id: "open-fly-sprites-workers",
|
||||
title: "Open Fly Sprites Workers",
|
||||
icon: "Cpu",
|
||||
keywords: ["fly", "sprites", "workers", "vm", "sandbox", "remote"],
|
||||
context: "global",
|
||||
onSelect({ openScreen }) {
|
||||
openScreen({ screenId: "workers" });
|
||||
},
|
||||
});
|
||||
|
||||
client.addSettingsScreen({
|
||||
id: "fly-sprites",
|
||||
title: "Fly Sprites Workers",
|
||||
icon: "Cpu",
|
||||
Component: FlySpritesSettingsScreen,
|
||||
});
|
||||
|
||||
return () => {};
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
/// <reference types="node" />
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import { createSpriteAgentTools } from "./server/agent-tools";
|
||||
import { createFlySpritesProvider } from "./server/provider";
|
||||
import { SpritesManager } from "./server/sprites-manager";
|
||||
import {
|
||||
createCheckpointRpc,
|
||||
createSpriteRpc,
|
||||
destroySpriteRpc,
|
||||
listCheckpointsRpc,
|
||||
restoreCheckpointRpc,
|
||||
spawnWorkerRpc,
|
||||
statusRpc,
|
||||
stopWorkerRpc,
|
||||
syncWorkspaceRpc,
|
||||
testConnectionRpc,
|
||||
watchWorkersSub,
|
||||
workerLogsRpc,
|
||||
} from "./shared/contracts";
|
||||
import {
|
||||
defaultFlySpritesSettings,
|
||||
flySpritesSettings,
|
||||
type FlySpritesSettings,
|
||||
} from "./shared/settings";
|
||||
|
||||
function errMsg(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const settingsStore = server.registerSettings(flySpritesSettings);
|
||||
|
||||
async function readSettings(): Promise<FlySpritesSettings> {
|
||||
const state = await settingsStore.read();
|
||||
return state.status === "ready" ? state.values : defaultFlySpritesSettings;
|
||||
}
|
||||
|
||||
const manager = new SpritesManager(readSettings);
|
||||
const provider = createFlySpritesProvider(manager, readSettings);
|
||||
const agentTools = createSpriteAgentTools(manager);
|
||||
|
||||
server.registerProvider(provider);
|
||||
|
||||
const removeOpenHook = server.addHook("agent.open.before", async ({ request }) => {
|
||||
const settings = await readSettings();
|
||||
if (!settings.injectAgentTools) return request;
|
||||
const existing = new Set(request.tools.map((tool) => tool.name));
|
||||
const additions = agentTools.filter((tool) => !existing.has(tool.name));
|
||||
if (additions.length === 0) return request;
|
||||
return {
|
||||
...request,
|
||||
tools: [...request.tools, ...additions],
|
||||
};
|
||||
});
|
||||
|
||||
const removeArchiveHook = server.addHook("agent.archive.after", async ({ agent }) => {
|
||||
const settings = await readSettings();
|
||||
if (!settings.autoCleanupOnArchive) return;
|
||||
const spriteName = provider.getSpriteForSession(agent.id);
|
||||
if (!spriteName) return;
|
||||
await manager.deleteSprite(spriteName).catch(() => undefined);
|
||||
});
|
||||
|
||||
server.handle(testConnectionRpc, async () => {
|
||||
try {
|
||||
const { client, source } = await manager.getClient();
|
||||
const sprites = await client.listAllSprites();
|
||||
return { ok: true as const, spriteCount: sprites.length, source };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(statusRpc, async ({ includeRemote }) => {
|
||||
const { source } = await manager.resolveToken();
|
||||
const configured = source !== "none";
|
||||
const workers = manager.listWorkers();
|
||||
if (!configured || includeRemote === false) {
|
||||
return {
|
||||
configured,
|
||||
tokenSource: source,
|
||||
remoteError: null,
|
||||
sprites: [],
|
||||
workers,
|
||||
};
|
||||
}
|
||||
try {
|
||||
const sprites = await manager.listRemoteSprites();
|
||||
return {
|
||||
configured,
|
||||
tokenSource: source,
|
||||
remoteError: null,
|
||||
sprites,
|
||||
workers,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
configured,
|
||||
tokenSource: source,
|
||||
remoteError: errMsg(error),
|
||||
sprites: [],
|
||||
workers,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(createSpriteRpc, async (input) => {
|
||||
try {
|
||||
const res = await manager.ensureSprite({
|
||||
name: input.name,
|
||||
config: {
|
||||
region: input.region,
|
||||
ramMB: input.ramMB,
|
||||
cpus: input.cpus,
|
||||
},
|
||||
syncLocalPath: input.syncLocalPath,
|
||||
remoteDir: input.remoteDir,
|
||||
});
|
||||
return {
|
||||
ok: true as const,
|
||||
sprite: {
|
||||
name: res.sprite.name,
|
||||
id: res.sprite.id,
|
||||
status: res.sprite.status ?? "ready",
|
||||
organization: res.sprite.organizationName,
|
||||
primaryRegion: res.sprite.primaryRegion,
|
||||
url: res.sprite.url,
|
||||
createdAt: res.sprite.createdAt?.toISOString(),
|
||||
updatedAt: res.sprite.updatedAt?.toISOString(),
|
||||
},
|
||||
syncedFiles: res.syncedFiles,
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(syncWorkspaceRpc, async (input) => {
|
||||
try {
|
||||
const res = await manager.syncWorkspace(input.spriteName, input.localPath, input.remoteDir);
|
||||
return { ok: true as const, ...res };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(spawnWorkerRpc, async (input) => {
|
||||
try {
|
||||
const worker = await manager.spawnWorker({
|
||||
spriteName: input.spriteName,
|
||||
command: input.command,
|
||||
cwd: input.cwd,
|
||||
syncLocalPath: input.syncLocalPath,
|
||||
maxRunAfterDisconnect: input.maxRunAfterDisconnect,
|
||||
});
|
||||
return { ok: true as const, worker };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(stopWorkerRpc, async ({ workerId }) => {
|
||||
const ok = manager.stopWorker(workerId);
|
||||
return ok ? { ok: true } : { ok: false, error: `Unknown worker: ${workerId}` };
|
||||
});
|
||||
|
||||
server.handle(workerLogsRpc, async ({ workerId }) => {
|
||||
const found = manager.getWorker(workerId);
|
||||
if (!found) {
|
||||
return { ok: false as const, error: `Unknown worker: ${workerId}` };
|
||||
}
|
||||
return { ok: true as const, worker: found.summary, output: found.output };
|
||||
});
|
||||
|
||||
server.handle(destroySpriteRpc, async ({ spriteName }) => {
|
||||
try {
|
||||
await manager.deleteSprite(spriteName);
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return { ok: false, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(listCheckpointsRpc, async ({ spriteName }) => {
|
||||
try {
|
||||
const checkpoints = await manager.listCheckpoints(spriteName);
|
||||
return { ok: true as const, checkpoints };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(createCheckpointRpc, async ({ spriteName, comment }) => {
|
||||
try {
|
||||
const messages = await manager.createCheckpoint(spriteName, comment);
|
||||
return { ok: true as const, messages };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(restoreCheckpointRpc, async ({ spriteName, checkpointId }) => {
|
||||
try {
|
||||
const messages = await manager.restoreCheckpoint(spriteName, checkpointId);
|
||||
return { ok: true as const, messages };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error: errMsg(error) };
|
||||
}
|
||||
});
|
||||
|
||||
server.handle(watchWorkersSub, async (_input, context) => {
|
||||
const unsubscribe = manager.subscribeWorkers((workers) => {
|
||||
void context.push({ workers });
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
if (context.signal.aborted) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
context.signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
});
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
return () => {
|
||||
removeOpenHook();
|
||||
removeArchiveHook();
|
||||
manager.dispose();
|
||||
};
|
||||
}
|
||||
Generated
+4168
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "fly-sprites-workers",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"paseo-plugin.json",
|
||||
"OVERVIEW.md",
|
||||
"index.client.tsx",
|
||||
"index.server.ts",
|
||||
"client/",
|
||||
"server/",
|
||||
"shared/"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fly/sprites": "^0.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.16.2",
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@getpaseo/protocol": "0.16.2",
|
||||
"@tanstack/react-query": "^5.90.11",
|
||||
"@types/node": "^22.15.3",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.1.0",
|
||||
"react-native": "0.81.5",
|
||||
"typescript": "^5.9.3",
|
||||
"zod": "^4.4.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"id": "fly-sprites-workers",
|
||||
"name": "Fly Sprites Workers",
|
||||
"media": [],
|
||||
"requirements": {
|
||||
"paseo": ">=0.16.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { defineAgentTool, type AgentToolDefinition } from "@getpaseo/plugin/server";
|
||||
import { z } from "zod";
|
||||
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 function createSpriteAgentTools(manager: SpritesManager): AgentToolDefinition[] {
|
||||
const spriteListTool = defineAgentTool({
|
||||
name: "sprite_list",
|
||||
title: "List Fly Sprites & Workers",
|
||||
description:
|
||||
"List remote Fly Sprites and currently tracked background workers spawned by this plugin.",
|
||||
input: z.object({
|
||||
includeRemote: z.boolean().optional().default(true),
|
||||
}),
|
||||
async execute(input) {
|
||||
try {
|
||||
const workers = manager.listWorkers();
|
||||
const sprites = input.includeRemote ? await manager.listRemoteSprites() : [];
|
||||
return textResult(
|
||||
JSON.stringify({ sprites, workers }, null, 2),
|
||||
{ sprites, workers },
|
||||
);
|
||||
} 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,
|
||||
});
|
||||
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 spriteSpawnWorkerTool = defineAgentTool({
|
||||
name: "sprite_spawn_worker",
|
||||
title: "Spawn Worker on Fly Sprite",
|
||||
description:
|
||||
"Spawn an asynchronous background worker command inside a Fly Sprite. Returns a workerId immediately so you can launch multiple workers in parallel and inspect them later with sprite_worker_status.",
|
||||
input: z.object({
|
||||
command: z.string().describe("Shell command to run inside the Sprite (via bash -lc)."),
|
||||
spriteName: z.string().optional().describe("Target Sprite name; creates a new Sprite if omitted."),
|
||||
cwd: z.string().optional().describe("Working directory inside the Sprite (defaults to /workspace)."),
|
||||
syncWorkspace: z.boolean().optional().default(false).describe("Sync this agent's local workspace into the Sprite before starting."),
|
||||
maxRunAfterDisconnect: z.string().optional().describe("Optional disconnect grace duration, e.g. '30m'."),
|
||||
}),
|
||||
async execute(input, context) {
|
||||
try {
|
||||
const worker = await manager.spawnWorker({
|
||||
spriteName: input.spriteName,
|
||||
command: input.command,
|
||||
cwd: input.cwd,
|
||||
syncLocalPath: input.syncWorkspace ? context.agent.cwd : undefined,
|
||||
maxRunAfterDisconnect: input.maxRunAfterDisconnect,
|
||||
});
|
||||
return textResult(
|
||||
`Spawned worker ${worker.workerId} on sprite ${worker.spriteName} (status=${worker.status}, cwd=${worker.cwd}).`,
|
||||
worker,
|
||||
);
|
||||
} catch (err) {
|
||||
return textResult(`Failed to spawn worker: ${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) {
|
||||
try {
|
||||
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 spriteWorkerStatusTool = defineAgentTool({
|
||||
name: "sprite_worker_status",
|
||||
title: "Check Fly Sprite Worker Status & Logs",
|
||||
description: "Inspect the status and buffered output of a spawned Fly Sprite worker (or list all workers).",
|
||||
input: z.object({
|
||||
workerId: z.string().optional().describe("Worker ID returned by sprite_spawn_worker. Omit to list all workers."),
|
||||
tailChars: z.number().int().positive().optional().default(8000),
|
||||
}),
|
||||
async execute(input) {
|
||||
if (!input.workerId) {
|
||||
const workers = manager.listWorkers();
|
||||
return textResult(JSON.stringify(workers, null, 2), { workers });
|
||||
}
|
||||
const found = manager.getWorker(input.workerId);
|
||||
if (!found) {
|
||||
return textResult(`Unknown worker: ${input.workerId}`, undefined, true);
|
||||
}
|
||||
const output =
|
||||
found.output.length > input.tailChars
|
||||
? found.output.slice(-input.tailChars)
|
||||
: found.output;
|
||||
return textResult(
|
||||
[
|
||||
`workerId: ${found.summary.workerId}`,
|
||||
`sprite: ${found.summary.spriteName}`,
|
||||
`status: ${found.summary.status}`,
|
||||
`exitCode: ${found.summary.exitCode ?? "null"}`,
|
||||
found.summary.error ? `error: ${found.summary.error}` : "",
|
||||
output ? `output:\n${output}` : "(no output yet)",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
{ ...found.summary, output },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const spriteWorkerStopTool = defineAgentTool({
|
||||
name: "sprite_worker_stop",
|
||||
title: "Stop Fly Sprite Worker",
|
||||
description: "Stop a running worker spawned with sprite_spawn_worker.",
|
||||
input: z.object({
|
||||
workerId: z.string(),
|
||||
}),
|
||||
async execute(input) {
|
||||
const stopped = manager.stopWorker(input.workerId);
|
||||
if (!stopped) {
|
||||
return textResult(`Unknown worker: ${input.workerId}`, undefined, true);
|
||||
}
|
||||
return textResult(`Stopped worker ${input.workerId}.`, { workerId: input.workerId, stopped: 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 and stop any active tracked workers on it.",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
}),
|
||||
async execute(input) {
|
||||
try {
|
||||
await manager.deleteSprite(input.spriteName);
|
||||
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,
|
||||
spriteSpawnWorkerTool,
|
||||
spriteExecTool,
|
||||
spriteWorkerStatusTool,
|
||||
spriteWorkerStopTool,
|
||||
spriteCheckpointTool,
|
||||
spriteDestroyTool,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import {
|
||||
ClientSideConnection,
|
||||
PROTOCOL_VERSION,
|
||||
ndJsonStream,
|
||||
type Client,
|
||||
type RequestPermissionRequest,
|
||||
type RequestPermissionResponse,
|
||||
type SessionNotification,
|
||||
} from "@agentclientprotocol/sdk";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
negotiateProviderCapabilities,
|
||||
type ProviderCatalog,
|
||||
type ProviderConfigState,
|
||||
type ProviderConnection,
|
||||
type ProviderContent,
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
type ProviderOptionControl,
|
||||
type ProviderPermissionAction,
|
||||
type ProviderPersistence,
|
||||
type ProviderRegistration,
|
||||
type ProviderToolCallDetail,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import type { SpriteCommand } from "@fly/sprites";
|
||||
import type { FlySpritesSettings } from "../shared/settings";
|
||||
import { sanitizeSpriteName, type SpritesManager } from "./sprites-manager";
|
||||
|
||||
type WorkerMode = "shell" | "acp";
|
||||
|
||||
interface PersistedSpriteSession {
|
||||
spriteName: string;
|
||||
remoteDir: string;
|
||||
mode: WorkerMode;
|
||||
acpSessionId?: string;
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
resolve: (response: RequestPermissionResponse) => void;
|
||||
options: RequestPermissionRequest["options"];
|
||||
}
|
||||
|
||||
interface AcpSessionRuntime {
|
||||
cmd: SpriteCommand;
|
||||
connection: ClientSideConnection;
|
||||
nativeSessionId: string;
|
||||
permissions: Map<string, PendingPermission>;
|
||||
messages: Map<string, string>;
|
||||
toolCalls: Map<string, { id: string; callId: string; name: string; detail: ProviderToolCallDetail }>;
|
||||
msgSeq: number;
|
||||
fallbackIds: Map<string, string>;
|
||||
}
|
||||
|
||||
interface ActiveSpriteSession {
|
||||
sessionId: string;
|
||||
spriteName: string;
|
||||
remoteDir: string;
|
||||
localCwd: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
mode: WorkerMode;
|
||||
syncWorkspace: boolean;
|
||||
checkpointAfterTurn: boolean;
|
||||
persistenceVersion: number;
|
||||
activeShellCmd: SpriteCommand | null;
|
||||
activeTurnId: string | null;
|
||||
canceledTurn: boolean;
|
||||
acp: AcpSessionRuntime | null;
|
||||
}
|
||||
|
||||
function readPersistence(persistence?: ProviderPersistence): PersistedSpriteSession | null {
|
||||
if (!persistence || typeof persistence.data !== "object" || persistence.data === null || Array.isArray(persistence.data)) {
|
||||
return null;
|
||||
}
|
||||
const data = persistence.data as Record<string, unknown>;
|
||||
if (typeof data.spriteName !== "string" || !data.spriteName.trim()) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
spriteName: data.spriteName,
|
||||
remoteDir: typeof data.remoteDir === "string" && data.remoteDir.trim() ? data.remoteDir : "/workspace",
|
||||
mode: data.mode === "acp" ? "acp" : "shell",
|
||||
acpSessionId: typeof data.acpSessionId === "string" ? data.acpSessionId : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function extractPromptText(input: Extract<ProviderInput, { type: "session.prompt" }>["prompt"]["input"]): string {
|
||||
if (input.type === "command") {
|
||||
return input.arguments ? `/${input.name} ${input.arguments}` : `/${input.name}`;
|
||||
}
|
||||
return input.content
|
||||
.map((part: ProviderContent) => {
|
||||
if (part.type === "text") return part.text;
|
||||
if (part.type === "uploaded_file") return `[Uploaded file: ${part.fileName} (${part.path})]`;
|
||||
if (part.type === "image") return "[Image attachment]";
|
||||
if ("title" in part && part.title) return `[${part.type}: ${part.title}]`;
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function toPermissionActions(options: RequestPermissionRequest["options"]): ProviderPermissionAction[] {
|
||||
return options.map((opt) => ({
|
||||
id: opt.optionId,
|
||||
label: opt.name,
|
||||
behavior: opt.kind.startsWith("allow") ? "allow" : "deny",
|
||||
}));
|
||||
}
|
||||
|
||||
function toJsonRecord(value: unknown): Record<string, JsonValue> | undefined {
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
return value as Record<string, JsonValue>;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const SUPPORTED_CAPABILITIES = [
|
||||
"prompt.message",
|
||||
"prompt.command",
|
||||
"session.configure",
|
||||
"session.persistence",
|
||||
"session.can_stop_runtime",
|
||||
"permission",
|
||||
] as const;
|
||||
|
||||
const SESSION_CONTROLS: readonly ProviderOptionControl[] = [
|
||||
{
|
||||
type: "toggle",
|
||||
key: "checkpointAfterTurn",
|
||||
label: "Checkpoint after turn",
|
||||
description: "Create a Fly Sprite checkpoint after each completed turn.",
|
||||
icon: "BookmarkCheck",
|
||||
defaultValue: false,
|
||||
},
|
||||
{
|
||||
type: "toggle",
|
||||
key: "syncWorkspace",
|
||||
label: "Sync local workspace",
|
||||
description: "Sync the local workspace files into /workspace on the Sprite.",
|
||||
icon: "FolderSync",
|
||||
defaultValue: true,
|
||||
},
|
||||
];
|
||||
|
||||
function buildCatalog(defaultMode: WorkerMode): ProviderCatalog {
|
||||
return {
|
||||
models: [
|
||||
{
|
||||
id: "shell",
|
||||
label: "Remote Shell Worker",
|
||||
description: "Execute each prompt as a shell command inside the Fly Sprite.",
|
||||
isDefault: defaultMode === "shell",
|
||||
},
|
||||
{
|
||||
id: "acp",
|
||||
label: "Remote ACP Agent",
|
||||
description: "Run the configured ACP coding agent inside the Fly Sprite.",
|
||||
isDefault: defaultMode === "acp",
|
||||
},
|
||||
],
|
||||
modes: [
|
||||
{ id: "shell", label: "Shell Worker", description: "Direct bash execution on the Sprite" },
|
||||
{ id: "acp", label: "ACP Agent", description: "Remote ACP agent over WebSocket stdio" },
|
||||
],
|
||||
defaultModel: defaultMode,
|
||||
defaultMode,
|
||||
};
|
||||
}
|
||||
|
||||
function buildConfigState(session: ActiveSpriteSession): ProviderConfigState {
|
||||
const catalog = buildCatalog(session.mode);
|
||||
return {
|
||||
model: session.mode,
|
||||
mode: session.mode,
|
||||
models: catalog.models,
|
||||
modes: catalog.modes,
|
||||
thinkingOptions: [],
|
||||
controls: SESSION_CONTROLS,
|
||||
providerOptions: {
|
||||
checkpointAfterTurn: session.checkpointAfterTurn,
|
||||
syncWorkspace: session.syncWorkspace,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface FlySpritesProviderRegistration extends ProviderRegistration {
|
||||
getSpriteForSession(sessionId: string): string | undefined;
|
||||
}
|
||||
|
||||
export function createFlySpritesProvider(
|
||||
manager: SpritesManager,
|
||||
getSettings: () => Promise<FlySpritesSettings>,
|
||||
): FlySpritesProviderRegistration {
|
||||
const sessionSprites = new Map<string, string>();
|
||||
|
||||
async function runShellTurn(
|
||||
session: ActiveSpriteSession,
|
||||
turnId: string,
|
||||
promptText: string,
|
||||
emit: (event: ProviderEvent) => void,
|
||||
): Promise<void> {
|
||||
const { client } = await manager.getClient();
|
||||
const sprite = client.sprite(session.spriteName);
|
||||
const callId = `shell:${turnId}`;
|
||||
let output = "";
|
||||
let lastEmit = 0;
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const emitToolState = (
|
||||
status: "running" | "completed" | "failed" | "canceled",
|
||||
exitCode: number | null,
|
||||
error: JsonValue = null,
|
||||
) => {
|
||||
const detail: ProviderToolCallDetail = {
|
||||
type: "shell",
|
||||
command: promptText,
|
||||
cwd: session.remoteDir,
|
||||
output,
|
||||
exitCode,
|
||||
};
|
||||
if (status === "failed") {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "tool_call",
|
||||
id: callId,
|
||||
callId,
|
||||
name: `sprite:${session.spriteName}`,
|
||||
detail,
|
||||
status: "failed",
|
||||
error,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "tool_call",
|
||||
id: callId,
|
||||
callId,
|
||||
name: `sprite:${session.spriteName}`,
|
||||
detail,
|
||||
status,
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleFlush = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastEmit >= 150) {
|
||||
lastEmit = now;
|
||||
emitToolState("running", null);
|
||||
return;
|
||||
}
|
||||
if (!flushTimer) {
|
||||
flushTimer = setTimeout(() => {
|
||||
flushTimer = null;
|
||||
lastEmit = Date.now();
|
||||
emitToolState("running", null);
|
||||
}, 150);
|
||||
}
|
||||
};
|
||||
|
||||
emitToolState("running", null);
|
||||
|
||||
const cmd = sprite.spawn("bash", ["-lc", promptText], {
|
||||
cwd: session.remoteDir,
|
||||
env: { ...session.env },
|
||||
});
|
||||
session.activeShellCmd = cmd;
|
||||
session.activeTurnId = turnId;
|
||||
session.canceledTurn = false;
|
||||
|
||||
const onChunk = (chunk: Buffer | string) => {
|
||||
output += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
||||
if (output.length > 256 * 1024) {
|
||||
output = output.slice(-256 * 1024);
|
||||
}
|
||||
scheduleFlush();
|
||||
};
|
||||
|
||||
cmd.stdout.on("data", onChunk);
|
||||
cmd.stderr.on("data", onChunk);
|
||||
|
||||
try {
|
||||
const exitCode = await new Promise<number>((resolve, reject) => {
|
||||
cmd.on("error", reject);
|
||||
cmd.on("exit", resolve);
|
||||
});
|
||||
|
||||
if (flushTimer) {
|
||||
clearTimeout(flushTimer);
|
||||
flushTimer = null;
|
||||
}
|
||||
|
||||
if (session.canceledTurn) {
|
||||
emitToolState("canceled", exitCode);
|
||||
emit({ type: "session.turn", sessionId: session.sessionId, turnId, state: "canceled" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (exitCode === 0) {
|
||||
emitToolState("completed", 0);
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
id: `reply:${turnId}`,
|
||||
text: output.trim()
|
||||
? `Completed on \`${session.spriteName}\` (exit 0).`
|
||||
: `Completed on \`${session.spriteName}\` with exit code 0 and no output.`,
|
||||
},
|
||||
});
|
||||
if (session.checkpointAfterTurn) {
|
||||
await manager.createCheckpoint(session.spriteName, `paseo-turn-${turnId}`).catch(() => undefined);
|
||||
}
|
||||
emit({ type: "session.turn", sessionId: session.sessionId, turnId, state: "completed" });
|
||||
} else {
|
||||
const errMsg = `Exited with code ${exitCode}`;
|
||||
emitToolState("failed", exitCode, errMsg);
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
id: `reply:${turnId}`,
|
||||
text: `Command failed on \`${session.spriteName}\` with exit code ${exitCode}.`,
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: session.sessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message: errMsg },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (flushTimer) {
|
||||
clearTimeout(flushTimer);
|
||||
flushTimer = null;
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
emitToolState("failed", null, message);
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: session.sessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message },
|
||||
});
|
||||
} finally {
|
||||
if (session.activeShellCmd === cmd) session.activeShellCmd = null;
|
||||
if (session.activeTurnId === turnId) session.activeTurnId = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureAcpRuntime(
|
||||
session: ActiveSpriteSession,
|
||||
emit: (event: ProviderEvent) => void,
|
||||
): Promise<AcpSessionRuntime> {
|
||||
if (session.acp) return session.acp;
|
||||
const settings = await getSettings();
|
||||
const { client } = await manager.getClient();
|
||||
const sprite = client.sprite(session.spriteName);
|
||||
const acpCmdText = settings.acpCommand.trim() || "claude-code-acp";
|
||||
|
||||
const cmd = sprite.spawn("bash", ["-lc", acpCmdText], {
|
||||
cwd: session.remoteDir,
|
||||
env: { ...session.env },
|
||||
});
|
||||
|
||||
const stderrChunks: string[] = [];
|
||||
cmd.stderr.on("data", (chunk: Buffer | string) => {
|
||||
stderrChunks.push(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
|
||||
});
|
||||
|
||||
const output = Writable.toWeb(cmd.stdin);
|
||||
const input = Readable.toWeb(cmd.stdout) as ReadableStream<Uint8Array>;
|
||||
const stream = ndJsonStream(output, input);
|
||||
|
||||
const runtime: AcpSessionRuntime = {
|
||||
cmd,
|
||||
connection: null as unknown as ClientSideConnection,
|
||||
nativeSessionId: "",
|
||||
permissions: new Map(),
|
||||
messages: new Map(),
|
||||
toolCalls: new Map(),
|
||||
msgSeq: 0,
|
||||
fallbackIds: new Map(),
|
||||
};
|
||||
|
||||
const resolveChunkId = (kind: string, messageId?: string | null) => {
|
||||
if (messageId) {
|
||||
runtime.fallbackIds.delete(kind);
|
||||
return JSON.stringify([kind, messageId]);
|
||||
}
|
||||
let id = runtime.fallbackIds.get(kind);
|
||||
if (!id) {
|
||||
id = `${kind}:${++runtime.msgSeq}`;
|
||||
runtime.fallbackIds.set(kind, id);
|
||||
}
|
||||
return id;
|
||||
};
|
||||
|
||||
const clientHandler: Client = {
|
||||
requestPermission: (req: RequestPermissionRequest) => {
|
||||
const permissionId = `permission:${req.toolCall.toolCallId}`;
|
||||
return new Promise<RequestPermissionResponse>((resolve) => {
|
||||
runtime.permissions.set(permissionId, { resolve, options: req.options });
|
||||
emit({
|
||||
type: "session.permission",
|
||||
sessionId: session.sessionId,
|
||||
request: {
|
||||
id: permissionId,
|
||||
name: req.toolCall.title ?? "Remote tool",
|
||||
kind: "tool",
|
||||
title: req.toolCall.title ?? undefined,
|
||||
input: toJsonRecord(req.toolCall.rawInput),
|
||||
actions: toPermissionActions(req.options),
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
sessionUpdate: async (notification: SessionNotification) => {
|
||||
if (notification.sessionId !== runtime.nativeSessionId) return;
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk") {
|
||||
const other =
|
||||
update.sessionUpdate === "agent_message_chunk" ? "agent_thought_chunk" : "agent_message_chunk";
|
||||
runtime.fallbackIds.delete(other);
|
||||
if (update.content.type !== "text") return;
|
||||
const id = resolveChunkId(update.sessionUpdate, update.messageId);
|
||||
const text = `${runtime.messages.get(id) ?? ""}${update.content.text}`;
|
||||
runtime.messages.set(id, text);
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: update.sessionUpdate === "agent_message_chunk" ? "assistant_message" : "reasoning",
|
||||
id,
|
||||
text,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
runtime.fallbackIds.clear();
|
||||
const prev = runtime.toolCalls.get(update.toolCallId);
|
||||
const title = update.title ?? prev?.name ?? update.toolCallId;
|
||||
const rawStatus = update.status ?? "in_progress";
|
||||
const status =
|
||||
rawStatus === "completed"
|
||||
? "completed"
|
||||
: rawStatus === "failed"
|
||||
? "failed"
|
||||
: "running";
|
||||
const detail: ProviderToolCallDetail = {
|
||||
type: "plain_text",
|
||||
label: title,
|
||||
text:
|
||||
typeof update.rawOutput === "string"
|
||||
? update.rawOutput
|
||||
: update.rawOutput !== undefined
|
||||
? JSON.stringify(update.rawOutput, null, 2)
|
||||
: undefined,
|
||||
icon: "square_terminal",
|
||||
};
|
||||
runtime.toolCalls.set(update.toolCallId, {
|
||||
id: update.toolCallId,
|
||||
callId: update.toolCallId,
|
||||
name: title,
|
||||
detail,
|
||||
});
|
||||
if (status === "failed") {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "tool_call",
|
||||
id: update.toolCallId,
|
||||
callId: update.toolCallId,
|
||||
name: title,
|
||||
detail,
|
||||
status: "failed",
|
||||
error: typeof update.rawOutput === "string" ? update.rawOutput : "Tool failed",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "tool_call",
|
||||
id: update.toolCallId,
|
||||
callId: update.toolCallId,
|
||||
name: title,
|
||||
detail,
|
||||
status,
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "plan") {
|
||||
runtime.fallbackIds.clear();
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: session.sessionId,
|
||||
item: {
|
||||
type: "todo",
|
||||
id: "acp-plan",
|
||||
items: update.entries.map((entry, idx) => ({
|
||||
id: String(idx),
|
||||
text: entry.content,
|
||||
completed: entry.status === "completed",
|
||||
status: entry.status,
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const connection = new ClientSideConnection(() => clientHandler, stream);
|
||||
runtime.connection = connection;
|
||||
|
||||
cmd.on("exit", (code) => {
|
||||
if (session.acp === runtime) {
|
||||
session.acp = null;
|
||||
if (code !== 0) {
|
||||
emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: session.sessionId,
|
||||
error: {
|
||||
message: `Remote ACP command '${acpCmdText}' exited (${code}): ${stderrChunks.join("").trim()}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await connection.initialize({
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {},
|
||||
clientInfo: { name: "paseo-fly-sprites", version: "0.1.0" },
|
||||
});
|
||||
|
||||
const created = await connection.newSession({
|
||||
cwd: session.remoteDir,
|
||||
mcpServers: [],
|
||||
});
|
||||
runtime.nativeSessionId = created.sessionId;
|
||||
session.acp = runtime;
|
||||
return runtime;
|
||||
}
|
||||
|
||||
async function runAcpTurn(
|
||||
session: ActiveSpriteSession,
|
||||
turnId: string,
|
||||
promptText: string,
|
||||
emit: (event: ProviderEvent) => void,
|
||||
): Promise<void> {
|
||||
session.activeTurnId = turnId;
|
||||
session.canceledTurn = false;
|
||||
try {
|
||||
const runtime = await ensureAcpRuntime(session, emit);
|
||||
runtime.fallbackIds.clear();
|
||||
const response = await runtime.connection.prompt({
|
||||
sessionId: runtime.nativeSessionId,
|
||||
prompt: [{ type: "text", text: promptText }],
|
||||
});
|
||||
if (response.usage) {
|
||||
emit({
|
||||
type: "session.usage",
|
||||
sessionId: session.sessionId,
|
||||
turnId,
|
||||
usage: {
|
||||
inputTokens: response.usage.inputTokens ?? undefined,
|
||||
outputTokens: response.usage.outputTokens ?? undefined,
|
||||
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (session.checkpointAfterTurn && response.stopReason !== "cancelled") {
|
||||
await manager.createCheckpoint(session.spriteName, `paseo-turn-${turnId}`).catch(() => undefined);
|
||||
}
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: session.sessionId,
|
||||
turnId,
|
||||
state: response.stopReason === "cancelled" || session.canceledTurn ? "canceled" : "completed",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: session.sessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message },
|
||||
});
|
||||
} finally {
|
||||
if (session.activeTurnId === turnId) session.activeTurnId = null;
|
||||
}
|
||||
}
|
||||
|
||||
const registration: ProviderRegistration & { getSpriteForSession(sessionId: string): string | undefined } = {
|
||||
id: "fly-sprites",
|
||||
label: "Fly Sprites",
|
||||
description: "Run shell workers or remote ACP agents inside Fly.io Sprites microVMs",
|
||||
getSpriteForSession(sessionId: string) {
|
||||
return sessionSprites.get(sessionId);
|
||||
},
|
||||
async status() {
|
||||
const { source } = await manager.resolveToken();
|
||||
if (source === "none") {
|
||||
return {
|
||||
available: false,
|
||||
diagnostic: "Configure a Fly Sprites token in Fly Sprites Workers settings or set SPRITES_TOKEN.",
|
||||
};
|
||||
}
|
||||
return { available: true };
|
||||
},
|
||||
async connect(request): Promise<ProviderConnection> {
|
||||
if (!request.versions.includes(PROVIDER_PROTOCOL_VERSION)) {
|
||||
throw new Error(`Fly Sprites provider requires protocol version ${PROVIDER_PROTOCOL_VERSION}`);
|
||||
}
|
||||
const capabilities = negotiateProviderCapabilities(request.capabilities, SUPPORTED_CAPABILITIES);
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
const sessions = new Map<string, ActiveSpriteSession>();
|
||||
let closed = false;
|
||||
|
||||
const emit = (event: ProviderEvent) => {
|
||||
if (closed) return;
|
||||
for (const listener of listeners) {
|
||||
listener(event);
|
||||
}
|
||||
};
|
||||
|
||||
const closeSessionRuntime = async (session: ActiveSpriteSession) => {
|
||||
if (session.activeShellCmd) {
|
||||
try {
|
||||
session.activeShellCmd.kill("SIGTERM");
|
||||
session.activeShellCmd.close();
|
||||
} catch {
|
||||
// Ignore close errors.
|
||||
}
|
||||
session.activeShellCmd = null;
|
||||
}
|
||||
if (session.acp) {
|
||||
try {
|
||||
session.acp.cmd.kill("SIGTERM");
|
||||
session.acp.cmd.close();
|
||||
} catch {
|
||||
// Ignore close errors.
|
||||
}
|
||||
session.acp = null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
version: PROVIDER_PROTOCOL_VERSION,
|
||||
capabilities,
|
||||
onEvent(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
async send(input) {
|
||||
if (closed) throw new Error("Fly Sprites provider connection is closed");
|
||||
try {
|
||||
switch (input.type) {
|
||||
case "catalog": {
|
||||
const settings = await getSettings();
|
||||
emit({
|
||||
type: "catalog",
|
||||
requestId: input.requestId,
|
||||
catalog: buildCatalog(settings.defaultProviderMode),
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "session.open": {
|
||||
const settings = await getSettings();
|
||||
const persisted = readPersistence(input.persistence);
|
||||
const opts = input.config.providerOptions ?? {};
|
||||
const requestedMode =
|
||||
input.config.mode === "acp" || input.config.model === "acp"
|
||||
? "acp"
|
||||
: input.config.mode === "shell" || input.config.model === "shell"
|
||||
? "shell"
|
||||
: (persisted?.mode ?? settings.defaultProviderMode);
|
||||
const syncWorkspace =
|
||||
typeof opts.syncWorkspace === "boolean"
|
||||
? opts.syncWorkspace
|
||||
: settings.syncWorkspaceOnCreate;
|
||||
const checkpointAfterTurn =
|
||||
typeof opts.checkpointAfterTurn === "boolean" ? opts.checkpointAfterTurn : false;
|
||||
const requestedSpriteName =
|
||||
typeof opts.spriteName === "string" && opts.spriteName.trim()
|
||||
? sanitizeSpriteName(opts.spriteName.trim())
|
||||
: persisted?.spriteName;
|
||||
|
||||
const ensured = await manager.ensureSprite({
|
||||
name: requestedSpriteName,
|
||||
remoteDir: persisted?.remoteDir ?? settings.defaultRemoteCwd,
|
||||
syncLocalPath:
|
||||
syncWorkspace && !persisted ? input.config.cwd : undefined,
|
||||
});
|
||||
|
||||
const session: ActiveSpriteSession = {
|
||||
sessionId: input.sessionId,
|
||||
spriteName: ensured.sprite.name,
|
||||
remoteDir: ensured.remoteDir,
|
||||
localCwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
mode: requestedMode,
|
||||
syncWorkspace,
|
||||
checkpointAfterTurn,
|
||||
persistenceVersion: 1,
|
||||
activeShellCmd: null,
|
||||
activeTurnId: null,
|
||||
canceledTurn: false,
|
||||
acp: null,
|
||||
};
|
||||
sessions.set(input.sessionId, session);
|
||||
sessionSprites.set(input.sessionId, session.spriteName);
|
||||
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities,
|
||||
restoration: "core",
|
||||
persistence: {
|
||||
version: 1,
|
||||
data: {
|
||||
spriteName: session.spriteName,
|
||||
remoteDir: session.remoteDir,
|
||||
mode: session.mode,
|
||||
},
|
||||
},
|
||||
title: input.config.title ?? `Sprite ${session.spriteName}`,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: buildConfigState(session),
|
||||
});
|
||||
emit({
|
||||
type: "session.notice",
|
||||
sessionId: input.sessionId,
|
||||
notice: {
|
||||
id: `sprite-info:${session.spriteName}`,
|
||||
severity: "info",
|
||||
title: `Connected to Fly Sprite: ${session.spriteName}`,
|
||||
description:
|
||||
ensured.syncedFiles !== undefined
|
||||
? `Synced ${ensured.syncedFiles} workspace files to ${session.remoteDir}. Mode: ${session.mode}.`
|
||||
: `Working directory in Sprite: ${session.remoteDir}. Mode: ${session.mode}.`,
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.ready",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "session.prompt": {
|
||||
const session = sessions.get(input.sessionId);
|
||||
if (!session) throw new Error(`Unknown session: ${input.sessionId}`);
|
||||
const promptText = extractPromptText(input.prompt.input);
|
||||
const turnId = `sprite:${input.prompt.clientMessageId}`;
|
||||
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
id: input.prompt.clientMessageId,
|
||||
text: promptText,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
|
||||
if (session.mode === "acp") {
|
||||
void runAcpTurn(session, turnId, promptText, emit);
|
||||
} else {
|
||||
void runShellTurn(session, turnId, promptText, emit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "session.interrupt": {
|
||||
const session = sessions.get(input.sessionId);
|
||||
if (session) {
|
||||
session.canceledTurn = true;
|
||||
if (session.activeShellCmd) {
|
||||
try {
|
||||
session.activeShellCmd.kill("SIGTERM");
|
||||
} catch {
|
||||
// Ignore kill error.
|
||||
}
|
||||
}
|
||||
if (session.acp?.nativeSessionId) {
|
||||
await session.acp.connection
|
||||
.cancel({ sessionId: session.acp.nativeSessionId })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return;
|
||||
}
|
||||
case "session.permission": {
|
||||
const session = sessions.get(input.sessionId);
|
||||
const pending = session?.acp?.permissions.get(input.permissionId);
|
||||
if (session?.acp && pending) {
|
||||
session.acp.permissions.delete(input.permissionId);
|
||||
const selected =
|
||||
pending.options.find((o) => o.optionId === input.response.selectedActionId) ??
|
||||
pending.options.find((o) =>
|
||||
input.response.behavior === "allow"
|
||||
? o.kind.startsWith("allow")
|
||||
: o.kind.startsWith("reject"),
|
||||
);
|
||||
pending.resolve({
|
||||
outcome: selected
|
||||
? { outcome: "selected", optionId: selected.optionId }
|
||||
: { outcome: "cancelled" },
|
||||
});
|
||||
emit({
|
||||
type: "session.permission_resolved",
|
||||
sessionId: input.sessionId,
|
||||
permissionId: input.permissionId,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "session.configure": {
|
||||
const session = sessions.get(input.sessionId);
|
||||
if (!session) throw new Error(`Unknown session: ${input.sessionId}`);
|
||||
const nextMode =
|
||||
input.changes.mode === "acp" || input.changes.model === "acp"
|
||||
? "acp"
|
||||
: input.changes.mode === "shell" || input.changes.model === "shell"
|
||||
? "shell"
|
||||
: session.mode;
|
||||
session.mode = nextMode;
|
||||
const opts = input.changes.providerOptions ?? {};
|
||||
if (typeof opts.checkpointAfterTurn === "boolean") {
|
||||
session.checkpointAfterTurn = opts.checkpointAfterTurn;
|
||||
}
|
||||
if (typeof opts.syncWorkspace === "boolean") {
|
||||
const shouldSyncNow = opts.syncWorkspace && !session.syncWorkspace;
|
||||
session.syncWorkspace = opts.syncWorkspace;
|
||||
if (shouldSyncNow) {
|
||||
await manager.syncWorkspace(session.spriteName, session.localCwd, session.remoteDir);
|
||||
}
|
||||
}
|
||||
emit({
|
||||
type: "session.persistence",
|
||||
sessionId: input.sessionId,
|
||||
persistence: {
|
||||
version: 1,
|
||||
data: {
|
||||
spriteName: session.spriteName,
|
||||
remoteDir: session.remoteDir,
|
||||
mode: session.mode,
|
||||
},
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: buildConfigState(session),
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return;
|
||||
}
|
||||
case "session.can_stop_runtime": {
|
||||
emit({
|
||||
type: "session.can_stop_runtime",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
canStop: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "session.close": {
|
||||
const session = sessions.get(input.sessionId);
|
||||
if (session) {
|
||||
sessions.delete(input.sessionId);
|
||||
await closeSessionRuntime(session);
|
||||
}
|
||||
emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return;
|
||||
}
|
||||
default: {
|
||||
if ("requestId" in input) {
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message: `Unsupported operation: ${input.type}` },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (input.type === "session.prompt") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "failed", error: { message } },
|
||||
});
|
||||
} else if ("requestId" in input) {
|
||||
emit({
|
||||
type: "request.failed",
|
||||
requestId: input.requestId,
|
||||
error: { message },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
async close() {
|
||||
closed = true;
|
||||
const all = [...sessions.values()];
|
||||
sessions.clear();
|
||||
await Promise.all(all.map((s) => closeSessionRuntime(s)));
|
||||
listeners.clear();
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return registration;
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
ExecError,
|
||||
SpritesClient,
|
||||
type Checkpoint,
|
||||
type Sprite,
|
||||
type SpriteCommand,
|
||||
type SpriteConfig,
|
||||
type StreamMessage,
|
||||
} from "@fly/sprites";
|
||||
import type {
|
||||
CheckpointSummary,
|
||||
SpriteSummary,
|
||||
WorkerSummary,
|
||||
} from "../shared/contracts";
|
||||
import type { FlySpritesSettings } from "../shared/settings";
|
||||
|
||||
const execFileAsync = promisify(nodeExecFile);
|
||||
const MAX_OUTPUT_BYTES = 256 * 1024;
|
||||
const TAIL_CHARS = 4000;
|
||||
|
||||
export type TokenSource = "settings" | "env" | "none";
|
||||
|
||||
export interface TrackedWorker {
|
||||
workerId: string;
|
||||
spriteName: string;
|
||||
command: string;
|
||||
cwd: string;
|
||||
status: WorkerSummary["status"];
|
||||
exitCode: number | null;
|
||||
error: string | null;
|
||||
startedAt: string;
|
||||
endedAt: string | null;
|
||||
output: string;
|
||||
outputBytes: number;
|
||||
cmd?: SpriteCommand;
|
||||
}
|
||||
|
||||
export function shellQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
export function sanitizeSpriteName(raw: string): string {
|
||||
const cleaned = raw
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 56);
|
||||
return cleaned || `paseo-worker-${randomBytes(3).toString("hex")}`;
|
||||
}
|
||||
|
||||
function toSpriteSummary(sprite: Sprite): SpriteSummary {
|
||||
return {
|
||||
name: sprite.name,
|
||||
id: sprite.id,
|
||||
status: sprite.status ?? "unknown",
|
||||
organization: sprite.organizationName,
|
||||
primaryRegion: sprite.primaryRegion,
|
||||
url: sprite.url,
|
||||
createdAt: sprite.createdAt?.toISOString(),
|
||||
updatedAt: sprite.updatedAt?.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function toWorkerSummary(worker: TrackedWorker): WorkerSummary {
|
||||
return {
|
||||
workerId: worker.workerId,
|
||||
spriteName: worker.spriteName,
|
||||
command: worker.command,
|
||||
cwd: worker.cwd,
|
||||
status: worker.status,
|
||||
exitCode: worker.exitCode,
|
||||
error: worker.error,
|
||||
startedAt: worker.startedAt,
|
||||
endedAt: worker.endedAt,
|
||||
outputTail:
|
||||
worker.output.length > TAIL_CHARS
|
||||
? worker.output.slice(-TAIL_CHARS)
|
||||
: worker.output,
|
||||
outputBytes: worker.outputBytes,
|
||||
};
|
||||
}
|
||||
|
||||
function formatCheckpointStreamMessage(msg: StreamMessage): string {
|
||||
if (msg.data) return `${msg.type}: ${msg.data}`;
|
||||
if (msg.error) return `error: ${msg.error}`;
|
||||
return msg.type;
|
||||
}
|
||||
|
||||
export class SpritesManager {
|
||||
private readonly getSettings: () => Promise<FlySpritesSettings>;
|
||||
private cachedClient: { key: string; client: SpritesClient } | null = null;
|
||||
private readonly workers = new Map<string, TrackedWorker>();
|
||||
private readonly listeners = new Set<(workers: WorkerSummary[]) => void>();
|
||||
private notifyTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(getSettings: () => Promise<FlySpritesSettings>) {
|
||||
this.getSettings = getSettings;
|
||||
}
|
||||
|
||||
async resolveToken(): Promise<{ token: string; source: TokenSource; baseUrl: string }> {
|
||||
const settings = await this.getSettings();
|
||||
const baseUrl = settings.baseUrl.trim() || "https://api.sprites.dev";
|
||||
const fromSettings = settings.token.trim();
|
||||
if (fromSettings) {
|
||||
return { token: fromSettings, source: "settings", baseUrl };
|
||||
}
|
||||
const fromEnv = process.env.SPRITES_TOKEN?.trim() ?? "";
|
||||
if (fromEnv) {
|
||||
return { token: fromEnv, source: "env", baseUrl };
|
||||
}
|
||||
return { token: "", source: "none", baseUrl };
|
||||
}
|
||||
|
||||
async getClient(): Promise<{ client: SpritesClient; source: "settings" | "env"; settings: FlySpritesSettings }> {
|
||||
const settings = await this.getSettings();
|
||||
const { token, source, baseUrl } = await this.resolveToken();
|
||||
if (!token || source === "none") {
|
||||
throw new Error(
|
||||
"Fly Sprites token is not configured. Set it in Fly Sprites Workers settings or SPRITES_TOKEN.",
|
||||
);
|
||||
}
|
||||
const key = `${baseUrl}::${token}`;
|
||||
if (!this.cachedClient || this.cachedClient.key !== key) {
|
||||
this.cachedClient = {
|
||||
key,
|
||||
client: new SpritesClient(token, { baseURL: baseUrl }),
|
||||
};
|
||||
}
|
||||
return { client: this.cachedClient.client, source, settings };
|
||||
}
|
||||
|
||||
async buildSpriteConfig(overrides?: Partial<SpriteConfig>): Promise<SpriteConfig | undefined> {
|
||||
const settings = await this.getSettings();
|
||||
const config: SpriteConfig = {};
|
||||
const region = overrides?.region?.trim() || settings.defaultRegion.trim();
|
||||
const ramMB = overrides?.ramMB ?? settings.defaultRamMB;
|
||||
const cpus = overrides?.cpus ?? settings.defaultCpus;
|
||||
if (region) config.region = region;
|
||||
if (ramMB && ramMB > 0) config.ramMB = ramMB;
|
||||
if (cpus && cpus > 0) config.cpus = cpus;
|
||||
return Object.keys(config).length > 0 ? config : undefined;
|
||||
}
|
||||
|
||||
async generateSpriteName(prefixOverride?: string): Promise<string> {
|
||||
const settings = await this.getSettings();
|
||||
const prefix = prefixOverride ?? settings.spritePrefix ?? "paseo-worker-";
|
||||
return sanitizeSpriteName(`${prefix}${randomBytes(3).toString("hex")}`);
|
||||
}
|
||||
|
||||
async ensureSprite(options: {
|
||||
name?: string;
|
||||
config?: Partial<SpriteConfig>;
|
||||
syncLocalPath?: string;
|
||||
remoteDir?: string;
|
||||
} = {}): Promise<{ sprite: Sprite; created: boolean; syncedFiles?: number; remoteDir: string }> {
|
||||
const { client, settings } = await this.getClient();
|
||||
const remoteDir = options.remoteDir?.trim() || settings.defaultRemoteCwd.trim() || "/workspace";
|
||||
const name = options.name?.trim()
|
||||
? sanitizeSpriteName(options.name.trim())
|
||||
: await this.generateSpriteName();
|
||||
|
||||
let sprite: Sprite | null = null;
|
||||
let created = false;
|
||||
if (options.name?.trim()) {
|
||||
try {
|
||||
sprite = await client.getSprite(name);
|
||||
} catch {
|
||||
sprite = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sprite) {
|
||||
const spriteConfig = await this.buildSpriteConfig(options.config);
|
||||
sprite = await client.createSprite(name, spriteConfig);
|
||||
created = true;
|
||||
}
|
||||
|
||||
let syncedFiles: number | undefined;
|
||||
if (options.syncLocalPath?.trim()) {
|
||||
const syncResult = await this.syncWorkspace(
|
||||
sprite.name,
|
||||
options.syncLocalPath.trim(),
|
||||
remoteDir,
|
||||
);
|
||||
syncedFiles = syncResult.fileCount;
|
||||
}
|
||||
|
||||
return { sprite, created, syncedFiles, remoteDir };
|
||||
}
|
||||
|
||||
async listRemoteSprites(): Promise<SpriteSummary[]> {
|
||||
const { client } = await this.getClient();
|
||||
const sprites = await client.listAllSprites();
|
||||
return sprites.map(toSpriteSummary);
|
||||
}
|
||||
|
||||
async syncWorkspace(
|
||||
spriteName: string,
|
||||
localPath: string,
|
||||
remoteDirOverride?: string,
|
||||
): Promise<{ fileCount: number; bytes: number; remoteDir: string }> {
|
||||
const { client, settings } = await this.getClient();
|
||||
const remoteDir = remoteDirOverride?.trim() || settings.defaultRemoteCwd.trim() || "/workspace";
|
||||
const info = await stat(localPath).catch(() => null);
|
||||
if (!info?.isDirectory()) {
|
||||
throw new Error(`Local workspace path does not exist or is not a directory: ${localPath}`);
|
||||
}
|
||||
|
||||
const sprite = client.sprite(sanitizeSpriteName(spriteName));
|
||||
|
||||
let isGitRepo = false;
|
||||
let fileListBuffer: Buffer | null = null;
|
||||
let fileCount = 0;
|
||||
|
||||
try {
|
||||
await execFileAsync("git", ["-C", localPath, "rev-parse", "--is-inside-work-tree"]);
|
||||
isGitRepo = true;
|
||||
const { stdout } = await execFileAsync(
|
||||
"git",
|
||||
["-C", localPath, "ls-files", "-z", "-co", "--exclude-standard"],
|
||||
{ encoding: "buffer", maxBuffer: 32 * 1024 * 1024 },
|
||||
);
|
||||
fileListBuffer = stdout;
|
||||
fileCount = stdout.toString("utf8").split("\0").filter(Boolean).length;
|
||||
} catch {
|
||||
isGitRepo = false;
|
||||
}
|
||||
|
||||
const extractCmd = sprite.spawn(
|
||||
"bash",
|
||||
["-lc", `mkdir -p ${shellQuote(remoteDir)} && tar -xzf - -C ${shellQuote(remoteDir)}`],
|
||||
);
|
||||
|
||||
const extractStderr: Buffer[] = [];
|
||||
extractCmd.stderr.on("data", (chunk: Buffer) => extractStderr.push(chunk));
|
||||
|
||||
let sentBytes = 0;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tarArgs = isGitRepo && fileListBuffer && fileCount > 0
|
||||
? ["-czf", "-", "-C", localPath, "--null", "-T", "-"]
|
||||
: [
|
||||
"-czf",
|
||||
"-",
|
||||
"--exclude=node_modules",
|
||||
"--exclude=.git",
|
||||
"--exclude=.DS_Store",
|
||||
"-C",
|
||||
localPath,
|
||||
".",
|
||||
];
|
||||
|
||||
const tarProc = nodeSpawn("tar", tarArgs, { stdio: ["pipe", "pipe", "pipe"] });
|
||||
const tarStderr: Buffer[] = [];
|
||||
tarProc.stderr.on("data", (chunk: Buffer) => tarStderr.push(chunk));
|
||||
|
||||
extractCmd.on("error", (err) => reject(err));
|
||||
tarProc.on("error", (err) => reject(err));
|
||||
|
||||
tarProc.stdout.on("data", (chunk: Buffer) => {
|
||||
sentBytes += chunk.length;
|
||||
extractCmd.stdin.write(chunk);
|
||||
});
|
||||
|
||||
tarProc.on("close", (tarCode) => {
|
||||
if (tarCode !== 0) {
|
||||
extractCmd.kill();
|
||||
reject(
|
||||
new Error(
|
||||
`Local tar failed (${tarCode}): ${Buffer.concat(tarStderr).toString("utf8").trim()}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
extractCmd.stdin.end();
|
||||
});
|
||||
|
||||
extractCmd.on("exit", (code) => {
|
||||
if (code !== 0) {
|
||||
reject(
|
||||
new Error(
|
||||
`Remote tar extract failed (${code}): ${Buffer.concat(extractStderr).toString("utf8").trim()}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
|
||||
if (isGitRepo && fileListBuffer && fileCount > 0) {
|
||||
tarProc.stdin.end(fileListBuffer);
|
||||
} else {
|
||||
tarProc.stdin.end();
|
||||
}
|
||||
});
|
||||
|
||||
return { fileCount, bytes: sentBytes, remoteDir };
|
||||
}
|
||||
|
||||
async execCommand(options: {
|
||||
spriteName: string;
|
||||
command: string;
|
||||
cwd?: string;
|
||||
timeoutMs?: number;
|
||||
}): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const { client, settings } = await this.getClient();
|
||||
const sprite = client.sprite(sanitizeSpriteName(options.spriteName));
|
||||
const cwd = options.cwd?.trim() || settings.defaultRemoteCwd.trim() || "/workspace";
|
||||
try {
|
||||
const result = await sprite.execFile("bash", ["-lc", options.command], {
|
||||
cwd,
|
||||
timeout: options.timeoutMs ?? 120_000,
|
||||
});
|
||||
return {
|
||||
stdout: String(result.stdout),
|
||||
stderr: String(result.stderr),
|
||||
exitCode: result.exitCode,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof ExecError) {
|
||||
return {
|
||||
stdout: String(err.stdout),
|
||||
stderr: String(err.stderr),
|
||||
exitCode: err.exitCode,
|
||||
};
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async spawnWorker(options: {
|
||||
spriteName?: string;
|
||||
command: string;
|
||||
cwd?: string;
|
||||
syncLocalPath?: string;
|
||||
maxRunAfterDisconnect?: string;
|
||||
}): Promise<WorkerSummary> {
|
||||
const { sprite, remoteDir } = await this.ensureSprite({
|
||||
name: options.spriteName,
|
||||
syncLocalPath: options.syncLocalPath,
|
||||
remoteDir: options.cwd,
|
||||
});
|
||||
const cwd = options.cwd?.trim() || remoteDir;
|
||||
const workerId = `wrk_${randomBytes(4).toString("hex")}`;
|
||||
|
||||
const worker: TrackedWorker = {
|
||||
workerId,
|
||||
spriteName: sprite.name,
|
||||
command: options.command,
|
||||
cwd,
|
||||
status: "starting",
|
||||
exitCode: null,
|
||||
error: null,
|
||||
startedAt: new Date().toISOString(),
|
||||
endedAt: null,
|
||||
output: "",
|
||||
outputBytes: 0,
|
||||
};
|
||||
|
||||
const cmd = sprite.spawn("bash", ["-lc", options.command], {
|
||||
cwd,
|
||||
maxRunAfterDisconnect: options.maxRunAfterDisconnect,
|
||||
});
|
||||
worker.cmd = cmd;
|
||||
this.workers.set(workerId, worker);
|
||||
this.emitWorkersUpdate(true);
|
||||
|
||||
const appendOutput = (chunk: Buffer | string) => {
|
||||
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
||||
worker.outputBytes += Buffer.byteLength(text, "utf8");
|
||||
worker.output += text;
|
||||
if (worker.output.length > MAX_OUTPUT_BYTES) {
|
||||
worker.output = worker.output.slice(-MAX_OUTPUT_BYTES);
|
||||
}
|
||||
this.emitWorkersUpdate(false);
|
||||
};
|
||||
|
||||
cmd.on("spawn", () => {
|
||||
if (worker.status === "starting") {
|
||||
worker.status = "running";
|
||||
this.emitWorkersUpdate(true);
|
||||
}
|
||||
});
|
||||
cmd.stdout.on("data", appendOutput);
|
||||
cmd.stderr.on("data", appendOutput);
|
||||
cmd.on("error", (err: unknown) => {
|
||||
worker.status = "failed";
|
||||
worker.error = err instanceof Error ? err.message : String(err);
|
||||
worker.endedAt = new Date().toISOString();
|
||||
worker.cmd = undefined;
|
||||
this.emitWorkersUpdate(true);
|
||||
});
|
||||
cmd.on("exit", (code: number) => {
|
||||
worker.exitCode = code;
|
||||
if (worker.status !== "stopped") {
|
||||
worker.status = code === 0 ? "completed" : "failed";
|
||||
}
|
||||
worker.endedAt = new Date().toISOString();
|
||||
worker.cmd = undefined;
|
||||
this.emitWorkersUpdate(true);
|
||||
});
|
||||
|
||||
return toWorkerSummary(worker);
|
||||
}
|
||||
|
||||
stopWorker(workerId: string): boolean {
|
||||
const worker = this.workers.get(workerId);
|
||||
if (!worker) return false;
|
||||
worker.status = "stopped";
|
||||
worker.endedAt = new Date().toISOString();
|
||||
if (worker.cmd) {
|
||||
try {
|
||||
worker.cmd.kill("SIGTERM");
|
||||
worker.cmd.close();
|
||||
} catch {
|
||||
// Ignore already-closed command sockets.
|
||||
}
|
||||
worker.cmd = undefined;
|
||||
}
|
||||
this.emitWorkersUpdate(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
getWorker(workerId: string): { summary: WorkerSummary; output: string } | null {
|
||||
const worker = this.workers.get(workerId);
|
||||
if (!worker) return null;
|
||||
return { summary: toWorkerSummary(worker), output: worker.output };
|
||||
}
|
||||
|
||||
listWorkers(): WorkerSummary[] {
|
||||
return [...this.workers.values()]
|
||||
.sort((a, b) => b.startedAt.localeCompare(a.startedAt))
|
||||
.map(toWorkerSummary);
|
||||
}
|
||||
|
||||
async deleteSprite(spriteName: string): Promise<void> {
|
||||
const normalized = sanitizeSpriteName(spriteName);
|
||||
for (const worker of this.workers.values()) {
|
||||
if (worker.spriteName === normalized && (worker.status === "starting" || worker.status === "running")) {
|
||||
this.stopWorker(worker.workerId);
|
||||
}
|
||||
}
|
||||
const { client } = await this.getClient();
|
||||
await client.deleteSprite(normalized);
|
||||
}
|
||||
|
||||
async listCheckpoints(spriteName: string): Promise<CheckpointSummary[]> {
|
||||
const { client } = await this.getClient();
|
||||
const sprite = client.sprite(sanitizeSpriteName(spriteName));
|
||||
const checkpoints: Checkpoint[] = await sprite.listCheckpoints();
|
||||
return checkpoints.map((cp) => ({
|
||||
id: cp.id,
|
||||
comment: cp.comment,
|
||||
createdAt: cp.createTime instanceof Date ? cp.createTime.toISOString() : String(cp.createTime),
|
||||
isAuto: cp.isAuto,
|
||||
}));
|
||||
}
|
||||
|
||||
async createCheckpoint(spriteName: string, comment?: string): Promise<string[]> {
|
||||
const { client } = await this.getClient();
|
||||
const sprite = client.sprite(sanitizeSpriteName(spriteName));
|
||||
const stream = await sprite.createCheckpoint(comment);
|
||||
const messages: string[] = [];
|
||||
for await (const msg of stream) {
|
||||
messages.push(formatCheckpointStreamMessage(msg));
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
async restoreCheckpoint(spriteName: string, checkpointId: string): Promise<string[]> {
|
||||
const { client } = await this.getClient();
|
||||
const sprite = client.sprite(sanitizeSpriteName(spriteName));
|
||||
const stream = await sprite.restoreCheckpoint(checkpointId);
|
||||
const messages: string[] = [];
|
||||
for await (const msg of stream) {
|
||||
messages.push(formatCheckpointStreamMessage(msg));
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
subscribeWorkers(listener: (workers: WorkerSummary[]) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
listener(this.listWorkers());
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.notifyTimer) {
|
||||
clearTimeout(this.notifyTimer);
|
||||
this.notifyTimer = null;
|
||||
}
|
||||
for (const worker of this.workers.values()) {
|
||||
if (worker.cmd) {
|
||||
try {
|
||||
worker.cmd.close();
|
||||
} catch {
|
||||
// Ignore close errors during shutdown.
|
||||
}
|
||||
worker.cmd = undefined;
|
||||
}
|
||||
}
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
private emitWorkersUpdate(immediate: boolean): void {
|
||||
if (this.listeners.size === 0) return;
|
||||
if (immediate) {
|
||||
if (this.notifyTimer) {
|
||||
clearTimeout(this.notifyTimer);
|
||||
this.notifyTimer = null;
|
||||
}
|
||||
const snapshot = this.listWorkers();
|
||||
for (const listener of this.listeners) {
|
||||
listener(snapshot);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.notifyTimer) return;
|
||||
this.notifyTimer = setTimeout(() => {
|
||||
this.notifyTimer = null;
|
||||
const snapshot = this.listWorkers();
|
||||
for (const listener of this.listeners) {
|
||||
listener(snapshot);
|
||||
}
|
||||
}, 150);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import { defineRpc, defineSubscription } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const SpriteSummarySchema = z.object({
|
||||
name: z.string(),
|
||||
id: z.string().optional(),
|
||||
status: z.string(),
|
||||
organization: z.string().optional(),
|
||||
primaryRegion: z.string().optional(),
|
||||
url: z.string().optional(),
|
||||
createdAt: z.string().optional(),
|
||||
updatedAt: z.string().optional(),
|
||||
});
|
||||
|
||||
export type SpriteSummary = z.output<typeof SpriteSummarySchema>;
|
||||
|
||||
export const WorkerStatusSchema = z.enum(["starting", "running", "completed", "failed", "stopped"]);
|
||||
|
||||
export const WorkerSummarySchema = z.object({
|
||||
workerId: z.string(),
|
||||
spriteName: z.string(),
|
||||
command: z.string(),
|
||||
cwd: z.string(),
|
||||
status: WorkerStatusSchema,
|
||||
exitCode: z.number().nullable(),
|
||||
error: z.string().nullable(),
|
||||
startedAt: z.string(),
|
||||
endedAt: z.string().nullable(),
|
||||
outputTail: z.string(),
|
||||
outputBytes: z.number(),
|
||||
});
|
||||
|
||||
export type WorkerSummary = z.output<typeof WorkerSummarySchema>;
|
||||
|
||||
export const CheckpointSummarySchema = z.object({
|
||||
id: z.string(),
|
||||
comment: z.string().optional(),
|
||||
createdAt: z.string(),
|
||||
isAuto: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type CheckpointSummary = z.output<typeof CheckpointSummarySchema>;
|
||||
|
||||
export const testConnectionRpc = defineRpc({
|
||||
name: "sprites.test",
|
||||
input: z.object({}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
spriteCount: z.number(),
|
||||
source: z.enum(["settings", "env"]),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const statusRpc = defineRpc({
|
||||
name: "sprites.status",
|
||||
input: z.object({
|
||||
includeRemote: z.boolean().optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
configured: z.boolean(),
|
||||
tokenSource: z.enum(["settings", "env", "none"]),
|
||||
remoteError: z.string().nullable(),
|
||||
sprites: z.array(SpriteSummarySchema),
|
||||
workers: z.array(WorkerSummarySchema),
|
||||
}),
|
||||
});
|
||||
|
||||
export const createSpriteRpc = defineRpc({
|
||||
name: "sprites.create",
|
||||
input: z.object({
|
||||
name: z.string().optional(),
|
||||
region: z.string().optional(),
|
||||
ramMB: z.number().int().positive().optional(),
|
||||
cpus: z.number().int().positive().optional(),
|
||||
syncLocalPath: z.string().optional(),
|
||||
remoteDir: z.string().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
sprite: SpriteSummarySchema,
|
||||
syncedFiles: z.number().optional(),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const syncWorkspaceRpc = defineRpc({
|
||||
name: "sprites.sync",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
localPath: z.string(),
|
||||
remoteDir: z.string().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
fileCount: z.number(),
|
||||
bytes: z.number(),
|
||||
remoteDir: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const spawnWorkerRpc = defineRpc({
|
||||
name: "sprites.worker.spawn",
|
||||
input: z.object({
|
||||
spriteName: z.string().optional(),
|
||||
command: z.string(),
|
||||
cwd: z.string().optional(),
|
||||
syncLocalPath: z.string().optional(),
|
||||
maxRunAfterDisconnect: z.string().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
worker: WorkerSummarySchema,
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const stopWorkerRpc = defineRpc({
|
||||
name: "sprites.worker.stop",
|
||||
input: z.object({
|
||||
workerId: z.string(),
|
||||
}),
|
||||
output: z.object({
|
||||
ok: z.boolean(),
|
||||
error: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const workerLogsRpc = defineRpc({
|
||||
name: "sprites.worker.logs",
|
||||
input: z.object({
|
||||
workerId: z.string(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
worker: WorkerSummarySchema,
|
||||
output: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const destroySpriteRpc = defineRpc({
|
||||
name: "sprites.destroy",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
}),
|
||||
output: z.object({
|
||||
ok: z.boolean(),
|
||||
error: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const listCheckpointsRpc = defineRpc({
|
||||
name: "sprites.checkpoint.list",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
checkpoints: z.array(CheckpointSummarySchema),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const createCheckpointRpc = defineRpc({
|
||||
name: "sprites.checkpoint.create",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
comment: z.string().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
messages: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const restoreCheckpointRpc = defineRpc({
|
||||
name: "sprites.checkpoint.restore",
|
||||
input: z.object({
|
||||
spriteName: z.string(),
|
||||
checkpointId: z.string(),
|
||||
}),
|
||||
output: z.discriminatedUnion("ok", [
|
||||
z.object({
|
||||
ok: z.literal(true),
|
||||
messages: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
ok: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
export const watchWorkersSub = defineSubscription({
|
||||
name: "sprites.watch",
|
||||
input: z.object({}),
|
||||
event: z.object({
|
||||
workers: z.array(WorkerSummarySchema),
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { defineSettings } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const flySpritesSettingsSchema = z.object({
|
||||
token: z.string().default(""),
|
||||
baseUrl: z.string().default("https://api.sprites.dev"),
|
||||
spritePrefix: z.string().default("paseo-worker-"),
|
||||
defaultRegion: z.string().default(""),
|
||||
defaultRamMB: z.number().int().nonnegative().default(0),
|
||||
defaultCpus: z.number().int().nonnegative().default(0),
|
||||
defaultRemoteCwd: z.string().default("/workspace"),
|
||||
defaultProviderMode: z.enum(["shell", "acp"]).default("shell"),
|
||||
acpCommand: z.string().default("claude-code-acp"),
|
||||
syncWorkspaceOnCreate: z.boolean().default(true),
|
||||
injectAgentTools: z.boolean().default(true),
|
||||
autoCleanupOnArchive: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export type FlySpritesSettings = z.output<typeof flySpritesSettingsSchema>;
|
||||
|
||||
export const flySpritesSettings = defineSettings({
|
||||
id: "fly-sprites",
|
||||
scope: "host",
|
||||
version: 1,
|
||||
schema: flySpritesSettingsSchema,
|
||||
});
|
||||
|
||||
export const defaultFlySpritesSettings: FlySpritesSettings = {
|
||||
token: "",
|
||||
baseUrl: "https://api.sprites.dev",
|
||||
spritePrefix: "paseo-worker-",
|
||||
defaultRegion: "",
|
||||
defaultRamMB: 0,
|
||||
defaultCpus: 0,
|
||||
defaultRemoteCwd: "/workspace",
|
||||
defaultProviderMode: "shell",
|
||||
acpCommand: "claude-code-acp",
|
||||
syncWorkspaceOnCreate: true,
|
||||
injectAgentTools: true,
|
||||
autoCleanupOnArchive: false,
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": [
|
||||
"ES2023"
|
||||
],
|
||||
"types": [
|
||||
"node",
|
||||
"react"
|
||||
],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user