Convex-only Slice 1: clients talk to Convex, Flue is a private worker (#20)

This commit is contained in:
2026-07-27 16:03:36 +00:00
parent cc47007fa9
commit cb7484912c
141 changed files with 1547 additions and 17812 deletions

View File

@@ -6,10 +6,8 @@ SITE_URL=http://localhost:5173
NATIVE_APP_URL=code://
# Browser and native public endpoints
VITE_AUTH_URL=http://localhost:5173
VITE_CONVEX_URL=https://example.convex.cloud
VITE_CONVEX_SITE_URL=https://example.convex.site
# For phone testing, replace localhost with this machine's Tailscale IPv4 address.
VITE_FLUE_URL=http://localhost:3583
EXPO_PUBLIC_CONVEX_URL=https://example.convex.cloud
EXPO_PUBLIC_CONVEX_SITE_URL=https://example.convex.site
@@ -23,6 +21,7 @@ DAEMON_COMMAND_LEASE_MS=60000
# Flue persistence adapter
FLUE_DB_TOKEN=replace-with-a-long-random-token
FLUE_URL=http://localhost:3583
# Agent model provider
AGENT_MODEL_PROVIDER=xiaomi

View File

@@ -15,8 +15,6 @@
"@code/env": "workspace:*",
"@code/primitives": "workspace:*",
"@code/ui": "workspace:*",
"@flue/react": "1.0.0-beta.9",
"@flue/sdk": "1.0.0-beta.9",
"@react-router/fs-routes": "^8.1.0",
"@react-router/node": "^8.1.0",
"@react-router/serve": "^8.1.0",
@@ -24,8 +22,8 @@
"isbot": "^5.1.44",
"lucide-react": "catalog:",
"next-themes": "catalog:",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react": "catalog:",
"react-dom": "catalog:",
"react-router": "^8.1.0",
"sonner": "catalog:",
"streamdown": "2.5.0"

View File

@@ -1,7 +1,7 @@
import type { Config } from "@react-router/dev/config";
export default {
// Desktop addons package static web assets; SSR output cannot be bundled
ssr: false,
appDirectory: "src",
ssr: true,
} satisfies Config;

View File

@@ -9,13 +9,13 @@ import {
AttachmentMedia,
AttachmentTitle,
} from "@code/ui/components/attachment";
import type { FlueConversationPart } from "@flue/react";
import { ImageIcon, X } from "lucide-react";
import { useEffect, useState } from "react";
import type { PendingChatImage } from "@/lib/chat/attachments";
import type { ConversationPart } from "@/lib/chat/types";
type FilePart = Extract<FlueConversationPart, { type: "file" }>;
type FilePart = Extract<ConversationPart, { type: "file" }>;
const isDirectlyRenderableUrl = (url: string): boolean =>
url.startsWith("blob:") || url.startsWith("data:");

View File

@@ -7,12 +7,10 @@ import {
MobileChatBubble,
MobileChatMessage,
} from "@code/ui/components/mobile-chat";
import type { FlueConversationMessage } from "@flue/react";
import {
getMessageText,
getReasoningText,
hasToolActivity,
isReasoningStreaming,
isMessageStreaming,
} from "@/lib/chat/transforms";
@@ -23,7 +21,6 @@ import type {
import { AssistantIdentity } from "./assistant-identity";
import { MessageAttachments } from "./chat-attachments";
import { ChatToolCall } from "./chat-tool-call";
const ReasoningTrace = ({
isStreaming,
@@ -96,27 +93,7 @@ const assistantState = (
return isStreaming ? "writing" : undefined;
};
const ToolActivity = ({
hidden,
message,
}: {
readonly hidden: boolean;
readonly message: FlueConversationMessage;
}) => {
if (hidden) {
return null;
}
return message.parts.map((part) =>
part.type === "dynamic-tool" ? (
<ChatToolCall key={part.toolCallId} part={part} />
) : null
);
};
export const ChatMessage = ({
hideToolActivity = false,
message,
}: ChatMessageProps) => {
export const ChatMessage = ({ message }: ChatMessageProps) => {
const isUser = message.role === "user";
const isStreaming = isMessageStreaming(message);
const text = getMessageText(message);
@@ -124,16 +101,6 @@ export const ChatMessage = ({
const reasoningStreaming = isReasoningStreaming(message);
const fileParts = message.parts.filter((part) => part.type === "file");
if (
hideToolActivity &&
!isUser &&
hasToolActivity(message) &&
!text &&
!reasoning
) {
return null;
}
if (message.parts.length === 0 && !isStreaming) {
return null;
}
@@ -167,7 +134,6 @@ export const ChatMessage = ({
text={reasoning}
/>
)}
<ToolActivity hidden={hideToolActivity} message={message} />
{content}
</MobileChatBubble>
</div>

View File

@@ -1,60 +0,0 @@
import {
Tool,
ToolContent,
ToolInput,
ToolOutput,
} from "@code/ui/components/ai-elements/tool";
import { MobileChatToolCall } from "@code/ui/components/mobile-chat";
import { Search, SquareTerminal } from "lucide-react";
import type { ChatToolCallProps } from "@/lib/chat/types";
export const ChatToolCall = ({ part }: ChatToolCallProps) => {
let detail =
typeof part.input === "string"
? part.input
: JSON.stringify(part.input, null, 2);
let status = "running";
let tone: "error" | "neutral" | "success" = "neutral";
if (part.state === "output-available") {
detail =
typeof part.output === "string"
? part.output
: JSON.stringify(part.output, null, 2);
status = "done";
tone = "success";
} else if (part.state === "output-error") {
detail = part.errorText;
status = "failed";
tone = "error";
}
const isSearch = part.toolName.toLowerCase().includes("search");
const output = part.state === "output-available" ? part.output : undefined;
const errorText = part.state === "output-error" ? part.errorText : undefined;
return (
<Tool className="mb-0 w-full border-0" defaultOpen>
<ToolContent className="space-y-0 p-0">
<MobileChatToolCall
detail={detail}
icon={
isSearch ? (
<Search className="size-3" strokeWidth={2.2} />
) : (
<SquareTerminal className="size-3" strokeWidth={2.2} />
)
}
status={status}
tone={tone}
toolName={part.toolName}
/>
<div className="sr-only">
<ToolInput input={part.input} />
<ToolOutput errorText={errorText} output={output} />
</div>
</ToolContent>
</Tool>
);
};

View File

@@ -1,200 +0,0 @@
import { signOutWeb, useWebAuth } from "@code/auth/web";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import {
MobileAssistantChatScreen,
MobileExpandedWorkScreen,
MobileHomeScreen,
MobileWorkChatScreen,
MobileWorkListScreen,
MobileWorkStackScreen,
MobileWorkUnitDetailScreen,
} from "@code/ui/components/mobile-product";
import type { FormEvent } from "react";
import { useNavigate, useParams } from "react-router";
import { useMobileProjectWorkspace } from "@/hooks/use-mobile-project-workspace";
import { useMobileWorkStack } from "@/hooks/use-mobile-work-stack";
import { useMobileWorkspace } from "@/hooks/use-mobile-workspace";
import { MODEL_ID, MODEL_LABEL } from "@/lib/chat/constants";
import { getMobileStatusMessage } from "@/lib/mobile-workspace/mobile-status-message";
import { getUserInitials } from "@/lib/users/get-user-initials";
export type MobileFlowScreen =
| "assistant-chat"
| "home"
| "stack-home"
| "work-chat"
| "work-list"
| "work-unit-detail";
interface MobileFlowPageProps {
screen: MobileFlowScreen;
}
export const MobileFlowPage = ({ screen }: MobileFlowPageProps) => {
const navigate = useNavigate();
const { workUnitId } = useParams();
const auth = useWebAuth();
const projectWorkspace = useMobileProjectWorkspace({
selectedWorkUnitId: workUnitId,
});
const workspace = useMobileWorkspace({
onCreateIssue: (title, body) =>
projectWorkspace.raiseIssue({ body, title }),
onSend: projectWorkspace.sendMessage,
});
const workStack = useMobileWorkStack(projectWorkspace.data.workUnits);
const workPath = "/work";
const chatPath = "/chat";
const handleRestoreChecked = workStack.restoreChecked;
const handleWorkUnitChecked = workStack.markChecked;
const handleWorkUnitSentBack = workStack.sendToBack;
const user = auth.status === "authenticated" ? auth.user : undefined;
const handleSignOut = async () => {
await signOutWeb();
navigate("/login");
};
const statusMessage = getMobileStatusMessage({
assistantError: projectWorkspace.error?.message,
localStatus: workspace.statusMessage,
});
const handleRepositoryChange =
projectWorkspace.projectWorkspace.setRepository;
const handleOpenUnit = (selectedWorkUnitId?: string) => {
const targetId =
selectedWorkUnitId ?? projectWorkspace.data.selectedWorkUnit?.id;
if (!targetId) {
workspace.setProjectManagerOpen(true);
return;
}
if (screen === "work-list" && !workspace.expanded) {
workspace.setExpanded(true);
return;
}
navigate(`/chat/${targetId}`);
};
const screenProps = {
composerValue: workspace.composerValue,
createIssueBody: workspace.issueBody,
createIssueTitle: workspace.issueTitle,
data: projectWorkspace.data,
modelId: MODEL_ID,
modelLabel: MODEL_LABEL,
onBack: () => navigate(chatPath),
onComposerChange: workspace.handleComposerChange,
onComposerMessageSubmit: workspace.handleComposerMessageSubmit,
onComposerSubmit: workspace.handleComposerSubmit,
onCreateBodyChange: workspace.setIssueBody,
onCreateIssue: workspace.handleCreateIssueSubmit,
onCreateIssueFromSignal: projectWorkspace.data.latestSignal?.projectId
? () =>
void projectWorkspace.raiseIssueFromSignal(
projectWorkspace.data.latestSignal?.id ?? ""
)
: undefined,
onCreateTitleChange: workspace.setIssueTitle,
onManageProjects: () => workspace.setProjectManagerOpen(true),
onOpenAssistant: () => navigate(chatPath),
onOpenUnit: handleOpenUnit,
onProjectManagerClose: () => workspace.setProjectManagerOpen(false),
onProjectSelect: (projectId: string) =>
projectWorkspace.projectWorkspace.setSelectedProjectId(
projectId as Id<"projects">
),
onRepositoryChange: projectWorkspace.projectWorkspace.setRepository,
onRepositoryConnect: (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
void projectWorkspace.projectWorkspace.connectRepository();
},
onReviewUnit: (reviewUrl: string) => {
window.open(reviewUrl, "_blank", "noopener,noreferrer");
},
onSettingsClose: () => workspace.setSettingsOpen(false),
onSettingsOpen: () => workspace.setSettingsOpen(true),
onStartUnit: (selectedIssueId: string) => {
void projectWorkspace.startWorkUnit(
selectedIssueId as Id<"projectIssues">
);
},
onViewWork: () => navigate(workPath),
pendingAction: projectWorkspace.projectWorkspace.pendingAction,
projectManagerOpen: workspace.projectManagerOpen,
repositoryValue: projectWorkspace.projectWorkspace.repository,
settingsOpen: workspace.settingsOpen,
statusMessage,
};
if (screen === "assistant-chat") {
return <MobileAssistantChatScreen {...screenProps} />;
}
if (screen === "stack-home") {
return (
<MobileWorkStackScreen
checkedCount={workStack.checkedCount}
composerValue={workspace.composerValue}
data={projectWorkspace.data}
modelId={MODEL_ID}
modelLabel={MODEL_LABEL}
onAddProject={() => workspace.setProjectManagerOpen(true)}
onComposerChange={workspace.handleComposerChange}
onComposerSubmit={workspace.handleComposerSubmit}
onOpenUnit={(selectedWorkUnitId) =>
navigate(`/chat/${selectedWorkUnitId}`)
}
onProjectSelect={(projectId) =>
projectWorkspace.projectWorkspace.setSelectedProjectId(
projectId as Id<"projects">
)
}
onProjectManagerClose={() => workspace.setProjectManagerOpen(false)}
onRepositoryChange={handleRepositoryChange}
onRepositoryConnect={(event) => {
event.preventDefault();
void projectWorkspace.projectWorkspace.connectRepository();
}}
onRestoreChecked={handleRestoreChecked}
onSettingsClose={() => workspace.setSettingsOpen(false)}
onSettingsOpen={() => workspace.setSettingsOpen(true)}
onSignOut={() => {
void handleSignOut();
}}
onWorkUnitChecked={handleWorkUnitChecked}
onWorkUnitSentBack={handleWorkUnitSentBack}
pendingAction={projectWorkspace.projectWorkspace.pendingAction}
projectManagerOpen={workspace.projectManagerOpen}
repositoryValue={projectWorkspace.projectWorkspace.repository}
settingsOpen={workspace.settingsOpen}
statusMessage={statusMessage}
userEmail={user?.email}
userInitials={getUserInitials(user?.name)}
userName={user?.name}
workUnits={workStack.visibleWorkUnits}
/>
);
}
if (screen === "work-chat") {
return (
<MobileWorkChatScreen
composerValue={workspace.composerValue}
data={projectWorkspace.data}
onBack={() => navigate(chatPath)}
onComposerChange={workspace.handleComposerChange}
onComposerMessageSubmit={workspace.handleComposerMessageSubmit}
onComposerSubmit={workspace.handleComposerSubmit}
statusMessage={statusMessage}
/>
);
}
if (screen === "home") {
return <MobileHomeScreen {...screenProps} />;
}
if (screen === "work-unit-detail") {
return <MobileWorkUnitDetailScreen {...screenProps} />;
}
if (workspace.expanded) {
return <MobileExpandedWorkScreen {...screenProps} />;
}
return <MobileWorkListScreen {...screenProps} />;
};

View File

@@ -23,7 +23,6 @@ import { ChatThinkingResponse } from "@/components/chat/chat-thinking-response";
import { useChatImages } from "@/hooks/chat/use-chat-images";
import { useSliceOne } from "@/hooks/slice-one/use-slice-one";
import { useVisualViewportStyle } from "@/hooks/slice-one/use-visual-viewport";
import { chatImageToPromptImage } from "@/lib/chat/attachments";
import {
buildSliceOneTimeline,
findSourceMessageTarget,
@@ -90,6 +89,78 @@ const WorkCard = ({ onSourceSelect, work }: WorkCardProps) => {
);
};
const ConversationLoading = () => (
<output
aria-label="Loading conversation"
className="mx-auto flex min-h-[55vh] w-full max-w-md flex-col justify-center gap-4"
>
<span className="h-16 w-4/5 animate-pulse rounded-sm bg-[#e3e0d5]" />
<span className="ml-auto h-12 w-3/5 animate-pulse rounded-sm bg-[#dedbd0]" />
<span className="h-24 w-full animate-pulse rounded-sm bg-[#e3e0d5]" />
<span className="sr-only">Loading conversation</span>
</output>
);
const ConversationEmptyState = () => (
<div className="grid min-h-[55vh] place-items-center text-center">
<div>
<MessageSquareText className="mx-auto size-7 text-[#8a887f]" />
<h1 className="mt-4 text-xl font-semibold">What should move forward?</h1>
<p className="mx-auto mt-2 max-w-sm text-sm leading-6 text-[#69675f]">
Describe an outcome or problem. Casual conversation stays conversation.
</p>
</div>
</div>
);
type SliceOneState = ReturnType<typeof useSliceOne>;
const ProjectsLoading = () => (
<div className="grid min-h-svh place-items-center bg-[#f2f0e7]">
<LoaderCircle className="size-5 animate-spin" />
</div>
);
const ConnectProject = ({ slice }: { slice: SliceOneState }) => (
<main className="grid min-h-svh place-items-center bg-[#f2f0e7] px-5 text-[#20201d]">
<form
className="w-full max-w-sm"
onSubmit={(event) => {
event.preventDefault();
void slice.connectRepository();
}}
>
<span className="grid size-11 place-items-center bg-[#20201d] text-white">
<FolderGit2 className="size-5" />
</span>
<h1 className="mt-6 text-2xl font-semibold">Connect one project</h1>
<p className="mt-2 text-sm leading-6 text-[#68665e]">
Slice 1 turns actionable conversation into proposed Work with exact
provenance.
</p>
<input
aria-label="Public Git repository URL"
className="mt-6 h-12 w-full border border-[#c9c5b9] bg-[#fffefa] px-3 text-sm outline-none focus:border-[#55564e]"
onChange={(event) => slice.setRepository(event.target.value)}
placeholder="https://github.com/owner/repository"
required
value={slice.repository}
/>
{slice.error ? (
<p className="mt-2 text-xs text-red-700">{slice.error.message}</p>
) : null}
<Button
className="mt-3 h-12 w-full"
disabled={slice.pending}
type="submit"
>
{slice.pending ? (
<LoaderCircle className="size-4 animate-spin" />
) : null}
{slice.pending ? "Connecting" : "Connect project"}
</Button>
</form>
</main>
);
export const SliceOnePage = () => {
const slice = useSliceOne();
const viewportStyle = useVisualViewportStyle();
@@ -134,55 +205,11 @@ export const SliceOnePage = () => {
};
if (slice.projects === undefined) {
return (
<div className="grid min-h-svh place-items-center bg-[#f2f0e7]">
<LoaderCircle className="size-5 animate-spin" />
</div>
);
return <ProjectsLoading />;
}
if (!slice.selectedProject) {
return (
<main className="grid min-h-svh place-items-center bg-[#f2f0e7] px-5 text-[#20201d]">
<form
className="w-full max-w-sm"
onSubmit={(event) => {
event.preventDefault();
void slice.connectRepository();
}}
>
<span className="grid size-11 place-items-center bg-[#20201d] text-white">
<FolderGit2 className="size-5" />
</span>
<h1 className="mt-6 text-2xl font-semibold">Connect one project</h1>
<p className="mt-2 text-sm leading-6 text-[#68665e]">
Slice 1 turns actionable conversation into proposed Work with exact
provenance.
</p>
<input
aria-label="Public Git repository URL"
className="mt-6 h-12 w-full border border-[#c9c5b9] bg-[#fffefa] px-3 text-sm outline-none focus:border-[#55564e]"
onChange={(event) => slice.setRepository(event.target.value)}
placeholder="https://github.com/owner/repository"
required
value={slice.repository}
/>
{slice.error ? (
<p className="mt-2 text-xs text-red-700">{slice.error.message}</p>
) : null}
<Button
className="mt-3 h-12 w-full"
disabled={slice.pending}
type="submit"
>
{slice.pending ? (
<LoaderCircle className="size-4 animate-spin" />
) : null}
{slice.pending ? "Connecting" : "Connect project"}
</Button>
</form>
</main>
);
return <ConnectProject slice={slice} />;
}
const send = async () => {
@@ -190,10 +217,9 @@ export const SliceOnePage = () => {
if (!message || busy) {
return;
}
const images = await Promise.all(
attachments.images.map(chatImageToPromptImage)
);
await slice.agent.sendMessage(message, { images });
await slice.agent.sendMessage(message, {
images: attachments.images.map((image) => image.file),
});
setDraft("");
attachments.clear();
};
@@ -233,19 +259,11 @@ export const SliceOnePage = () => {
</header>
<Conversation className="min-h-0 flex-1">
<ConversationContent className="mx-auto min-h-full w-full max-w-2xl gap-4 px-4 py-5 sm:px-6">
{!slice.agent.historyReady && timeline.length === 0 ? (
<ConversationLoading />
) : null}
{slice.agent.historyReady && timeline.length === 0 ? (
<div className="grid min-h-[55vh] place-items-center text-center">
<div>
<MessageSquareText className="mx-auto size-7 text-[#8a887f]" />
<h1 className="mt-4 text-xl font-semibold">
What should move forward?
</h1>
<p className="mx-auto mt-2 max-w-sm text-sm leading-6 text-[#69675f]">
Describe an outcome or problem. Casual conversation stays
conversation.
</p>
</div>
</div>
<ConversationEmptyState />
) : null}
{timeline.map((item) => {
if (item.kind === "work") {
@@ -275,7 +293,7 @@ export const SliceOnePage = () => {
id={`slice-message-${item.message.id}`}
key={item.message.id}
>
<ChatMessage hideToolActivity message={item.message} />
<ChatMessage message={item.message} />
</div>
);
})}

View File

@@ -1,79 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { useChatAgent } from "./use-chat-agent";
const mocks = vi.hoisted(() => ({
agent: {
error: undefined,
historyReady: true,
messages: [],
sendMessage: vi.fn(() => Promise.resolve()),
status: "idle" as const,
},
organization: {} as { error?: Error; organizationId?: string },
useFlueAgent: vi.fn(),
}));
vi.mock("@flue/react", () => ({
useFlueAgent: mocks.useFlueAgent,
}));
vi.mock("@/hooks/use-personal-organization", () => ({
usePersonalOrganization: () => mocks.organization,
}));
describe("useChatAgent", () => {
beforeEach(() => {
mocks.organization = {};
mocks.agent.sendMessage.mockClear();
mocks.useFlueAgent.mockReset();
mocks.useFlueAgent.mockReturnValue(mocks.agent);
});
test("does not use the agent before organization bootstrap completes", async () => {
const chat = useChatAgent();
expect(mocks.useFlueAgent).toHaveBeenCalledWith({
id: undefined,
live: "sse",
name: "zopu",
});
expect(chat.status).toBe("connecting");
await expect(chat.sendMessage("too early")).rejects.toThrow(
"Personal organization is still being prepared"
);
expect(mocks.agent.sendMessage).not.toHaveBeenCalled();
});
test("uses the ensured organization id for the agent session", async () => {
mocks.organization = { organizationId: "org-a" };
const chat = useChatAgent();
expect(mocks.useFlueAgent).toHaveBeenCalledWith({
id: "org-a",
live: "sse",
name: "zopu",
});
await chat.sendMessage("ready");
expect(mocks.agent.sendMessage).toHaveBeenCalledWith("ready", undefined);
});
test("forwards image attachments through to the Flue agent", async () => {
mocks.organization = { organizationId: "org-a" };
const images = [
{
data: "abc",
filename: "a.png",
mimeType: "image/png",
type: "image" as const,
},
];
const chat = useChatAgent();
await chat.sendMessage("describe this", { images });
expect(mocks.agent.sendMessage).toHaveBeenCalledWith("describe this", {
images,
});
});
});

View File

@@ -1,45 +1,106 @@
import type { SendMessageOptions } from "@flue/react";
import { useFlueAgent } from "@flue/react";
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { useMutation, useQuery } from "convex/react";
import { useState } from "react";
import { usePersonalOrganization } from "@/hooks/use-personal-organization";
import type { PersonalOrganizationState } from "@/hooks/use-personal-organization";
import { CHAT_AGENT } from "@/lib/chat/constants";
import type { ChatAgentState } from "@/lib/chat/types";
import { projectConversation } from "@/lib/chat/conversation";
import type { AgentStatus, ChatAgentState } from "@/lib/chat/types";
const requestId = (): string =>
globalThis.crypto?.randomUUID?.() ??
`${Date.now()}-${Math.random().toString(16).slice(2)}`;
const uploadImage = async (
file: File,
generateUploadUrl: () => Promise<string>
) => {
const response = await fetch(await generateUploadUrl(), {
body: file,
headers: { "content-type": file.type },
method: "POST",
});
if (!response.ok) {
throw new Error(`Image upload failed (${response.status})`);
}
const payload: unknown = await response.json();
if (
typeof payload !== "object" ||
payload === null ||
!("storageId" in payload) ||
typeof payload.storageId !== "string"
) {
throw new Error("Image upload returned an invalid response");
}
return {
filename: file.name || undefined,
mimeType: file.type,
storageId: payload.storageId as Id<"_storage">,
};
};
export const useOrganizationChatAgent = (
organization: PersonalOrganizationState
): ChatAgentState => {
const agent = useFlueAgent({
...CHAT_AGENT,
id: organization.organizationId,
});
const { organizationId } = organization;
const rows = useQuery(
api.conversationMessages.listForCurrentOrganization,
organizationId ? { organizationId } : "skip"
);
const send = useMutation(api.conversationMessages.send);
const generateUploadUrl = useMutation(
api.conversationMessages.generateUploadUrl
);
const [sendError, setSendError] = useState<Error>();
const projected = projectConversation(rows ?? []);
let status: AgentStatus = projected.pending ? "submitted" : "idle";
if (!organizationId || rows === undefined) {
status = organization.error ? "error" : "connecting";
} else if (projected.failedError || sendError) {
status = "error";
}
const sendMessage = async (
message: string,
options?: SendMessageOptions
options?: { readonly images?: readonly File[] }
): Promise<void> => {
if (!organization.organizationId) {
if (!organizationId) {
throw (
organization.error ??
new Error("Personal organization is still being prepared")
);
}
await agent.sendMessage(message, options);
setSendError(undefined);
try {
const images = await Promise.all(
(options?.images ?? []).map((file) =>
uploadImage(file, generateUploadUrl)
)
);
await send({
clientRequestId: requestId(),
images,
organizationId,
rawText: message,
});
} catch (error) {
const normalized =
error instanceof Error ? error : new Error(String(error));
setSendError(normalized);
throw normalized;
}
};
let { status } = agent;
if (!organization.organizationId) {
status = organization.error ? "error" : "connecting";
}
return {
error: organization.error ?? agent.error,
historyReady: agent.historyReady,
messages: agent.messages,
error:
organization.error ??
sendError ??
(projected.failedError ? new Error(projected.failedError) : undefined),
historyReady: rows !== undefined,
messages: projected.messages,
sendMessage,
status,
};
};
export const useChatAgent = (): ChatAgentState =>
useOrganizationChatAgent(usePersonalOrganization());

View File

@@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from "react";
import { MAX_CHAT_IMAGES, validateChatImage } from "@/lib/chat/attachments";
import type { PendingChatImage } from "@/lib/chat/attachments";
import { generateBrowserRequestId } from "@/lib/flue-transport";
const generateImageId = (): string =>
globalThis.crypto?.randomUUID?.() ??
`${Date.now()}-${Math.random().toString(16).slice(2)}`;
export const useChatImages = () => {
const [images, setImages] = useState<PendingChatImage[]>([]);
@@ -40,7 +43,7 @@ export const useChatImages = () => {
previewUrls.current.add(previewUrl);
next.push({
file,
id: generateBrowserRequestId(),
id: generateImageId(),
previewUrl,
});
}

View File

@@ -3,15 +3,20 @@ import type { Id } from "@code/backend/convex/_generated/dataModel";
import { useAction, useQuery } from "convex/react";
import { useMemo, useState } from "react";
import { useChatAgent } from "@/hooks/chat/use-chat-agent";
import { useOrganizationChatAgent } from "@/hooks/chat/use-chat-agent";
import { usePersonalOrganization } from "@/hooks/use-personal-organization";
const toError = (error: unknown) =>
error instanceof Error ? error : new Error(String(error));
export const useSliceOne = () => {
const projects = useQuery(api.projects.list);
const organization = usePersonalOrganization();
const projects = useQuery(
api.projects.list,
organization.organizationId ? {} : "skip"
);
const importPublicGit = useAction(api.projects.importPublicGit);
const agent = useChatAgent();
const agent = useOrganizationChatAgent(organization);
const [selectedProjectId, setSelectedProjectId] =
useState<Id<"projects"> | null>(null);
const [repository, setRepository] = useState("");

View File

@@ -1,126 +0,0 @@
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import type {
MobileAssistantMessageView,
MobileAssistantView,
} from "@code/ui/components/mobile-product";
import { useQuery } from "convex/react";
import { useOrganizationChatAgent } from "@/hooks/chat/use-chat-agent";
import { usePersonalOrganization } from "@/hooks/use-personal-organization";
import { useProjectWorkspace } from "@/hooks/use-project-workspace";
import { STATUS_COPY } from "@/lib/chat/constants";
import { getMessageText } from "@/lib/chat/transforms";
import { buildMobileWorkspaceView } from "@/lib/mobile-workspace/build-mobile-workspace-view";
const WORK_UNIT_SCOPE_PATTERN =
/^<zopu-work-unit id="(?<workUnitId>[^"]+)">[\s\S]*?<message>(?<message>[\s\S]*?)<\/message>\s*<\/zopu-work-unit>$/u;
const toAssistantMessages = (
messages: ReturnType<typeof useOrganizationChatAgent>["messages"],
selectedWorkUnitId?: string
): MobileAssistantMessageView[] => {
const result: MobileAssistantMessageView[] = [];
for (const message of messages) {
if (message.role !== "assistant" && message.role !== "user") {
continue;
}
const rawText = getMessageText(message);
if (!rawText) {
continue;
}
if (!selectedWorkUnitId) {
result.push({ id: message.id, role: message.role, text: rawText });
continue;
}
if (message.role === "user") {
const match = WORK_UNIT_SCOPE_PATTERN.exec(rawText);
if (match?.groups?.workUnitId !== selectedWorkUnitId) {
result.length = 0;
continue;
}
result.push({
id: message.id,
role: message.role,
text: match.groups.message?.trim() ?? rawText,
});
continue;
}
if (result.length > 0) {
result.push({ id: message.id, role: message.role, text: rawText });
}
}
return result;
};
const getStatusTone = (
status: ReturnType<typeof useOrganizationChatAgent>["status"]
): MobileAssistantView["statusTone"] => {
if (status === "error") {
return "red";
}
return status === "connecting" ? "amber" : "green";
};
interface UseMobileProjectWorkspaceOptions {
readonly selectedWorkUnitId?: string;
}
export const useMobileProjectWorkspace = ({
selectedWorkUnitId,
}: UseMobileProjectWorkspaceOptions) => {
const organization = usePersonalOrganization();
const projectWorkspace = useProjectWorkspace();
const chatAgent = useOrganizationChatAgent(organization);
const signals = useQuery(
api.signals.list,
organization.organizationId
? { organizationId: organization.organizationId }
: "skip"
);
const selectedIssue = projectWorkspace.issues?.find(
(issue) => String(issue._id) === selectedWorkUnitId
);
const sendMessage = (message: string) => {
if (!selectedIssue) {
return chatAgent.sendMessage(message);
}
return chatAgent.sendMessage(
`<zopu-work-unit id="${selectedIssue._id}">\n<context>Issue #${selectedIssue.number}: ${selectedIssue.title}</context>\n<message>${message}</message>\n</zopu-work-unit>`
);
};
const assistant: MobileAssistantView = {
isBusy:
chatAgent.status === "connecting" ||
chatAgent.status === "streaming" ||
chatAgent.status === "submitted",
messages: toAssistantMessages(chatAgent.messages, selectedWorkUnitId),
statusLabel: STATUS_COPY[chatAgent.status],
statusTone: getStatusTone(chatAgent.status),
};
return {
data: buildMobileWorkspaceView({
artifacts: projectWorkspace.artifacts,
assistant,
events: projectWorkspace.events,
issues: projectWorkspace.issues,
organizationLabel: organization.organizationName,
projects: projectWorkspace.projects,
selectedProject: projectWorkspace.selectedProject,
selectedWorkUnitId,
signals,
}),
error:
organization.error ??
chatAgent.error ??
(projectWorkspace.error ? new Error(projectWorkspace.error) : undefined),
organization,
projectWorkspace,
raiseIssue: projectWorkspace.raiseIssue,
raiseIssueFromSignal: (signalId: string) =>
projectWorkspace.raiseIssueFromSignal(signalId as Id<"signals">),
sendMessage,
startWorkUnit: projectWorkspace.startWorkUnit,
} as const;
};

View File

@@ -1,66 +0,0 @@
import type { MobileWorkUnitView } from "@code/ui/components/mobile-product";
import { useCallback, useMemo, useState } from "react";
export const useMobileWorkStack = (
workUnits: readonly MobileWorkUnitView[]
) => {
const [order, setOrder] = useState<readonly string[]>([]);
const [checkedIds, setCheckedIds] = useState<ReadonlySet<string>>(
() => new Set()
);
const workUnitsById = useMemo(
() => new Map(workUnits.map((workUnit) => [workUnit.id, workUnit])),
[workUnits]
);
const availableIds = useMemo(
() => new Set(workUnitsById.keys()),
[workUnitsById]
);
const visibleWorkUnits = useMemo(() => {
const retainedOrder = order.filter(
(workUnitId) =>
availableIds.has(workUnitId) && !checkedIds.has(workUnitId)
);
const retainedIds = new Set(retainedOrder);
const addedIds = workUnits
.map((workUnit) => workUnit.id)
.filter(
(workUnitId) =>
!retainedIds.has(workUnitId) && !checkedIds.has(workUnitId)
);
return [...retainedOrder, ...addedIds].flatMap((workUnitId) => {
const workUnit = workUnitsById.get(workUnitId);
return workUnit ? [workUnit] : [];
});
}, [availableIds, checkedIds, order, workUnits, workUnitsById]);
const sendToBack = useCallback(
(workUnitId: string) => {
if (visibleWorkUnits[0]?.id !== workUnitId) {
return;
}
setOrder([...visibleWorkUnits.slice(1).map(({ id }) => id), workUnitId]);
},
[visibleWorkUnits]
);
const markChecked = useCallback((workUnitId: string) => {
setCheckedIds((current) => new Set(current).add(workUnitId));
}, []);
const restoreChecked = useCallback(() => {
setCheckedIds(new Set());
setOrder([]);
}, []);
return {
checkedCount: [...checkedIds].filter((workUnitId) =>
availableIds.has(workUnitId)
).length,
markChecked,
restoreChecked,
sendToBack,
visibleWorkUnits,
} as const;
};

View File

@@ -1,98 +0,0 @@
import type { FormEvent } from "react";
import { useState } from "react";
interface UseMobileWorkspaceOptions {
readonly initialExpanded?: boolean;
readonly onCreateIssue: (title: string, body: string) => Promise<void>;
readonly onSend: (message: string) => Promise<void>;
}
const errorMessage = (error: unknown) =>
error instanceof Error ? error.message : "Message could not be sent";
export const useMobileWorkspace = ({
initialExpanded = false,
onCreateIssue,
onSend,
}: UseMobileWorkspaceOptions) => {
const [composerValue, setComposerValue] = useState("");
const [issueBody, setIssueBody] = useState("");
const [issueTitle, setIssueTitle] = useState("");
const [expanded, setExpanded] = useState(initialExpanded);
const [projectManagerOpen, setProjectManagerOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [statusMessage, setStatusMessage] = useState<string>();
const handleComposerChange = (value: string) => {
setComposerValue(value);
setStatusMessage(undefined);
};
const submitMessage = async (message: string) => {
const trimmedMessage = message.trim();
if (!trimmedMessage) {
return;
}
setStatusMessage("Sending to Zopu…");
try {
await onSend(trimmedMessage);
setComposerValue("");
setStatusMessage("Sent to Zopu");
} catch (error) {
setStatusMessage(errorMessage(error));
throw error;
}
};
const handleComposerSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const sendCurrentMessage = async () => {
try {
await submitMessage(composerValue);
} catch {
// submitMessage already exposes the failure through statusMessage.
}
};
void sendCurrentMessage();
};
const handleCreateIssueSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const title = issueTitle.trim();
const body = issueBody.trim();
if (!title || !body) {
return;
}
setStatusMessage("Creating project work…");
const createIssue = async () => {
try {
await onCreateIssue(title, body);
setIssueTitle("");
setIssueBody("");
setStatusMessage("Project work created");
} catch (error) {
setStatusMessage(errorMessage(error));
}
};
void createIssue();
};
return {
composerValue,
expanded,
handleComposerChange,
handleComposerMessageSubmit: submitMessage,
handleComposerSubmit,
handleCreateIssueSubmit,
issueBody,
issueTitle,
projectManagerOpen,
setExpanded,
setIssueBody,
setIssueTitle,
setProjectManagerOpen,
setSettingsOpen,
settingsOpen,
statusMessage,
};
};

View File

@@ -1,7 +1,7 @@
import { useWebAuth } from "@code/auth/web";
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { useMutation } from "convex/react";
import { useConvexAuth, useMutation } from "convex/react";
import { useEffect, useState } from "react";
export interface PersonalOrganizationState {
@@ -13,6 +13,8 @@ export interface PersonalOrganizationState {
/** Ensure the authenticated user has its personal tenancy boundary. */
export const usePersonalOrganization = (): PersonalOrganizationState => {
const auth = useWebAuth();
const { isAuthenticated, isRefreshing } = useConvexAuth();
const convexReady = isAuthenticated && !isRefreshing;
const userId = auth.status === "authenticated" ? auth.user.id : null;
const ensurePersonalOrganization = useMutation(
api.organizations.ensurePersonalOrganization
@@ -25,7 +27,7 @@ export const usePersonalOrganization = (): PersonalOrganizationState => {
}>();
useEffect(() => {
if (!userId) {
if (!convexReady || !userId) {
return;
}
@@ -57,9 +59,9 @@ export const usePersonalOrganization = (): PersonalOrganizationState => {
return () => {
active = false;
};
}, [ensurePersonalOrganization, userId]);
}, [convexReady, ensurePersonalOrganization, userId]);
if (!userId || state?.userId !== userId) {
if (!convexReady || !userId || state?.userId !== userId) {
return {};
}

View File

@@ -1,194 +0,0 @@
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { useFlueClient } from "@flue/react";
import { useAction, useMutation, useQuery } from "convex/react";
import { useState } from "react";
import {
buildProjectLoopView,
summarizeProjectIssues,
} from "@/lib/projects/project-evidence";
const errorMessage = (error: unknown) =>
error instanceof Error ? error.message : String(error);
export const useProjectWorkspace = () => {
const flueClient = useFlueClient();
const projects = useQuery(api.projects.list);
const [selectedProjectId, setSelectedProjectId] =
useState<Id<"projects"> | null>(null);
const [repository, setRepository] = useState("");
const [issueTitle, setIssueTitle] = useState("");
const [issueBody, setIssueBody] = useState("");
const [selectedIssueId, setSelectedIssueId] =
useState<Id<"projectIssues"> | null>(null);
const [pendingAction, setPendingAction] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const importPublicGit = useAction(api.projects.importPublicGit);
const createIssue = useMutation(api.projectIssues.create);
const createIssueFromSignal = useMutation(api.projectIssues.createFromSignal);
const beginIssue = useMutation(api.projectIssues.begin);
const markDispatchFailed = useMutation(api.projectIssues.markDispatchFailed);
const activeProjectId =
selectedProjectId ??
(projects?.[0]?.id as unknown as Id<"projects">) ??
null;
const artifacts = useQuery(
api.projectArtifacts.list,
activeProjectId ? { projectId: activeProjectId } : "skip"
);
const issues = useQuery(
api.projectIssues.list,
activeProjectId ? { projectId: activeProjectId } : "skip"
);
const events = useQuery(
api.projectIssues.events,
activeProjectId ? { projectId: activeProjectId } : "skip"
);
const pullRequest = events
?.map((event) => event.data)
.find(
(
data
): data is {
pullRequest: {
baseBranch: string;
branch: string;
number: number;
status: "open" | "closed" | "merged";
url: string;
};
} =>
typeof data === "object" &&
data !== null &&
"pullRequest" in data &&
typeof data.pullRequest === "object" &&
data.pullRequest !== null
)?.pullRequest;
const connectRepository = async () => {
setPendingAction("connect");
setError(null);
try {
const outcome = await importPublicGit({ repositoryUrl: repository });
setSelectedProjectId(outcome.id as unknown as Id<"projects">);
setRepository("");
} catch (caughtError) {
setError(errorMessage(caughtError));
} finally {
setPendingAction(null);
}
};
const raiseIssue = async (input?: {
readonly body?: string;
readonly title?: string;
}) => {
if (!activeProjectId) {
return;
}
const nextTitle = input?.title ?? issueTitle;
const nextBody = input?.body ?? issueBody;
setPendingAction("issue");
setError(null);
try {
const issueId = await createIssue({
body: nextBody,
projectId: activeProjectId,
title: nextTitle,
});
setSelectedIssueId(issueId);
setIssueTitle("");
setIssueBody("");
} catch (caughtError) {
setError(errorMessage(caughtError));
} finally {
setPendingAction(null);
}
};
const raiseIssueFromSignal = async (signalId: Id<"signals">) => {
setPendingAction(`signal:${signalId}`);
setError(null);
try {
const outcome = await createIssueFromSignal({ signalId });
setSelectedIssueId(outcome.issueId);
} catch (caughtError) {
setError(errorMessage(caughtError));
} finally {
setPendingAction(null);
}
};
const startIssue = async (
issueId: Id<"projectIssues">,
issueNumber: number,
title: string
) => {
const actionKey = `issue:${issueId}`;
setPendingAction(actionKey);
setError(null);
try {
await beginIssue({ issueId });
await flueClient.agents.send("project-manager", String(issueId), {
message: `Start project issue ${issueNumber}: ${title}. Read the bound context and complete the workflow.`,
});
} catch (caughtError) {
const message = errorMessage(caughtError);
await markDispatchFailed({ error: message, issueId });
setError(message);
} finally {
setPendingAction(null);
}
};
const startWorkUnit = async (issueId: Id<"projectIssues">) => {
const issue = issues?.find((candidate) => candidate._id === issueId);
if (!issue) {
setError("That work unit is no longer available");
return;
}
await startIssue(issue._id, issue.number, issue.title);
};
const selectedProject =
projects?.find(
(project) => project.id === (activeProjectId as unknown as string)
) ?? null;
const selectedIssue =
issues?.find((issue) => issue._id === selectedIssueId) ?? issues?.[0];
const projectLoop = buildProjectLoopView({
artifacts,
issue: selectedIssue,
source: selectedProject?.sources[0],
});
const issueSummary = summarizeProjectIssues(issues);
return {
artifacts,
connectRepository,
error,
events,
issueBody,
issueSummary,
issueTitle,
issues,
pendingAction,
projectLoop,
projects,
pullRequest,
raiseIssue,
raiseIssueFromSignal,
repository,
selectedIssue,
selectedIssueId,
selectedProject,
selectedProjectId: activeProjectId,
setIssueBody,
setIssueTitle,
setRepository,
setSelectedIssueId,
setSelectedProjectId,
startIssue,
startWorkUnit,
} as const;
};

View File

@@ -75,6 +75,19 @@ html.slice-one-viewport-lock body {
min-height: 1.75rem;
}
.route-progress-bar {
animation: route-progress 900ms ease-in-out infinite;
}
@keyframes route-progress {
from {
transform: translateX(-100%);
}
to {
transform: translateX(400%);
}
}
@keyframes response-dot {
0%,
60%,

View File

@@ -0,0 +1,64 @@
import { env } from "@code/env/web";
import { redirect } from "react-router";
interface AuthLoaderData {
readonly token: string | null;
}
const tokenUrl = new URL("/api/auth/convex/token", env.VITE_AUTH_URL);
export const loadAuthToken = async (
request: Request
): Promise<AuthLoaderData> => {
const cookie = request.headers.get("cookie");
if (!cookie) {
return { token: null };
}
const headers = new Headers({ cookie });
headers.set("host", tokenUrl.host);
const response = await fetch(tokenUrl, { headers });
if (response.status === 401) {
return { token: null };
}
if (!response.ok) {
throw new Response("Authentication service unavailable", { status: 503 });
}
const payload: unknown = await response.json();
if (
typeof payload !== "object" ||
payload === null ||
!("token" in payload) ||
typeof payload.token !== "string"
) {
throw new Response("Authentication service returned an invalid response", {
status: 502,
});
}
return { token: payload.token };
};
export const requireAuthToken = async (
request: Request
): Promise<AuthLoaderData> => {
const auth = await loadAuthToken(request);
if (!auth.token) {
const requestUrl = new URL(request.url);
const returnTo = `${requestUrl.pathname}${requestUrl.search}`;
throw redirect(`/login?returnTo=${encodeURIComponent(returnTo)}`);
}
return auth;
};
export const redirectAuthenticated = async (
request: Request
): Promise<AuthLoaderData> => {
const auth = await loadAuthToken(request);
if (auth.token) {
const requestUrl = new URL(request.url);
const returnTo = requestUrl.searchParams.get("returnTo");
throw redirect(returnTo?.startsWith("/") ? returnTo : "/");
}
return auth;
};

View File

@@ -1,10 +1,6 @@
import { describe, expect, test } from "vitest";
import {
MAX_CHAT_IMAGE_BYTES,
bytesToBase64,
validateChatImage,
} from "./attachments";
import { MAX_CHAT_IMAGE_BYTES, validateChatImage } from "./attachments";
describe("chat image attachments", () => {
test("accepts supported image payloads within the upload limit", () => {
@@ -24,8 +20,4 @@ describe("chat image attachments", () => {
}).accepted
).toBe(false);
});
test("encodes image bytes for the Flue prompt contract", () => {
expect(bytesToBase64(new Uint8Array([90, 111, 112, 117]))).toBe("Wm9wdQ==");
});
});

View File

@@ -1,5 +1,3 @@
import type { AgentPromptImage } from "@flue/react";
export const MAX_CHAT_IMAGES = 4;
export const MAX_CHAT_IMAGE_BYTES = 10 * 1024 * 1024;
@@ -28,20 +26,3 @@ export const validateChatImage = (
}
return { accepted: true };
};
export const bytesToBase64 = (bytes: Uint8Array): string => {
let binary = "";
for (const byte of bytes) {
binary += String.fromCodePoint(byte);
}
return btoa(binary);
};
export const chatImageToPromptImage = async (
image: PendingChatImage
): Promise<AgentPromptImage> => ({
data: bytesToBase64(new Uint8Array(await image.file.arrayBuffer())),
filename: image.file.name,
mimeType: image.file.type,
type: "image",
});

View File

@@ -1,24 +1,13 @@
import type { AgentStatus } from "@flue/react";
import type { AgentStatus } from "./types";
/**
* The global Zopu agent. The instance `id` is the current organization id
* (resolved at runtime by the chat hook), not the legacy `main` shared
* instance. Organization scoping is the hard tenancy boundary.
*/
export const CHAT_AGENT = {
live: "sse",
name: "zopu",
} as const;
export const MODEL_ID = "openrouter/openai/gpt-oss-20b:free";
export const MODEL_LABEL = "GPT-OSS 20B Free";
export const SUGGESTIONS = [
["Think it through", "Help me make a difficult decision"],
["Make a plan", "Turn an idea into clear next steps"],
["Explain simply", "Break down something complex"],
] as const;
export const STATUS_COPY: Record<AgentStatus, string> = {
connecting: "Connecting",
error: "Connection issue",

View File

@@ -0,0 +1,44 @@
import { describe, expect, test } from "vitest";
import type { ConversationRow } from "./conversation";
import { projectConversation } from "./conversation";
const row = (
overrides: Partial<ConversationRow> &
Pick<ConversationRow, "messageId" | "role" | "status">
): ConversationRow => ({
attachments: [],
error: null,
rawText: "",
...overrides,
});
describe("projectConversation", () => {
test("keeps queued assistant rows as status instead of duplicate messages", () => {
const state = projectConversation([
row({
messageId: "user-1",
rawText: "Build it",
role: "user",
status: "processing",
}),
row({ messageId: "assistant-1", role: "assistant", status: "queued" }),
]);
expect(state.pending).toBe(true);
expect(state.messages).toHaveLength(1);
});
test("projects completed Convex rows into renderable messages", () => {
const state = projectConversation([
row({
messageId: "assistant-1",
rawText: "Captured the request.",
role: "assistant",
status: "completed",
}),
]);
expect(state.messages[0]?.parts).toEqual([
{ state: "done", text: "Captured the request.", type: "text" },
]);
});
});

View File

@@ -0,0 +1,50 @@
import type { ConversationMessage } from "./types";
export interface ConversationRow {
readonly attachments: readonly {
readonly filename: string | null;
readonly id: string;
readonly mediaType: string;
readonly url: string | null;
}[];
readonly error: string | null;
readonly messageId: string;
readonly rawText: string;
readonly role: "assistant" | "user";
readonly status: "completed" | "failed" | "processing" | "queued";
}
export const projectConversation = (rows: readonly ConversationRow[]) => ({
failedError: rows.findLast(
(row) => row.role === "assistant" && row.status === "failed"
)?.error,
messages: rows
.filter((row) => row.role === "user" || row.status === "completed")
.map<ConversationMessage>((row) => ({
id: row.messageId,
parts: [
...row.attachments.map((attachment) => ({
filename: attachment.filename ?? undefined,
id: attachment.id,
mediaType: attachment.mediaType,
type: "file" as const,
url: attachment.url ?? undefined,
})),
...(row.rawText
? [
{
state: "done" as const,
text: row.rawText,
type: "text" as const,
},
]
: []),
],
role: row.role,
})),
pending: rows.some(
(row) =>
row.role === "assistant" &&
(row.status === "queued" || row.status === "processing")
),
});

View File

@@ -1,53 +1,18 @@
import type { FlueConversationMessage } from "@flue/react";
import { describe, expect, test } from "vitest";
import {
extractThinkingMarkup,
getReasoningText,
hasToolActivity,
isReasoningStreaming,
} from "./transforms";
import type { ConversationMessage } from "./types";
const message = (
parts: FlueConversationMessage["parts"]
): FlueConversationMessage => ({
const message = (parts: ConversationMessage["parts"]): ConversationMessage => ({
id: "message-1",
parts,
role: "assistant",
});
describe("hasToolActivity", () => {
test("detects an orchestration turn", () => {
expect(
hasToolActivity(
message([
{
input: { projectId: "project-1" },
state: "input-available",
toolCallId: "tool-1",
toolName: "list_proposed_work",
type: "dynamic-tool",
},
])
)
).toBe(true);
});
test("keeps a product-facing assistant response", () => {
expect(
hasToolActivity(
message([
{
state: "done",
text: "Captured the signal and proposed Work.",
type: "text",
},
])
)
).toBe(false);
});
});
describe("reasoning traces", () => {
test("extracts completed and streaming MiniMax think blocks", () => {
expect(

View File

@@ -1,4 +1,4 @@
import type { AgentStatus, FlueConversationMessage } from "@flue/react";
import type { AgentStatus, ConversationMessage } from "./types";
export const stripThinkingMarkup = (text: string): string => {
const withoutCompletedBlocks = text.replaceAll(
@@ -33,16 +33,16 @@ export const extractThinkingMarkup = (text: string): string => {
return completed.join("\n\n");
};
export const getRawMessageText = (message: FlueConversationMessage): string =>
export const getRawMessageText = (message: ConversationMessage): string =>
message.parts
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
export const getMessageText = (message: FlueConversationMessage): string =>
export const getMessageText = (message: ConversationMessage): string =>
stripThinkingMarkup(getRawMessageText(message));
export const getReasoningText = (message: FlueConversationMessage): string => {
export const getReasoningText = (message: ConversationMessage): string => {
const nativeReasoning = message.parts
.filter((part) => part.type === "reasoning")
.map((part) => part.text)
@@ -51,9 +51,7 @@ export const getReasoningText = (message: FlueConversationMessage): string => {
return [nativeReasoning, inlineReasoning].filter(Boolean).join("\n\n");
};
export const isReasoningStreaming = (
message: FlueConversationMessage
): boolean => {
export const isReasoningStreaming = (message: ConversationMessage): boolean => {
const nativeReasoningStreaming = message.parts.some(
(part) => part.type === "reasoning" && part.state === "streaming"
);
@@ -66,19 +64,12 @@ export const isReasoningStreaming = (
return nativeReasoningStreaming || inlineReasoningStreaming;
};
export const hasToolActivity = (message: FlueConversationMessage): boolean =>
message.parts.some((part) => part.type === "dynamic-tool");
export const isMessageStreaming = (message: FlueConversationMessage): boolean =>
message.parts.some((part) => {
if (part.type === "dynamic-tool") {
return part.state === "input-available";
}
return (
export const isMessageStreaming = (message: ConversationMessage): boolean =>
message.parts.some(
(part) =>
(part.type === "text" || part.type === "reasoning") &&
part.state === "streaming"
);
});
);
export const getStatusDotClass = (status: AgentStatus): string => {
if (status === "error") {

View File

@@ -1,17 +1,42 @@
import type {
AgentPromptImage,
AgentStatus,
FlueConversationMessage,
FlueConversationPart,
} from "@flue/react";
export type AgentStatus =
| "connecting"
| "error"
| "idle"
| "streaming"
| "submitted";
export type ConversationPart =
| {
readonly state: "done" | "streaming";
readonly text: string;
readonly type: "text";
}
| {
readonly state: "done" | "streaming";
readonly text: string;
readonly type: "reasoning";
}
| {
readonly filename?: string;
readonly id?: string;
readonly mediaType: string;
readonly type: "file";
readonly url?: string;
};
export interface ConversationMessage {
readonly id: string;
readonly parts: ConversationPart[];
readonly role: "assistant" | "user";
}
export interface ChatAgentState {
error?: Error;
historyReady: boolean;
messages: FlueConversationMessage[];
messages: ConversationMessage[];
sendMessage: (
message: string,
options?: { readonly images?: AgentPromptImage[] }
options?: { readonly images?: readonly File[] }
) => Promise<void>;
status: AgentStatus;
}
@@ -24,7 +49,7 @@ export interface ChatComposerProps {
export interface ChatConversationProps {
historyReady: boolean;
messages: FlueConversationMessage[];
messages: ConversationMessage[];
onSuggestion: (suggestion: string) => void;
status: AgentStatus;
}
@@ -34,12 +59,7 @@ export interface ChatHeaderProps {
}
export interface ChatMessageProps {
hideToolActivity?: boolean;
message: FlueConversationMessage;
}
export interface ChatToolCallProps {
part: Extract<FlueConversationPart, { type: "dynamic-tool" }>;
message: ConversationMessage;
}
export type AssistantResponseState = "thinking" | "writing";

View File

@@ -1,152 +0,0 @@
import { createFlueClient } from "@flue/sdk";
import { describe, expect, test } from "vitest";
import { createFlueFetch, generateBrowserRequestId } from "./flue-transport";
const BASE_URL = new URL("https://flue.example/api/");
const GLOBAL_RECEIVER_FETCH = function globalReceiverFetch(this: unknown) {
if (this !== globalThis) {
throw new TypeError("fetch receiver must be globalThis");
}
return Promise.resolve(new Response(null, { status: 204 }));
} as typeof fetch;
describe("createFlueFetch", () => {
test("overlapping SDK agent sends keep distinct request IDs", async () => {
const firstResponse = Promise.withResolvers<Response>();
const secondResponse = Promise.withResolvers<Response>();
const bothStarted = Promise.withResolvers<boolean>();
const capturedHeaders: Headers[] = [];
let requestCount = 0;
let requestId = 0;
const fetchImpl: typeof fetch = (input, init) => {
capturedHeaders.push(new Headers(init?.headers));
requestCount += 1;
if (requestCount === 2) {
bothStarted.resolve(true);
}
if (requestCount === 1) {
return firstResponse.promise;
}
if (requestCount === 2) {
return secondResponse.promise;
}
throw new Error(`Unexpected request: ${String(input)}`);
};
const client = createFlueClient({
baseUrl: BASE_URL.toString(),
fetch: createFlueFetch({
baseUrl: BASE_URL,
fetchImpl,
generateRequestId: () => `request-${(requestId += 1)}`,
}),
headers: { authorization: "Bearer current-jwt" },
});
const firstSend = client.agents.send("zopu", "org-a", {
message: "first",
});
const secondSend = client.agents.send("zopu", "org-a", {
message: "second",
});
await bothStarted.promise;
expect(capturedHeaders).toHaveLength(2);
expect(capturedHeaders[0]?.get("x-zopu-request-id")).toBe("request-1");
expect(capturedHeaders[1]?.get("x-zopu-request-id")).toBe("request-2");
expect(capturedHeaders[0]?.get("authorization")).toBe("Bearer current-jwt");
expect(capturedHeaders[1]?.get("authorization")).toBe("Bearer current-jwt");
firstResponse.resolve(
Response.json(
{
offset: "1",
streamUrl: "http://internal/streams/first",
submissionId: "submission-1",
},
{ status: 202 }
)
);
secondResponse.resolve(
Response.json(
{
offset: "2",
streamUrl: "http://internal/streams/second",
submissionId: "submission-2",
},
{ status: 202 }
)
);
await expect(Promise.all([firstSend, secondSend])).resolves.toEqual([
{
offset: "1",
streamUrl: "https://flue.example/streams/first",
submissionId: "submission-1",
},
{
offset: "2",
streamUrl: "https://flue.example/streams/second",
submissionId: "submission-2",
},
]);
});
test("invokes fetch with the browser global receiver", async () => {
await expect(
createFlueFetch({ baseUrl: BASE_URL, fetchImpl: GLOBAL_RECEIVER_FETCH })(
"https://flue.example/api/agents/zopu/org-a?view=history"
)
).resolves.toBeInstanceOf(Response);
});
test("uses the default browser request ID generator without losing its receiver", async () => {
const capturedHeaders: Headers[] = [];
const fetchImpl: typeof fetch = (_input, init) => {
capturedHeaders.push(new Headers(init?.headers));
return Promise.resolve(new Response(null, { status: 204 }));
};
await createFlueFetch({ baseUrl: BASE_URL, fetchImpl })(
"https://flue.example/api/agents/zopu/org-a",
{ method: "POST" }
);
expect(capturedHeaders[0]?.get("x-zopu-request-id")).toMatch(
/^[0-9a-f-]{36}$/u
);
});
test("generates a UUID without requiring crypto.randomUUID", () => {
expect(generateBrowserRequestId()).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
);
});
test("history and stream observation requests remain untagged", async () => {
const capturedHeaders: Headers[] = [];
const fetchImpl: typeof fetch = (_input, init) => {
capturedHeaders.push(new Headers(init?.headers));
return Promise.resolve(new Response(null, { status: 204 }));
};
const flueFetch = createFlueFetch({
baseUrl: BASE_URL,
fetchImpl,
generateRequestId: () => "must-not-be-used",
});
await flueFetch("https://flue.example/api/agents/zopu/org-a?view=history", {
headers: { authorization: "Bearer current-jwt" },
method: "GET",
});
await flueFetch("https://flue.example/api/agents/zopu/org-a?view=updates", {
headers: { authorization: "Bearer current-jwt" },
method: "GET",
});
expect(capturedHeaders).toHaveLength(2);
expect(capturedHeaders[0]?.has("x-zopu-request-id")).toBe(false);
expect(capturedHeaders[1]?.has("x-zopu-request-id")).toBe(false);
});
});

View File

@@ -1,120 +0,0 @@
interface FlueFetchOptions {
readonly baseUrl: URL;
readonly fetchImpl?: typeof fetch;
readonly generateRequestId?: () => string;
}
export const generateBrowserRequestId = (): string => {
const bytes = new Uint8Array(16);
if (globalThis.crypto?.getRandomValues) {
globalThis.crypto.getRandomValues(bytes);
} else {
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Math.floor(Math.random() * 256);
}
}
bytes[6] = ((bytes[6] ?? 0) % 16) + 64;
bytes[8] = ((bytes[8] ?? 0) % 64) + 128;
const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
};
const addRequestContext = async (
response: Response,
method: string,
requestUrl: URL
): Promise<Response> => {
if (response.ok) {
return response;
}
const responseClone = response.clone();
const responseText = await responseClone.text();
const detail = responseText.trim() || "request failed";
return Response.json(
{
error: {
message: `${method} ${requestUrl.pathname}${requestUrl.search}: ${detail}`,
},
},
{
headers: response.headers,
status: response.status,
statusText: response.statusText,
}
);
};
/**
* Build the Flue transport used by the browser client.
*
* The installed Flue SDK does not expose per-call headers on `agents.send`.
* Its custom `fetch` seam does receive the resolved URL and method, so request
* IDs are attached here to each agent admission POST. History and Durable
* Streams observation requests are GETs and intentionally remain untagged.
*/
export const createFlueFetch = ({
baseUrl,
fetchImpl = fetch,
generateRequestId = generateBrowserRequestId,
}: FlueFetchOptions): typeof fetch => {
const basePath = baseUrl.pathname.replace(/\/+$/u, "");
return async (input, init) => {
const inputUrl =
typeof input === "string" || input instanceof URL ? input : input.url;
const requestUrl = new URL(inputUrl, baseUrl);
const method = (
init?.method ?? (input instanceof Request ? input.method : "GET")
).toUpperCase();
const relativePath = requestUrl.pathname.startsWith(`${basePath}/`)
? requestUrl.pathname.slice(basePath.length)
: requestUrl.pathname;
const pathSegments = relativePath.split("/").filter(Boolean);
const isAgentAdmission =
method === "POST" &&
pathSegments.length === 3 &&
pathSegments[0] === "agents";
let requestInit = init;
if (isAgentAdmission) {
const headers = new Headers(
input instanceof Request ? input.headers : undefined
);
for (const [key, value] of new Headers(init?.headers).entries()) {
headers.set(key, value);
}
headers.set("x-zopu-request-id", generateRequestId());
requestInit = { ...init, headers };
}
const rawResponse = await fetchImpl.call(globalThis, input, requestInit);
const response = await addRequestContext(rawResponse, method, requestUrl);
if (!response.headers.get("content-type")?.includes("application/json")) {
return response;
}
const body = (await response.clone().json()) as unknown;
if (
typeof body !== "object" ||
body === null ||
!("streamUrl" in body) ||
typeof body.streamUrl !== "string"
) {
return response;
}
const streamUrl = new URL(body.streamUrl);
streamUrl.protocol = baseUrl.protocol;
streamUrl.host = baseUrl.host;
const headers = new Headers(response.headers);
headers.set("location", streamUrl.toString());
return Response.json(
{ ...body, streamUrl: streamUrl.toString() },
{
headers,
status: response.status,
statusText: response.statusText,
}
);
};
};

View File

@@ -1,191 +0,0 @@
import type { api } from "@code/backend/convex/_generated/api";
import type { Doc } from "@code/backend/convex/_generated/dataModel";
import {
getProjectWorkNextAction,
getProjectWorkProgress,
getProjectWorkStatus,
} from "@code/primitives/project-work";
import type {
MobileAssistantView,
MobileProjectView,
MobileSignalView,
MobileWorkspaceView,
MobileWorkUnitTone,
MobileWorkUnitView,
} from "@code/ui/components/mobile-product";
import type { FunctionReturnType } from "convex/server";
type SignalList = FunctionReturnType<typeof api.signals.list>;
type ProjectEventList = FunctionReturnType<typeof api.projectIssues.events>;
type ProjectView = FunctionReturnType<typeof api.projects.list>[number];
interface BuildMobileWorkspaceViewInput {
readonly artifacts: readonly Doc<"projectArtifacts">[] | undefined;
readonly assistant: MobileAssistantView;
readonly events: ProjectEventList | undefined;
readonly issues: readonly Doc<"projectIssues">[] | undefined;
readonly organizationLabel?: string;
readonly projects: readonly ProjectView[] | undefined;
readonly selectedProject: ProjectView | null;
readonly selectedWorkUnitId?: string;
readonly signals: SignalList | undefined;
}
const updatedDateFormatter = new Intl.DateTimeFormat("en", {
day: "numeric",
month: "short",
});
const statusTone = (
status: ReturnType<typeof getProjectWorkStatus>
): MobileWorkUnitTone => {
if (status.phase === "completed") {
return "green";
}
if (status.phase === "failed" || status.phase === "waiting") {
return "orange";
}
if (status.phase === "captured") {
return "purple";
}
return "blue";
};
const isPullRequestData = (
value: unknown
): value is {
pullRequest: {
number: number;
status: "open" | "closed" | "merged";
url: string;
};
} =>
typeof value === "object" &&
value !== null &&
"pullRequest" in value &&
typeof value.pullRequest === "object" &&
value.pullRequest !== null &&
"number" in value.pullRequest &&
typeof value.pullRequest.number === "number" &&
"url" in value.pullRequest &&
typeof value.pullRequest.url === "string";
const toWorkUnit = (
issue: Doc<"projectIssues">,
artifactCount: number,
events: ProjectEventList | undefined
): MobileWorkUnitView => {
const status = getProjectWorkStatus(issue.status);
const pullRequest = events
?.filter((event) => event.issueId === issue._id)
.map((event) => event.data)
.find(isPullRequestData)?.pullRequest;
return {
artifactCount,
canRetry: status.phase === "failed" || status.phase === "waiting",
canStart: status.phase === "captured",
code: `#${issue.number}`,
id: issue._id,
nextAction: getProjectWorkNextAction(issue.status),
progress: getProjectWorkProgress(issue.status),
pullRequestNumber: pullRequest?.number,
reviewUrl: pullRequest?.url,
statusLabel: status.label,
summary: issue.body,
title: issue.title,
tone: statusTone(status),
updatedLabel: updatedDateFormatter.format(issue.updatedAt),
};
};
const toLatestSignalView = (
signal: SignalList[number]["signal"] | undefined
): MobileSignalView | undefined => {
if (!signal) {
return;
}
return {
desiredOutcome: signal.problemStatement.desiredOutcome,
id: signal._id,
projectId: signal.projectId ?? undefined,
summary: signal.problemStatement.summary,
title: signal.problemStatement.title,
};
};
const relevantSignalsForProject = (
signals: SignalList | undefined,
projectId: ProjectView["id"] | undefined
) =>
signals?.filter(
({ signal }) =>
!signal.projectId || String(signal.projectId) === String(projectId)
) ?? [];
const makeProjectViews = (
projects: readonly ProjectView[] | undefined
): readonly MobileProjectView[] =>
projects?.map((project) => {
const [source] = project.sources;
return {
connected: Boolean(source),
host: source?.host,
id: project.id,
name: project.name,
repositoryPath: source?.repositoryPath,
};
}) ?? [];
export const buildMobileWorkspaceView = ({
artifacts,
assistant,
events,
issues,
organizationLabel = "Personal workspace",
projects,
selectedProject,
selectedWorkUnitId,
signals,
}: BuildMobileWorkspaceViewInput): MobileWorkspaceView => {
const artifactCount = artifacts?.length ?? 0;
const workUnits =
issues?.map((issue) => toWorkUnit(issue, artifactCount, events)) ?? [];
const selectedWorkUnit =
workUnits.find((workUnit) => workUnit.id === selectedWorkUnitId) ??
workUnits.find((workUnit) => workUnit.tone === "blue") ??
workUnits[0];
const selectedProjectId = selectedProject?.id;
const relevantSignals = relevantSignalsForProject(signals, selectedProjectId);
const latestSignal = relevantSignals[0]?.signal;
const activeCount = workUnits.filter(
(workUnit) => workUnit.progress < 100
).length;
const needsAttentionCount = issues?.filter(
(issue) => issue.status === "failed" || issue.status === "needs-input"
).length;
const shippedCount = issues?.filter(
(issue) => issue.status === "completed"
).length;
const hasSelectedProject = Boolean(selectedProject);
const projectViews = makeProjectViews(projects);
return {
activeCount,
activityCount: workUnits.length + relevantSignals.length,
artifactCount,
assistant,
isLoading:
projects === undefined ||
(hasSelectedProject && (artifacts === undefined || issues === undefined)),
latestSignal: toLatestSignalView(latestSignal),
needsAttentionCount: needsAttentionCount ?? 0,
organizationLabel,
projectName: selectedProject?.name,
projects: projectViews,
selectedProjectId: selectedProject?.id,
selectedWorkUnit,
shippedCount: shippedCount ?? 0,
totalCount: workUnits.length,
workUnits,
};
};

View File

@@ -1,23 +0,0 @@
import { describe, expect, it } from "vitest";
import { getMobileStatusMessage } from "./mobile-status-message";
describe("getMobileStatusMessage", () => {
it("keeps local composer feedback", () => {
expect(
getMobileStatusMessage({
assistantError: "Flue API error 401",
localStatus: "Sent to Zopu",
})
).toBe("Sent to Zopu");
});
it("does not expose Flue authorization internals", () => {
expect(
getMobileStatusMessage({
assistantError:
'Flue API error 401: GET /agents/zopu/example: {"error":"Unauthorized"}',
})
).toBe("Zopu is reconnecting…");
});
});

View File

@@ -1,25 +0,0 @@
interface MobileStatusMessageInput {
readonly assistantError?: string;
readonly localStatus?: string;
}
const isAgentAuthorizationError = (message: string) =>
message.includes("Flue API error 401") ||
message.includes('"Unauthorized"') ||
message.includes("GET /agents/");
export const getMobileStatusMessage = ({
assistantError,
localStatus,
}: MobileStatusMessageInput): string | undefined => {
if (localStatus) {
return localStatus;
}
if (!assistantError) {
return undefined;
}
if (isAgentAuthorizationError(assistantError)) {
return "Zopu is reconnecting…";
}
return "Zopu needs attention";
};

View File

@@ -1,91 +0,0 @@
import type { Doc, Id } from "@code/backend/convex/_generated/dataModel";
import { describe, expect, test } from "vitest";
import {
buildProjectLoopView,
summarizeProjectIssues,
} from "./project-evidence";
const makeIssue = (
status: Doc<"projectIssues">["status"],
issueId: Id<"projectIssues"> = "issue-1" as Id<"projectIssues">
): Doc<"projectIssues"> =>
({
_creationTime: 1,
_id: issueId,
body: "Make the project loop visible in the web app.",
createdAt: 1000,
number: 8,
projectId: "project-1",
status,
title: "Build project loop UI",
updatedAt: 2000,
}) as Doc<"projectIssues">;
const makeArtifact = (content: string): Doc<"projectArtifacts"> =>
({
_creationTime: 1,
_id: "artifact-1",
content,
createdAt: 1000,
path: "artifacts.md",
projectId: "project-1",
revision: 2,
updatedAt: 2000,
}) as Doc<"projectArtifacts">;
describe("project evidence", () => {
test("turns published PR evidence into a review action", () => {
const view = buildProjectLoopView({
artifacts: [
makeArtifact(
"Verification: 14 unit tests passed.\nPull request: PR #42"
),
],
issue: makeIssue("completed"),
source: {
host: "git.example.com",
repositoryPath: "puter/zopu",
url: "https://git.example.com/puter/zopu",
},
});
expect(view?.progress).toBe(100);
expect(view?.verification).toBe("passed");
expect(view?.pullRequest.reviewUrl).toBe(
"https://git.example.com/puter/zopu/pulls/42"
);
expect(view?.verificationNote).toContain(
"Verification: 14 unit tests passed."
);
});
test("keeps the review slot pending when no PR is published", () => {
const view = buildProjectLoopView({
artifacts: [
makeArtifact("The run is recording implementation evidence."),
],
issue: makeIssue("working"),
source: undefined,
});
expect(view?.verification).toBe("running");
expect(view?.pullRequest.state).toBe("pending");
expect(view?.pullRequest.reviewUrl).toBeUndefined();
});
test("summarizes the project queue without inventing work", () => {
const summary = summarizeProjectIssues([
makeIssue("working"),
makeIssue("needs-input", "issue-2" as Id<"projectIssues">),
makeIssue("completed", "issue-3" as Id<"projectIssues">),
]);
expect(summary).toEqual({
active: 2,
completed: 1,
needsInput: 1,
total: 3,
});
});
});

View File

@@ -1,315 +0,0 @@
import type { Doc } from "@code/backend/convex/_generated/dataModel";
import type { ProjectIssueStatus } from "@code/primitives/project-issue";
import {
getProjectWorkNextAction,
getProjectWorkProgress,
getProjectWorkStatus,
} from "@code/primitives/project-work";
import type { ProjectVerificationStatus } from "@code/primitives/project-work";
type ProjectIssue = Doc<"projectIssues">;
type ProjectArtifact = Doc<"projectArtifacts">;
export interface ProjectSourceSummary {
readonly host: string;
readonly repositoryPath: string;
readonly url: string;
}
export interface ProjectIssueSummary {
readonly active: number;
readonly completed: number;
readonly needsInput: number;
readonly total: number;
}
export interface ProjectVerificationCheck {
readonly detail: string;
readonly label: string;
readonly state: "attention" | "complete" | "current" | "upcoming";
}
export interface ProjectActivityItem {
readonly detail: string;
readonly label: string;
readonly time: string;
}
export interface ProjectPullRequest {
readonly number: number | undefined;
readonly reviewUrl: string | undefined;
readonly state: "available" | "pending";
}
export interface ProjectLoopView {
readonly activity: readonly ProjectActivityItem[];
readonly currentState: string;
readonly nextAction: string;
readonly progress: number;
readonly pullRequest: ProjectPullRequest;
readonly status: ReturnType<typeof getProjectWorkStatus>;
readonly verification: ProjectVerificationStatus;
readonly verificationChecks: readonly ProjectVerificationCheck[];
readonly verificationNote: string;
}
const STATUS_TEXT: Readonly<Record<ProjectIssueStatus, string>> = {
completed:
"Implementation and verification are complete. Review the resulting change.",
failed:
"The run stopped with its workspace preserved. Review the failure and retry when ready.",
"needs-input":
"The run is paused until a project decision or missing piece is resolved.",
open: "The issue is ready to start. Zopu will keep the project context attached to the run.",
queued: "The issue is queued for the project manager to pick up.",
working:
"The project manager is working through the issue and recording durable evidence.",
};
const formatTime = (timestamp: number): string =>
new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(timestamp);
const relativeTime = (timestamp: number): string => {
const minutes = Math.max(0, Math.round((Date.now() - timestamp) / 60_000));
if (minutes < 1) {
return "just now";
}
if (minutes < 60) {
return `${minutes}m ago`;
}
const hours = Math.round(minutes / 60);
if (hours < 24) {
return `${hours}h ago`;
}
return `${Math.round(hours / 24)}d ago`;
};
const allArtifactText = (artifacts: readonly ProjectArtifact[]): string =>
artifacts.map((artifact) => artifact.content).join("\n");
const extractPullRequest = (
artifacts: readonly ProjectArtifact[],
source: ProjectSourceSummary | undefined
): ProjectPullRequest => {
const text = allArtifactText(artifacts);
const urlMatch = text.match(/https?:\/\/[^\s)]+\/pulls\/\d+/iu)?.[0];
const numberMatch = text.match(/\bPR\s*#(?<number>\d+)\b/iu);
const numberValue = numberMatch?.groups?.number;
const number = numberValue ? Number(numberValue) : undefined;
let reviewUrl = urlMatch;
if (!reviewUrl && number && source) {
reviewUrl = `${source.url.replace(/\/$/u, "")}/pulls/${number}`;
}
return {
number,
reviewUrl,
state: reviewUrl ? "available" : "pending",
};
};
const extractVerificationNote = (
artifacts: readonly ProjectArtifact[],
status: ProjectIssueStatus
): string => {
const evidenceLine = allArtifactText(artifacts)
.split("\n")
.map((line) => line.trim())
.find((line) => /verification|tests?|browser|passed|failed/iu.test(line));
if (evidenceLine) {
return evidenceLine.replace(/^[-*#\s]+/u, "").slice(0, 140);
}
if (status === "completed") {
return "The agent reported completion after its verification step.";
}
if (status === "failed") {
return "Verification did not complete successfully.";
}
if (status === "working") {
return "Verification will appear here as the run records evidence.";
}
return "No verification evidence has been recorded yet.";
};
const makeRunCheck = (status: ProjectIssueStatus): ProjectVerificationCheck => {
if (status === "queued") {
return {
detail: "Agent admission is queued",
label: "Agent run",
state: "current",
};
}
if (status === "open") {
return {
detail: "Start the issue to create a run",
label: "Agent run",
state: "upcoming",
};
}
return {
detail: "Project manager run is attached",
label: "Agent run",
state: "complete",
};
};
const makeVerificationCheck = (
verification: ProjectVerificationStatus
): ProjectVerificationCheck => {
if (verification === "passed") {
return {
detail: "Verification passed",
label: "Verification",
state: "complete",
};
}
if (verification === "failed") {
return {
detail: "Review the preserved failure",
label: "Verification",
state: "attention",
};
}
if (verification === "blocked") {
return {
detail: "Waiting on a project decision",
label: "Verification",
state: "attention",
};
}
if (verification === "running") {
return {
detail: "Evidence is being recorded",
label: "Verification",
state: "current",
};
}
return {
detail: "No verification result yet",
label: "Verification",
state: "upcoming",
};
};
const makeChecks = (
status: ProjectIssueStatus,
verification: ProjectVerificationStatus,
pullRequest: ProjectPullRequest
): readonly ProjectVerificationCheck[] => {
const issueCheck: ProjectVerificationCheck =
status === "open"
? {
detail: "Waiting to be started",
label: "Issue accepted",
state: "upcoming",
}
: {
detail: "Issue context is attached",
label: "Issue accepted",
state: "complete",
};
const pullRequestCheck: ProjectVerificationCheck =
pullRequest.state === "available"
? {
detail: "Ready for human review",
label: "Gitea pull request",
state: "complete",
}
: {
detail: "Appears after a verified run publishes one",
label: "Gitea pull request",
state: "upcoming",
};
return [
issueCheck,
makeRunCheck(status),
makeVerificationCheck(verification),
pullRequestCheck,
];
};
const buildActivity = (
issue: ProjectIssue,
artifacts: readonly ProjectArtifact[],
statusLabel: string
): readonly ProjectActivityItem[] => {
const artifact = [...artifacts]
.toSorted((left, right) => right.updatedAt - left.updatedAt)
.find((candidate) => candidate.path !== "work.md");
const items: ProjectActivityItem[] = [
{
detail: `Issue #${issue.number} entered the project loop`,
label: "Issue created",
time: formatTime(issue.createdAt),
},
];
if (issue.updatedAt !== issue.createdAt) {
items.unshift({
detail: `Status is now ${statusLabel.toLowerCase()}`,
label: "Work state updated",
time: relativeTime(issue.updatedAt),
});
}
if (artifact) {
items.unshift({
detail: `Durable project evidence changed in ${artifact.path}`,
label: "Evidence recorded",
time: relativeTime(artifact.updatedAt),
});
}
return items.slice(0, 3);
};
export const summarizeProjectIssues = (
issues: readonly ProjectIssue[] | undefined
): ProjectIssueSummary => {
if (!issues) {
return { active: 0, completed: 0, needsInput: 0, total: 0 };
}
return {
active: issues.filter(
(issue) => !["completed", "failed"].includes(issue.status)
).length,
completed: issues.filter((issue) => issue.status === "completed").length,
needsInput: issues.filter((issue) => issue.status === "needs-input").length,
total: issues.length,
};
};
export const buildProjectLoopView = ({
artifacts,
issue,
source,
}: {
readonly artifacts: readonly ProjectArtifact[] | undefined;
readonly issue: ProjectIssue | undefined;
readonly source: ProjectSourceSummary | undefined;
}): ProjectLoopView | null => {
if (!issue) {
return null;
}
const status = getProjectWorkStatus(issue.status);
const { verification } = status;
const resolvedArtifacts = artifacts ?? [];
const pullRequest = extractPullRequest(resolvedArtifacts, source);
return {
activity: buildActivity(issue, resolvedArtifacts, status.label),
currentState: STATUS_TEXT[issue.status],
nextAction: getProjectWorkNextAction(issue.status),
progress: getProjectWorkProgress(issue.status),
pullRequest,
status,
verification,
verificationChecks: makeChecks(issue.status, verification, pullRequest),
verificationNote: extractVerificationNote(resolvedArtifacts, issue.status),
};
};

View File

@@ -1,14 +1,15 @@
import type { WorkNotice } from "@code/primitives/work";
import type { FlueConversationMessage } from "@flue/react";
import { describe, expect, test } from "vitest";
import type { ConversationMessage } from "@/lib/chat/types";
import { buildSliceOneTimeline, findSourceMessageTarget } from "./presentation";
const textMessage = (
id: string,
role: "assistant" | "user",
text: string
): FlueConversationMessage => ({
): ConversationMessage => ({
id,
parts: [{ state: "done", text, type: "text" }],
role,
@@ -27,19 +28,6 @@ describe("Slice 1 presentation", () => {
const timeline = buildSliceOneTimeline(
[
textMessage("user-1", "user", "Build the phone flow."),
{
id: "tool-1",
parts: [
{
input: {},
state: "input-available",
toolCallId: "call-1",
toolName: "create_signal",
type: "dynamic-tool",
},
],
role: "assistant",
},
textMessage("assistant-1", "assistant", "Captured and proposed Work."),
],
[notice]

View File

@@ -1,30 +1,28 @@
import type { WorkNotice } from "@code/primitives/work";
import type { FlueConversationMessage } from "@flue/react";
import {
getMessageText,
getRawMessageText,
getReasoningText,
hasToolActivity,
} from "@/lib/chat/transforms";
import type { ConversationMessage } from "@/lib/chat/types";
export type SliceTimelineItem =
| {
readonly kind: "message";
readonly message: FlueConversationMessage;
readonly message: ConversationMessage;
}
| { readonly kind: "work"; readonly notice: WorkNotice };
export const isSliceOneVisibleMessage = (
message: FlueConversationMessage
message: ConversationMessage
): boolean =>
message.role === "user" ||
!hasToolActivity(message) ||
getMessageText(message).length > 0 ||
getReasoningText(message).length > 0;
const targetIndexForNotice = (
messages: readonly FlueConversationMessage[],
messages: readonly ConversationMessage[],
notice: WorkNotice
): number => {
const sourceIndexes = notice.sourceTexts.flatMap((sourceText) => {
@@ -40,14 +38,12 @@ const targetIndexForNotice = (
const sourceIndex = Math.max(...sourceIndexes);
const responseOffset = messages
.slice(sourceIndex + 1)
.findIndex(
(message) => message.role === "assistant" && !hasToolActivity(message)
);
.findIndex((message) => message.role === "assistant");
return responseOffset === -1 ? sourceIndex : sourceIndex + responseOffset + 1;
};
export const buildSliceOneTimeline = (
allMessages: readonly FlueConversationMessage[],
allMessages: readonly ConversationMessage[],
notices: readonly WorkNotice[]
): readonly SliceTimelineItem[] => {
const messages = allMessages.filter(isSliceOneVisibleMessage);
@@ -75,7 +71,7 @@ export const buildSliceOneTimeline = (
};
export const findSourceMessageTarget = (
messages: readonly FlueConversationMessage[],
messages: readonly ConversationMessage[],
sourceText: string
): string | undefined =>
messages.find(

View File

@@ -1,11 +1,8 @@
import { useConvexAccessToken, WebAuthProvider } from "@code/auth/web";
import { env } from "@code/env/web";
import { WebAuthProvider } from "@code/auth/web";
import { Toaster } from "@code/ui/components/sonner";
import { FlueProvider } from "@flue/react";
import "./index.css";
import { createFlueClient } from "@flue/sdk";
import { useMemo } from "react";
import { LoaderCircle } from "lucide-react";
import {
isRouteErrorResponse,
Links,
@@ -13,11 +10,14 @@ import {
Outlet,
Scripts,
ScrollRestoration,
useNavigation,
} from "react-router";
import type { Route } from "./+types/root";
import { ThemeProvider } from "./components/theme-provider";
import { createFlueFetch } from "./lib/flue-transport";
import { loadAuthToken } from "./lib/auth.server";
export const loader = ({ request }: Route.LoaderArgs) => loadAuthToken(request);
export const links: Route.LinksFunction = () => [
{ href: "https://fonts.googleapis.com", rel: "preconnect" },
@@ -32,34 +32,6 @@ export const links: Route.LinksFunction = () => [
},
];
const flueBaseUrl = new URL(env.VITE_FLUE_URL);
const flueFetch = createFlueFetch({ baseUrl: flueBaseUrl });
const AuthenticatedFlueProvider = ({
children,
}: {
children: React.ReactNode;
}) => {
const resolveAccessToken = useConvexAccessToken();
const client = useMemo(
() =>
createFlueClient({
baseUrl: flueBaseUrl.toString(),
fetch: flueFetch,
headers: async () => {
const accessToken = await resolveAccessToken();
const headers: Record<string, string> = {};
if (accessToken) {
headers.authorization = `Bearer ${accessToken}`;
}
return headers;
},
}),
[resolveAccessToken]
);
return <FlueProvider client={client}>{children}</FlueProvider>;
};
export const Layout = ({ children }: { children: React.ReactNode }) => (
<html lang="en">
<head>
@@ -79,20 +51,42 @@ export const Layout = ({ children }: { children: React.ReactNode }) => (
</html>
);
const App = () => (
<WebAuthProvider>
<AuthenticatedFlueProvider>
<ThemeProvider
attribute="class"
defaultTheme="dark"
forcedTheme="dark"
disableTransitionOnChange
storageKey="vite-ui-theme"
>
<Outlet />
<Toaster richColors />
</ThemeProvider>
</AuthenticatedFlueProvider>
const RouteProgress = () => {
const navigation = useNavigation();
if (!navigation.location) {
return null;
}
return (
<output
aria-label="Loading page"
className="fixed inset-x-0 top-0 z-50 h-0.5 overflow-hidden bg-[#d7d3c7]"
>
<div className="route-progress-bar h-full w-1/3 bg-[#7f9130]" />
</output>
);
};
export const HydrateFallback = () => (
<main className="grid min-h-svh place-items-center bg-[#f2f0e7] text-[#69675f]">
<div className="flex items-center gap-2 text-sm">
<LoaderCircle className="size-4 animate-spin" /> Loading Zopu
</div>
</main>
);
const App = ({ loaderData }: Route.ComponentProps) => (
<WebAuthProvider initialToken={loaderData.token}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
forcedTheme="dark"
disableTransitionOnChange
storageKey="vite-ui-theme"
>
<RouteProgress />
<Outlet />
<Toaster richColors />
</ThemeProvider>
</WebAuthProvider>
);

View File

@@ -2,21 +2,12 @@ import { index, layout, route } from "@react-router/dev/routes";
import type { RouteConfig } from "@react-router/dev/routes";
export default [
// Standalone chat page — no auth, mobile-first, talks to the zopu server.
route("chat", "./routes/standalone/chat/page.tsx"),
layout("./routes/auth/layout.tsx", [
route("login", "./routes/auth/login/page.tsx"),
route("signup", "./routes/auth/signup/page.tsx"),
]),
layout("./routes/app/layout.tsx", [
layout("./routes/app/mobile/layout.tsx", [
index("./routes/app/mobile/page.tsx"),
route("chat", "./routes/app/mobile/chat/page.tsx"),
route("chat/:workUnitId", "./routes/app/mobile/chat/work/page.tsx"),
route("work", "./routes/app/mobile/work-list/page.tsx"),
route("work/:workUnitId", "./routes/app/mobile/work/page.tsx"),
]),
index("./routes/app/mobile/page.tsx"),
route("dashboard", "./routes/app/dashboard/page.tsx"),
route("todos", "./routes/app/todos/page.tsx"),
]),
] satisfies RouteConfig;

View File

@@ -1,29 +1,12 @@
import { useWebAuth } from "@code/auth/web";
import { Navigate, Outlet, useLocation } from "react-router";
import { Outlet } from "react-router";
import { requireAuthToken } from "@/lib/auth.server";
import type { Route } from "./+types/layout";
export const loader = ({ request }: Route.LoaderArgs) =>
requireAuthToken(request);
export default function AppLayout() {
const auth = useWebAuth();
const location = useLocation();
if (auth.status === "loading") {
return (
<div className="grid min-h-svh place-items-center text-sm text-muted-foreground">
Loading
</div>
);
}
if (auth.status === "inconsistent") {
return (
<div className="grid min-h-svh place-items-center text-sm text-muted-foreground">
Your session could not be verified
</div>
);
}
if (auth.status === "unauthenticated") {
return <Navigate replace state={{ from: location.pathname }} to="/login" />;
}
return <Outlet />;
}

View File

@@ -1,12 +0,0 @@
import { SliceOnePage } from "@/components/slice-one/slice-one-page";
import type { Route } from "./+types/page";
export const meta = (_args: Route.MetaArgs) => [
{ title: "Zopu" },
{ content: "Chat with Zopu", name: "description" },
];
export default function MobileChatPage() {
return <SliceOnePage />;
}

View File

@@ -1,15 +0,0 @@
import { MobileFlowPage } from "@/components/mobile-workspace/mobile-flow-page";
import type { Route } from "./+types/page";
export const meta = (_args: Route.MetaArgs) => [
{ title: "Work chat | Zopu" },
{
content: "Chat with Zopu in the context of a selected work unit",
name: "description",
},
];
export default function MobileWorkChatPage() {
return <MobileFlowPage screen="work-chat" />;
}

View File

@@ -1,9 +0,0 @@
import { Outlet } from "react-router";
export default function MobileProductLayout() {
return (
<div className="min-h-svh bg-[#11110f]">
<Outlet />
</div>
);
}

View File

@@ -1,15 +0,0 @@
import { MobileFlowPage } from "@/components/mobile-workspace/mobile-flow-page";
import type { Route } from "./+types/page";
export const meta = (_args: Route.MetaArgs) => [
{ title: "Active work | Zopu" },
{
content: "Browse active work and expand a work unit in place",
name: "description",
},
];
export default function MobileWorkListPage() {
return <MobileFlowPage screen="work-list" />;
}

View File

@@ -1,15 +0,0 @@
import { MobileFlowPage } from "@/components/mobile-workspace/mobile-flow-page";
import type { Route } from "./+types/page";
export const meta = (_args: Route.MetaArgs) => [
{ title: "Work unit | Zopu" },
{
content: "Review the state, next milestone, and activity for a work unit",
name: "description",
},
];
export default function MobileWorkUnitPage() {
return <MobileFlowPage screen="work-unit-detail" />;
}

View File

@@ -1,123 +0,0 @@
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { Button } from "@code/ui/components/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@code/ui/components/card";
import { Checkbox } from "@code/ui/components/checkbox";
import { Input } from "@code/ui/components/input";
import { useMutation, useQuery } from "convex/react";
import { Loader2, Trash2 } from "lucide-react";
import { useState } from "react";
import type { FormEvent, ReactNode } from "react";
export default function Todos() {
const [newTodoText, setNewTodoText] = useState("");
const todos = useQuery(api.todos.getAll);
const createTodo = useMutation(api.todos.create);
const toggleTodo = useMutation(api.todos.toggle);
const deleteTodo = useMutation(api.todos.deleteTodo);
const handleAddTodo = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const text = newTodoText.trim();
if (!text) {
return;
}
await createTodo({ text });
setNewTodoText("");
};
const handleToggleTodo = (id: Id<"todos">, currentCompleted: boolean) => {
void toggleTodo({ completed: !currentCompleted, id });
};
const handleDeleteTodo = (id: Id<"todos">) => {
void deleteTodo({ id });
};
let todoContent: ReactNode;
if (todos === undefined) {
todoContent = (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
);
} else if (todos.length === 0) {
todoContent = (
<p className="py-4 text-center">No todos yet. Add one above!</p>
);
} else {
todoContent = (
<ul className="space-y-2">
{todos.map((todo) => (
<li
className="flex items-center justify-between rounded-md border p-2"
key={todo._id}
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
id={`todo-${todo._id}`}
onCheckedChange={() =>
handleToggleTodo(todo._id, todo.completed)
}
/>
<label
className={
todo.completed
? "text-muted-foreground line-through"
: undefined
}
htmlFor={`todo-${todo._id}`}
>
{todo.text}
</label>
</div>
<Button
aria-label="Delete todo"
onClick={() => handleDeleteTodo(todo._id)}
size="icon"
variant="ghost"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
);
}
return (
<div className="mx-auto w-full max-w-md py-10">
<Card>
<CardHeader>
<CardTitle>Todo List</CardTitle>
<CardDescription>Manage your tasks efficiently</CardDescription>
</CardHeader>
<CardContent>
<form
className="mb-6 flex items-center space-x-2"
onSubmit={handleAddTodo}
>
<Input
onChange={(event) => setNewTodoText(event.target.value)}
placeholder="Add a new task..."
value={newTodoText}
/>
<Button disabled={!newTodoText.trim()} type="submit">
Add
</Button>
</form>
{todoContent}
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,21 +1,13 @@
import { useWebAuth } from "@code/auth/web";
import { Navigate, Outlet } from "react-router";
import { Outlet } from "react-router";
import { redirectAuthenticated } from "@/lib/auth.server";
import type { Route } from "./+types/layout";
export const loader = ({ request }: Route.LoaderArgs) =>
redirectAuthenticated(request);
export default function AuthLayout() {
const auth = useWebAuth();
if (auth.status === "loading") {
return (
<div className="grid min-h-svh place-items-center text-sm text-muted-foreground">
Loading
</div>
);
}
if (auth.status === "authenticated") {
return <Navigate replace to="/" />;
}
return (
<main className="grid min-h-svh place-items-center bg-muted/30 p-6 md:p-10">
<div className="w-full max-w-sm">

View File

@@ -1,5 +1,5 @@
import { LoginForm } from "@code/auth/web";
import { useNavigate } from "react-router";
import { useNavigate, useSearchParams } from "react-router";
import type { Route } from "./+types/page";
@@ -10,6 +10,14 @@ export const meta = (_args: Route.MetaArgs) => [
export default function LoginRoute() {
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const returnTo = searchParams.get("returnTo");
return <LoginForm onSuccess={() => navigate("/", { replace: true })} />;
return (
<LoginForm
onSuccess={() =>
navigate(returnTo?.startsWith("/") ? returnTo : "/", { replace: true })
}
/>
);
}

View File

@@ -6,12 +6,12 @@ import { defineConfig } from "vite-plus";
export default defineConfig({
envDir: path.resolve(import.meta.dirname, "../.."),
server: {
allowedHosts: true,
},
plugins: [tailwindcss(), reactRouter()],
resolve: {
dedupe: ["convex", "react", "react-dom"],
tsconfigPaths: true,
},
server: {
allowedHosts: true,
},
});

168
bun.lock
View File

@@ -32,8 +32,6 @@
"@code/env": "workspace:*",
"@code/primitives": "workspace:*",
"@code/ui": "workspace:*",
"@flue/react": "1.0.0-beta.9",
"@flue/sdk": "1.0.0-beta.9",
"@react-router/fs-routes": "^8.1.0",
"@react-router/node": "^8.1.0",
"@react-router/serve": "^8.1.0",
@@ -41,8 +39,8 @@
"isbot": "^5.1.44",
"lucide-react": "catalog:",
"next-themes": "catalog:",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react": "catalog:",
"react-dom": "catalog:",
"react-router": "^8.1.0",
"sonner": "catalog:",
"streamdown": "2.5.0",
@@ -66,25 +64,17 @@
"name": "@code/agents",
"version": "0.0.0",
"dependencies": {
"@agentos-software/opencode": "0.2.7",
"@code/backend": "workspace:*",
"@code/env": "workspace:*",
"@code/primitives": "workspace:*",
"@flue/runtime": "latest",
"@rivet-dev/agentos-core": "catalog:",
"convex": "catalog:",
"dockerode": "^5.0.1",
"effect": "catalog:",
"get-port": "^7.2.0",
"hono": "4.12.31",
"sandbox-agent": "0.4.2",
"valibot": "^1.4.2",
},
"devDependencies": {
"@code/config": "workspace:*",
"@flue/cli": "latest",
"@types/bun": "catalog:",
"@types/dockerode": "^4.0.1",
"typescript": "catalog:",
},
},
@@ -103,7 +93,7 @@
"expo-constants": "~57.0.2",
"expo-secure-store": "~57.0.0",
"heroui-native": "catalog:",
"react": "^19.2.3",
"react": "catalog:",
"react-native": "0.86.0",
"sonner": "catalog:",
"zod": "catalog:",
@@ -185,8 +175,8 @@
"clsx": "^2.1.1",
"lucide-react": "catalog:",
"next-themes": "catalog:",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react": "catalog:",
"react-dom": "catalog:",
"shadcn": "^4.12.0",
"shiki": "^4.3.1",
"sonner": "catalog:",
@@ -225,6 +215,8 @@
"heroui-native": "^1.0.5",
"lucide-react": "^1.23.0",
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.2",
@@ -482,8 +474,6 @@
"@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
"@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
"@base-ui/react": ["@base-ui/react@1.6.0", "", { "dependencies": { "@babel/runtime": "^7.29.2", "@base-ui/utils": "0.3.1", "@floating-ui/react-dom": "^2.1.8", "@floating-ui/utils": "^0.2.11", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@date-fns/tz": "^1.2.0", "@types/react": "^17 || ^18 || ^19", "date-fns": "^4.0.0", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@date-fns/tz", "@types/react", "date-fns"] }, "sha512-/jzjTWJYXhRFO45Bev9lc3cHbmjzCMpUqbMZ2AgKy/z25mY9B6shGSNcXcjQar9n5doM0KYW1W8fcFv2jZBuMw=="],
"@base-ui/utils": ["@base-ui/utils@0.3.1", "", { "dependencies": { "@babel/runtime": "^7.29.2", "@floating-ui/utils": "^0.2.11", "reselect": "^5.2.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-gFFiltORVmW/N6IILTGxizP3PBpVpysqML1ALY5Vk0mH+7faVkCknOU31goYHN5Aoek2dkjxva1XOD2Ce9WuIg=="],
@@ -732,8 +722,6 @@
"@flue/cli": ["@flue/cli@1.0.0-beta.9", "", { "dependencies": { "@cloudflare/vite-plugin": "^1.39.2", "@flue/runtime": "1.0.0-beta.9", "@flue/sdk": "1.0.0-beta.9", "@hono/node-server": "^2.0.3", "@vercel/detect-agent": "^1.2.3", "debug": "^4.4.3", "minisearch": "^7.2.0", "package-up": "^5.0.0", "picocolors": "^1.1.1", "ulidx": "^2.4.1", "valibot": "^1.0.0", "vite": "^8.0.14" }, "bin": { "flue": "bin/flue.mjs" } }, "sha512-RPv28ecD7lQ2XBZbuohte3rXDqHHrdXTpCGC5mSxYQsEkOeDN2LOmImQZbJqCrkIAFmMgntzOhaF2+14R61C4Q=="],
"@flue/react": ["@flue/react@1.0.0-beta.9", "", { "peerDependencies": { "@flue/sdk": ">=1.0.0-beta.3 <1.0.0", "react": ">=18" } }, "sha512-mr8vNtr1kwUpgsq1fISfz1TmPhVOpp/jrQdx0FYSRoeURq+cMVcWo/k5gI86xTS2BjtCN70edYrmxjjRWBUA6A=="],
"@flue/runtime": ["@flue/runtime@1.0.0-beta.9", "", { "dependencies": { "@earendil-works/pi-agent-core": "^0.80.2", "@earendil-works/pi-ai": "^0.80.2", "@hono/node-server": "^2.0.3", "@hono/standard-validator": "^0.2.0", "@modelcontextprotocol/sdk": "^1.29.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@valibot/to-json-schema": "^1.3.0", "hono": "^4.8.3", "hono-openapi": "^1.3.0", "js-yaml": "^4.1.1", "just-bash": "^3.0.1", "openapi-types": "^12.1.3", "quansync": "^0.2.11", "ulidx": "^2.4.1", "valibot": "^1.1.0" } }, "sha512-ksh0ZkTVyqQnGvU3OnbVX6luAJwe6tt8q7O0vn99b7Cx6XcPTXzY/YEkXrOtCHzV6ZwfSdO9ZfaWbhTD1tdQuQ=="],
"@flue/sdk": ["@flue/sdk@1.0.0-beta.9", "", { "dependencies": { "@durable-streams/client": "^0.2.6" } }, "sha512-EkGWF1Yw6baM4ekmp+3xFkc+LmDKcIAA0KQSZSpaSqQRYyixXB+IwEbhePS83HCgrR0/jup9l8rgld4Q2IGNOw=="],
@@ -744,10 +732,6 @@
"@gorhom/portal": ["@gorhom/portal@1.0.14", "", { "dependencies": { "nanoid": "^3.3.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-MXyL4xvCjmgaORr/rtryDNFy3kU4qUbKlwtQqqsygd0xX3mhKjOLn6mQK8wfu0RkoE0pBE0nAasRoHua+/QZ7A=="],
"@grpc/grpc-js": ["@grpc/grpc-js@1.14.4", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ=="],
"@grpc/proto-loader": ["@grpc/proto-loader@0.7.15", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="],
"@hono/node-server": ["@hono/node-server@2.0.11", "", { "peerDependencies": { "hono": "^4" } }, "sha512-bjD221KPLoJTWUwso1J6fGKiTXEUFedG/s0visavY4zakFPkeGURMRNly+FhBHs7T8Dz4qHaZIMX9ZoJHSJtKA=="],
"@hono/standard-validator": ["@hono/standard-validator@0.2.3", "", { "peerDependencies": { "@standard-schema/spec": "^1.0.0", "hono": ">=3.9.0" } }, "sha512-bp9vHu6Va6SfMHC3D4ZLBbT/woi+AZ9CRdTXQu3kLJuLh2W/Gb9UO4hijS+BQAGFXi4EGpXdetxpzwTAawSVeg=="],
@@ -848,8 +832,6 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="],
"@mariozechner/clipboard": ["@mariozechner/clipboard@0.3.9", "", { "optionalDependencies": { "@mariozechner/clipboard-darwin-arm64": "0.3.9", "@mariozechner/clipboard-darwin-universal": "0.3.9", "@mariozechner/clipboard-darwin-x64": "0.3.9", "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9", "@mariozechner/clipboard-linux-arm64-musl": "0.3.9", "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-gnu": "0.3.9", "@mariozechner/clipboard-linux-x64-musl": "0.3.9", "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9", "@mariozechner/clipboard-win32-x64-msvc": "0.3.9" } }, "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA=="],
"@mariozechner/clipboard-darwin-arm64": ["@mariozechner/clipboard-darwin-arm64@0.3.9", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ=="],
@@ -1250,20 +1232,6 @@
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.2", "", { "os": "linux", "cpu": "x64" }, "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A=="],
"@sandbox-agent/cli": ["@sandbox-agent/cli@0.4.2", "", { "dependencies": { "@sandbox-agent/cli-shared": "0.4.2" }, "optionalDependencies": { "@sandbox-agent/cli-darwin-arm64": "0.4.2", "@sandbox-agent/cli-darwin-x64": "0.4.2", "@sandbox-agent/cli-linux-arm64": "0.4.2", "@sandbox-agent/cli-linux-x64": "0.4.2", "@sandbox-agent/cli-win32-x64": "0.4.2" }, "bin": { "sandbox-agent": "bin/sandbox-agent" } }, "sha512-trO//ypJBSt5xkewuol9LOykvDgHwUXq8R+yQVS+0CmpN3lYUtewHkb+At9RVGRhDMmJZY2oasaXDnhfurQ33w=="],
"@sandbox-agent/cli-darwin-arm64": ["@sandbox-agent/cli-darwin-arm64@0.4.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-+L1O8SI7k/LLhyB4dG0ghmz1cJHa0WtVjuRTrEE2gw/5EbGLWopPBsCVCmQ7snrQ4fPwtaiZDhfExcEj1VI7aw=="],
"@sandbox-agent/cli-darwin-x64": ["@sandbox-agent/cli-darwin-x64@0.4.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-dDg/EwWsdgVVbJiiCX1scSNRRA48u77SsC7Tuqrfzx4fIJMLuLiIcmEtXQyCBWysSyQNV2Cr+PYXXQfCb3xg8g=="],
"@sandbox-agent/cli-linux-arm64": ["@sandbox-agent/cli-linux-arm64@0.4.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-TGmTUexMoubmWQyTeaOJu0rDVl2h0Ifh1pZ0ceZy7u/6Eoqs2n46CbfQtasUxZJf10uxPgRyzEDhcdDrTYVQUA=="],
"@sandbox-agent/cli-linux-x64": ["@sandbox-agent/cli-linux-x64@0.4.2", "", { "os": "linux", "cpu": "x64" }, "sha512-H9Rbqq0DRkCHvakzefJUDrDa2y+vJjlYd5/tefzKbQ34locE13TGNygRLxdEVXpBECjK9wVdBwTVEphQNsOcjw=="],
"@sandbox-agent/cli-shared": ["@sandbox-agent/cli-shared@0.4.2", "", {}, "sha512-sjZXRkKeFXCSKR6hHzF2Af8CCRO3F3WFwVQJ22+sLTXJ2xskV8lkUE4egknQU9B5BC1Zumts/YiNCFQWG85awQ=="],
"@sandbox-agent/cli-win32-x64": ["@sandbox-agent/cli-win32-x64@0.4.2", "", { "os": "win32", "cpu": "x64" }, "sha512-lZNfHWPwQe/VH51Yvrl/ATCUvBZ3a+c8mwovojhQcmZlv4QuUQPkuvxhPqHRh9AyBx78L5J/ha46es2doa34nQ=="],
"@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
"@secure-exec/core": ["@secure-exec/core@0.2.1", "", { "dependencies": { "better-sqlite3": "^12.8.0" } }, "sha512-HsnUv6gClpMA1BBRmX86j30TKTZtgJC/fO1tVavr7IpM2zNKbHU8LgSlBd7mv2SNy02ImTmU/GnQ3aYB4NSbEg=="],
@@ -1300,7 +1268,7 @@
"@silvia-odwyer/photon-node": ["@silvia-odwyer/photon-node@0.3.4", "", {}, "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA=="],
"@sinclair/typebox": ["@sinclair/typebox@0.34.52", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="],
"@sinclair/typebox": ["@sinclair/typebox@0.27.12", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
"@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="],
@@ -1498,10 +1466,6 @@
"@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/docker-modem": ["@types/docker-modem@3.0.6", "", { "dependencies": { "@types/node": "*", "@types/ssh2": "*" } }, "sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg=="],
"@types/dockerode": ["@types/dockerode@4.0.1", "", { "dependencies": { "@types/docker-modem": "*", "@types/node": "*", "@types/ssh2": "*" } }, "sha512-cmUpB+dPN955PxBEuXE3f6lKO1hHiIGYJA46IVF3BJpNsZGvtBDcRnlrHYHtOH/B6vtDOyl2kZ2ShAu3mgc27Q=="],
"@types/esrecurse": ["@types/esrecurse@4.3.1", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
"@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
@@ -1540,8 +1504,6 @@
"@types/retry": ["@types/retry@0.12.2", "", {}, "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow=="],
"@types/ssh2": ["@types/ssh2@1.15.5", "", { "dependencies": { "@types/node": "^18.11.18" } }, "sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ=="],
"@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
@@ -1628,8 +1590,6 @@
"acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
"acp-http-client": ["acp-http-client@0.4.2", "", { "dependencies": { "@agentclientprotocol/sdk": "^0.16.1" } }, "sha512-3wtPieF08YIU4vNXaoL5up/1D0if4i9IX3Ye5q/bwbcwg1BKsazIK/VNNfvN4ldbPjWul69IqIOpGRS3I0qo3Q=="],
"agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
"agent-cli-detector": ["agent-cli-detector@0.1.4", "", { "bin": { "agent-cli-detector": "dist/cli.js" } }, "sha512-qPgevFvpaQoBaRJVKzr8R7h1WPvV3DtbgRIQlne4le66KBzXx5hNBwo/+NTw67LgkKBlhCzksrdautpUdlls0Q=="],
@@ -1664,8 +1624,6 @@
"asap": ["asap@2.0.6", "", {}, "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="],
"asn1": ["asn1@0.2.6", "", { "dependencies": { "safer-buffer": "~2.1.0" } }, "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ=="],
"asn1.js": ["asn1.js@4.10.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0" } }, "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw=="],
"assert": ["assert@2.1.0", "", { "dependencies": { "call-bind": "^1.0.2", "is-nan": "^1.3.2", "object-is": "^1.1.5", "object.assign": "^4.1.4", "util": "^0.12.5" } }, "sha512-eLHpSK/Y4nhMJ07gDaAzoX/XAKS8PSaojml3M0DM4JpV1LAi5JOJ/p6H/XWrl8L+DzVEvVCW1z3vWAaB9oTsQw=="],
@@ -1710,8 +1668,6 @@
"basic-ftp": ["basic-ftp@5.3.1", "", {}, "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw=="],
"bcrypt-pbkdf": ["bcrypt-pbkdf@1.0.2", "", { "dependencies": { "tweetnacl": "^0.14.3" } }, "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w=="],
"better-auth": ["better-auth@1.6.15", "", { "dependencies": { "@better-auth/core": "1.6.15", "@better-auth/drizzle-adapter": "1.6.15", "@better-auth/kysely-adapter": "1.6.15", "@better-auth/memory-adapter": "1.6.15", "@better-auth/mongo-adapter": "1.6.15", "@better-auth/prisma-adapter": "1.6.15", "@better-auth/telemetry": "1.6.15", "@better-auth/utils": "0.4.1", "@better-fetch/fetch": "1.1.21", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.3.5", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-0nuQuEru3ZrLF+9xFUuN3llAmR+6gHLtLunoXaZxB9lXGjSmfBcc6SZUgYq4DfzugPnLvdnzYazsyprZFSFC4Q=="],
"better-call": ["better-call@1.3.5", "", { "dependencies": { "@better-auth/utils": "^0.4.0", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-kOFJkBP7utAQLEYrobZm3vkTH8mXq5GNgvjc5/XEST1ilVHaxXUXfeDeFlqoETMtyqS4+3/h4ONX2i++ebZrvA=="],
@@ -1774,8 +1730,6 @@
"buffer-xor": ["buffer-xor@1.0.3", "", {}, "sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ=="],
"buildcheck": ["buildcheck@0.0.7", "", {}, "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA=="],
"builtin-status-codes": ["builtin-status-codes@3.0.0", "", {}, "sha512-HpGFw18DgFWlncDfjTa2rcQ4W88O1mC8e8yZ2AvQY5KDaktSTwo+KRf6nHK6FRI5FyRyb/5T6+TSxfP7QyGsmQ=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
@@ -1908,8 +1862,6 @@
"cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="],
"cpu-features": ["cpu-features@0.0.10", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="],
"create-ecdh": ["create-ecdh@4.0.4", "", { "dependencies": { "bn.js": "^4.1.0", "elliptic": "^6.5.3" } }, "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A=="],
"create-hash": ["create-hash@1.2.0", "", { "dependencies": { "cipher-base": "^1.0.1", "inherits": "^2.0.1", "md5.js": "^1.3.4", "ripemd160": "^2.0.1", "sha.js": "^2.4.0" } }, "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg=="],
@@ -2072,10 +2024,6 @@
"dnssd-advertise": ["dnssd-advertise@1.1.6", "", {}, "sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg=="],
"docker-modem": ["docker-modem@5.0.7", "", { "dependencies": { "debug": "^4.1.1", "readable-stream": "^3.5.0", "split-ca": "^1.0.1", "ssh2": "^1.15.0" } }, "sha512-XJgGhoR/CLpqshm4d3L7rzH6t8NgDFUIIpztYlLHIApeJjMZKYJMz2zxPsYxnejq5h3ELYSw/RBsi3t5h7gNTA=="],
"dockerode": ["dockerode@5.0.1", "", { "dependencies": { "@balena/dockerignore": "^1.0.2", "@grpc/grpc-js": "^1.11.1", "@grpc/proto-loader": "^0.7.13", "docker-modem": "^5.0.7", "protobufjs": "^7.3.2", "tar-fs": "^2.1.4" } }, "sha512-avsq/xk4YPIrn0CgleX5bjT9Y8IT1p9PxrNQ++RBQ2WEyFfHCTDsT9kmyxz+H/axnjAwg8wJWEIuPGOUuNupiA=="],
"dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],
"dom-helpers": ["dom-helpers@3.4.0", "", { "dependencies": { "@babel/runtime": "^7.1.2" } }, "sha512-LnuPJ+dwqKDIyotW1VzmOZ5TONUN7CwkCR5hrgawTUbkBGYdeoNLZo6nNfGkCrjtE1nXXaj7iMMpDa8/d9WoIA=="],
@@ -2328,9 +2276,9 @@
"fuzzysort": ["fuzzysort@3.1.0", "", {}, "sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ=="],
"gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],
"gaxios": ["gaxios@7.2.0", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-CUVb4wcYe+771XevyH6HtGmXFAGGKkIC3kswAP8Z1JCe0j80JMaTPZH930DWFrvo0atjh18Arc0pEyUCWa5bfg=="],
"gcp-metadata": ["gcp-metadata@6.1.1", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="],
"gcp-metadata": ["gcp-metadata@8.1.2", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],
"generator-function": ["generator-function@2.0.1", "", {}, "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g=="],
@@ -2346,8 +2294,6 @@
"get-own-enumerable-keys": ["get-own-enumerable-keys@1.0.0", "", {}, "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA=="],
"get-port": ["get-port@7.2.0", "", {}, "sha512-afP4W205ONCuMoPBqcR6PSXnzX35KTcJygfJfcp+QY+uwm3p20p1YczWXhlICIzGMCxYBQcySEcOgsJcrkyobg=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="],
@@ -2366,7 +2312,7 @@
"goober": ["goober@2.1.19", "", { "peerDependencies": { "csstype": "^3.0.10" } }, "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg=="],
"google-auth-library": ["google-auth-library@9.15.1", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="],
"google-auth-library": ["google-auth-library@10.9.0", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" } }, "sha512-xtvUqvINPhTaBm7nXqlYPcrMHJPm1lCNdSovxnKKhTm+4JsvQ+KGVYJViLoH9Yxu8w+T0Qv5HubzYT9BLrppJg=="],
"google-logging-utils": ["google-logging-utils@1.1.3", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="],
@@ -2442,7 +2388,7 @@
"hono-openapi": ["hono-openapi@1.3.1", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.11.2", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-NLVeVkhKZ3drmQNEIPac8HX8Y54uf1hJAgIM/7MfDsaeVVmB+QILWQxx5x3R3NvRHgedcbEbOCGY2uR7WQYyMw=="],
"hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="],
"hosted-git-info": ["hosted-git-info@7.0.2", "", { "dependencies": { "lru-cache": "^10.0.1" } }, "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w=="],
"html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
@@ -2670,8 +2616,6 @@
"lodash-es": ["lodash-es@4.18.1", "", {}, "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="],
"lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="],
"lodash.debounce": ["lodash.debounce@4.0.8", "", {}, "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow=="],
"lodash.throttle": ["lodash.throttle@4.1.1", "", {}, "sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ=="],
@@ -2906,8 +2850,6 @@
"mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="],
"nan": ["nan@2.28.0", "", {}, "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ=="],
"nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="],
"nanostores": ["nanostores@1.4.1", "", {}, "sha512-PGd3uPojJB9Z07d5NX3Db/SOSBbyy3wLMUGq0GpnEEJfVzY9mq7daPMAZ3jObV5D3Jn+YKND636eI5ULg7F80Q=="],
@@ -2928,7 +2870,7 @@
"node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],
"node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
"node-forge": ["node-forge@1.4.0", "", {}, "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ=="],
@@ -3334,8 +3276,6 @@
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"sandbox-agent": ["sandbox-agent@0.4.2", "", { "dependencies": { "@sandbox-agent/cli-shared": "0.4.2", "acp-http-client": "0.4.2" }, "optionalDependencies": { "@sandbox-agent/cli": "0.4.2" }, "peerDependencies": { "@cloudflare/sandbox": ">=0.1.0", "@daytonaio/sdk": ">=0.12.0", "@e2b/code-interpreter": ">=1.0.0", "@fly/sprites": ">=0.0.1", "@vercel/sandbox": ">=0.1.0", "computesdk": ">=0.1.0", "dockerode": ">=4.0.0", "get-port": ">=7.0.0", "modal": ">=0.1.0" }, "optionalPeers": ["@cloudflare/sandbox", "@daytonaio/sdk", "@e2b/code-interpreter", "@fly/sprites", "@vercel/sandbox", "computesdk", "dockerode", "get-port", "modal"] }, "sha512-fH6WDQEaIrgiu93LxZcy+4Dx+t+/cslu+hzXImDyUlsaL6jV2jIv4fdxELkALlo7uzyEDVK9lmqs9qy65RHwBQ=="],
"sax": ["sax@1.6.0", "", {}, "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
@@ -3432,8 +3372,6 @@
"space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],
"split-ca": ["split-ca@1.0.1", "", {}, "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ=="],
"split-on-first": ["split-on-first@1.1.0", "", {}, "sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw=="],
"split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="],
@@ -3442,8 +3380,6 @@
"sql.js": ["sql.js@1.14.1", "", {}, "sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A=="],
"ssh2": ["ssh2@1.17.0", "", { "dependencies": { "asn1": "^0.2.6", "bcrypt-pbkdf": "^1.0.2" }, "optionalDependencies": { "cpu-features": "~0.0.10", "nan": "^2.23.0" } }, "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ=="],
"stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"stackframe": ["stackframe@1.3.4", "", {}, "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw=="],
@@ -3592,8 +3528,6 @@
"tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
"tweetnacl": ["tweetnacl@0.14.5", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="],
"type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
"type-fest": ["type-fest@5.8.0", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA=="],
@@ -3858,16 +3792,10 @@
"@expo/xcpretty/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"@google/genai/google-auth-library": ["google-auth-library@10.9.0", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" } }, "sha512-xtvUqvINPhTaBm7nXqlYPcrMHJPm1lCNdSovxnKKhTm+4JsvQ+KGVYJViLoH9Yxu8w+T0Qv5HubzYT9BLrppJg=="],
"@google/genai/p-retry": ["p-retry@4.6.2", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],
"@google/genai/ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="],
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
"@jest/schemas/@sinclair/typebox": ["@sinclair/typebox@0.27.12", "", {}, "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g=="],
"@jest/types/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
"@jest/types/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
@@ -3880,6 +3808,10 @@
"@mariozechner/pi-ai/@mistralai/mistralai": ["@mistralai/mistralai@1.14.1", "", { "dependencies": { "ws": "^8.18.0", "zod": "^3.25.0 || ^4.0.0", "zod-to-json-schema": "^3.24.1" } }, "sha512-IiLmmZFCCTReQgPAT33r7KQ1nYo5JPdvGkrkZqA8qQ2qB1GHgs5LoP5K2ICyrjnpw2n8oSxMM/VP+liiKcGNlQ=="],
"@mariozechner/pi-ai/@sinclair/typebox": ["@sinclair/typebox@0.34.52", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="],
"@mariozechner/pi-coding-agent/hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="],
"@mariozechner/pi-coding-agent/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="],
"@mariozechner/pi-coding-agent/marked": ["marked@15.0.12", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA=="],
@@ -3934,12 +3866,6 @@
"@testing-library/jest-dom/dom-accessibility-api": ["dom-accessibility-api@0.6.3", "", {}, "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w=="],
"@types/docker-modem/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
"@types/dockerode/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
"@types/ssh2/@types/node": ["@types/node@18.19.130", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="],
"@types/yauzl/@types/node": ["@types/node@26.1.1", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
@@ -3988,6 +3914,8 @@
"create-ecdh/bn.js": ["bn.js@4.12.5", "", {}, "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="],
"cross-fetch/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"css-tree/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"cytoscape-fcose/cose-base": ["cose-base@2.2.0", "", { "dependencies": { "layout-base": "^2.0.0" } }, "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g=="],
@@ -4044,18 +3972,22 @@
"fetch-blob/web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],
"gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"gaxios/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
"gcp-metadata/google-logging-utils": ["google-logging-utils@0.0.2", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="],
"get-uri/data-uri-to-buffer": ["data-uri-to-buffer@6.0.2", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="],
"googleapis/google-auth-library": ["google-auth-library@9.15.1", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="],
"googleapis-common/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],
"googleapis-common/google-auth-library": ["google-auth-library@9.15.1", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="],
"googleapis-common/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
"gtoken/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],
"hoist-non-react-statics/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
"hosted-git-info/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"import-fresh/resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
"is-inside-container/is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
@@ -4102,8 +4034,6 @@
"node-stdlib-browser/punycode": ["punycode@1.4.1", "", {}, "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ=="],
"npm-package-arg/hosted-git-info": ["hosted-git-info@7.0.2", "", { "dependencies": { "lru-cache": "^10.0.1" } }, "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w=="],
"npm-package-arg/validate-npm-package-name": ["validate-npm-package-name@5.0.1", "", {}, "sha512-OljLrQ9SQdOUqTaQxqL5dEfZWrXExyyWsozYlAWFawPVNuD83igl7uJD2RTkNMbniIYgt8l81eCJGIdQF7avLQ=="],
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
@@ -4284,10 +4214,6 @@
"@expo/xcpretty/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"@google/genai/google-auth-library/gaxios": ["gaxios@7.2.0", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-CUVb4wcYe+771XevyH6HtGmXFAGGKkIC3kswAP8Z1JCe0j80JMaTPZH930DWFrvo0atjh18Arc0pEyUCWa5bfg=="],
"@google/genai/google-auth-library/gcp-metadata": ["gcp-metadata@8.1.2", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],
"@google/genai/p-retry/@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="],
"@jest/types/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
@@ -4394,12 +4320,6 @@
"@testing-library/dom/pretty-format/react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="],
"@types/docker-modem/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
"@types/dockerode/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
"@types/ssh2/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
"@types/yauzl/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
"browserify-sign/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
@@ -4436,6 +4356,22 @@
"expo-modules-autolinking/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"googleapis-common/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"googleapis-common/gaxios/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"googleapis-common/google-auth-library/gcp-metadata": ["gcp-metadata@6.1.1", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="],
"googleapis/google-auth-library/gaxios": ["gaxios@6.7.1", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],
"googleapis/google-auth-library/gcp-metadata": ["gcp-metadata@6.1.1", "", { "dependencies": { "gaxios": "^6.1.1", "google-logging-utils": "^0.0.2", "json-bigint": "^1.0.0" } }, "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A=="],
"gtoken/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"gtoken/gaxios/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"gtoken/gaxios/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
"jest-util/@types/node/undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
"jest-util/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
@@ -4454,8 +4390,6 @@
"morgan/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],
"npm-package-arg/hosted-git-info/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"ora/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
"pkg-up/find-up/locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="],
@@ -4616,14 +4550,22 @@
"@expo/package-manager/ora/strip-ansi/ansi-regex": ["ansi-regex@4.1.1", "", {}, "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g=="],
"@google/genai/google-auth-library/gaxios/node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
"@react-native/dev-middleware/serve-static/send/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],
"@react-native/dev-middleware/serve-static/send/fresh": ["fresh@0.5.2", "", {}, "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q=="],
"cli-highlight/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"googleapis-common/google-auth-library/gcp-metadata/google-logging-utils": ["google-logging-utils@0.0.2", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="],
"googleapis/google-auth-library/gaxios/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
"googleapis/google-auth-library/gaxios/node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="],
"googleapis/google-auth-library/gaxios/uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
"googleapis/google-auth-library/gcp-metadata/google-logging-utils": ["google-logging-utils@0.0.2", "", {}, "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ=="],
"md5.js/hash-base/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"md5.js/hash-base/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],

View File

@@ -12,10 +12,11 @@
# ---------------------------------------------------------------------------
CONVEX_URL=https://your-deployment.convex.cloud
CONVEX_SITE_URL=https://your-deployment.convex.site
SITE_URL=http://localhost:5173
SITE_URL=http://localhost:13100
VITE_AUTH_URL=http://localhost:13100
VITE_CONVEX_URL=https://your-deployment.convex.cloud
VITE_CONVEX_SITE_URL=https://your-deployment.convex.site
VITE_FLUE_URL=http://localhost:3583
VITE_ZOPU_SERVER_URL=http://localhost:3590
# Self-hosted Convex origins used by convex/docker-compose.yml
CONVEX_CLOUD_ORIGIN=https://your-deployment.convex.cloud

View File

@@ -1,13 +1,21 @@
# Caddyfile — Public reverse proxy for the Zopu web + API.
#
# The web frontend (port 5173) is served at the root, and the Flue agent/API
# (port 3585) is mounted under /api so the browser talks same-origin.
# The web frontend (port 5173) is served at the root, Better Auth is proxied
# first-party under /api/auth, and Flue is mounted under /api/flue.
zopu.cheaptricks.puter.wtf {
bind 135.181.82.179 2a01:4f9:c013:4a64::1
encode zstd gzip
handle_path /api/* {
handle /api/auth/* {
reverse_proxy https://befitting-dalmatian-161.convex.site {
header_up Host befitting-dalmatian-161.convex.site
header_up X-Forwarded-Host {host}
header_up X-Forwarded-Proto {scheme}
}
}
handle_path /api/flue/* {
reverse_proxy 127.0.0.1:3585
}

View File

@@ -10,62 +10,64 @@
## 1. System topology
```text
Web / Buzz / integrations
Web / desktop / mobile
Convex queries, mutations, storage
Application API + Convex durable data
Convex application backend
├── authentication and tenancy
├── normalized product data
├── conversation turn queue
└── reactive client projections
│ service-authenticated dispatch
Rivet actor system
├── ProjectActor
├── WorkActor
── AttemptActor
├── VerificationActor (later split)
├── IntegrationActor (later)
└── ResultActor (later)
FLUE orchestration service
├── model calls
├── typed tools
── canonical Flue persistence in Convex
│ later execution commands
FLUE orchestration/application agents
── Signal/Definition
├── Design/Slice planning
├── Resolver decisions
├── Verification design/evaluation
└── Learning synthesis
Ports
├── HarnessRuntime
├── SandboxRuntime
├── SourceControl
├── ArtifactStore
├── PreviewRuntime
├── SecretBroker
├── EventJournal
└── RuntimePolicy
Adapters
├── OMP/OpenCode/Codex/Pi/custom FLUE
├── CubeSandbox/AgentOS/persistent machine/Docker
├── Git forge
├── object storage
└── deployment/preview providers
Rivet Engine + AgentOS (post-Slice 1)
── sandboxes, harnesses, and durable execution
```
Clients MUST communicate only with Convex. FLUE and future Rivet/AgentOS
services are private workers: Convex admits durable commands, invokes the
worker, and stores the product-facing result before clients observe it.
### Ownership
| Layer | Owns |
|---|---|
| Work OS | durable intent, lifecycle, evidence, policy |
| Rivet actors | serialized ownership, recovery, timers, leases |
| FLUE | programmable orchestration and domain-specific agents |
| Convex | authentication, normalized product records, command admission, reactive reads |
| FLUE | private programmable orchestration and domain-specific agents |
| Rivet actors (later) | serialized execution ownership, recovery, timers, leases |
| Harness | bounded coding/tool loop |
| Sandbox/runtime | filesystem, processes, network, isolation |
| Git | source revision history |
| Artifact store | durable outputs/evidence |
| External systems | collaboration, delivery, monitoring |
No harness, sandbox, or chat transcript owns Work state.
No client, harness, sandbox, or FLUE process owns product state.
### Slice 1 relational core
```text
organizations ──< organizationMembers
organizations ──< projects ──< projectContextDocuments
organizations ──1 conversations ──< conversationTurns
conversationTurns ──< conversationMessages ──< conversationAttachments
projects ──< signals ──< signalConstraints
signals ──< signalSources >── conversationMessages
projects ──< works
signals ──< signalWorkAttachments >── works
works ──< workEvents
```
Convex mutations provide atomic transactions and optimistic serializability.
Foreign-key integrity and uniqueness are enforced in the owning mutations;
composite indexes back every identity and relation lookup. Flue's adapter
tables remain isolated infrastructure persistence and are not product-domain
relations.
## 2. Domain boundaries

View File

@@ -10,7 +10,6 @@
"packages/config",
"packages/env",
"packages/primitives",
"packages/ui",
"packages/ui"
],
"catalog": {
@@ -21,6 +20,8 @@
"zod": "^4.4.3",
"lucide-react": "^1.23.0",
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"sonner": "^2.0.7",
"convex": "^1.42.1",
"better-auth": "1.6.15",
@@ -44,10 +45,9 @@
"dev": "vp run -r dev",
"build": "vp run -r build",
"check-types": "vp run -r check-types",
"check": "ultracite check package.json vite.config.ts apps/web/package.json apps/web/src/root.tsx apps/web/src/index.css apps/web/src/components/chat/chat-attachments.tsx apps/web/src/components/chat/chat-message.tsx apps/web/src/components/slice-one apps/web/src/hooks/chat/use-chat-agent.test.ts apps/web/src/hooks/chat/use-chat-images.ts apps/web/src/hooks/slice-one apps/web/src/lib/chat/attachments.ts apps/web/src/lib/chat/attachments.test.ts apps/web/src/lib/chat/transforms.ts apps/web/src/lib/chat/transforms.test.ts apps/web/src/lib/flue-transport.ts apps/web/src/lib/flue-transport.test.ts apps/web/src/lib/slice-one apps/web/src/routes/app/dashboard/page.tsx apps/web/src/routes/app/mobile/chat/page.tsx apps/web/src/routes/app/mobile/page.tsx packages/agents/package.json packages/agents/src/agents/zopu.ts packages/agents/src/tools/slice-one.ts packages/backend/package.json packages/backend/convex/schema.ts packages/backend/convex/works.ts packages/backend/convex/works.test.ts packages/primitives/src/work.ts packages/primitives/src/work.test.ts",
"check": "ultracite check package.json vite.config.ts apps/web/package.json apps/web/src/root.tsx apps/web/src/index.css apps/web/src/components/chat apps/web/src/components/slice-one apps/web/src/hooks/chat apps/web/src/hooks/slice-one apps/web/src/lib/chat apps/web/src/lib/slice-one apps/web/src/routes.ts apps/web/src/routes/app/dashboard/page.tsx apps/web/src/routes/app/mobile/page.tsx packages/agents/package.json packages/agents/src/agents/zopu.ts packages/agents/src/app.ts packages/agents/src/auth.ts packages/agents/src/tools/slice-one.ts packages/backend/package.json packages/backend/convex/conversationMessages.ts packages/backend/convex/conversationMessages.test.ts packages/backend/convex/projects.ts packages/backend/convex/schema.ts packages/backend/convex/signalRouting.ts packages/backend/convex/signalRouting.test.ts packages/backend/convex/works.ts packages/backend/convex/works.test.ts packages/primitives/src/work.ts packages/primitives/src/work.test.ts",
"lint": "vp lint",
"format": "vp fmt",
"smoke:zopu": "bun scripts/zopu-smoke.ts",
"staged": "vp staged",
"hooks:setup": "vp config",
"dev:web": "vp run --filter web dev",
@@ -61,8 +61,6 @@
"subtree": "bun run scripts/subtree.ts",
"fix": "ultracite fix",
"slice1": "vp run -r dev",
"orb:proof": "bun run scripts/orb-proof.ts",
"orb:run": "bun run scripts/orb-project-run.ts",
"dev:zopu": "vp run --filter @code/agents dev",
"dev:zopu:web": "vp run --filter web dev"
},

View File

@@ -9,29 +9,20 @@
"dev": "bun --env-file=../../.env flue dev",
"dev:tailscale": "bun --env-file=../../.env flue dev",
"run": "bun --env-file=../../.env flue run",
"run:zopu": "bun --env-file=../../.env flue run zopu",
"run:zopu-dev": "bun --env-file=../../.env flue run zopu-dev"
"run:zopu": "bun --env-file=../../.env flue run zopu"
},
"dependencies": {
"@agentos-software/opencode": "0.2.7",
"@code/backend": "workspace:*",
"@code/env": "workspace:*",
"@code/primitives": "workspace:*",
"@flue/runtime": "latest",
"@rivet-dev/agentos-core": "catalog:",
"convex": "catalog:",
"dockerode": "^5.0.1",
"effect": "catalog:",
"get-port": "^7.2.0",
"hono": "4.12.31",
"sandbox-agent": "0.4.2",
"valibot": "^1.4.2"
},
"devDependencies": {
"@code/config": "workspace:*",
"@flue/cli": "latest",
"@types/bun": "catalog:",
"@types/dockerode": "^4.0.1",
"typescript": "catalog:"
}
}

View File

@@ -1,91 +0,0 @@
/**
* Smoke test: exercise the agentos sandbox adapter through Flue's
* createSandboxSessionEnv wrapper — the same path the zopu agent uses.
*
* Run: bun --env-file=../../.env packages/agents/scripts/agentos-adapter-test.ts
*/
import { agentos } from "../src/sandboxes/agentos";
const main = async () => {
const factory = agentos();
// Flue calls this once per harness initialization.
const env = await factory.createSessionEnv({ id: "smoke-test" });
let pass = 0;
let fail = 0;
const assert = (label: string, condition: boolean) => {
if (condition) {
pass += 1;
console.log(`${label}`);
} else {
fail += 1;
console.log(`${label}`);
}
};
console.log("\n=== File operations ===");
await env.writeFile("test.txt", "hello from Flue adapter");
assert("writeFile", true);
const content = await env.readFile("test.txt");
assert(
"readFile returns written content",
content === "hello from Flue adapter"
);
const stat = await env.stat("test.txt");
assert("stat isFile", stat.isFile === true);
assert("stat size", stat.size === "hello from Flue adapter".length);
assert("exists true", (await env.exists("test.txt")) === true);
assert("exists false for missing", (await env.exists("nope.txt")) === false);
console.log("\n=== Directory operations ===");
await env.mkdir("subdir", { recursive: true });
await env.writeFile("subdir/a.ts", "export const a = 1;");
await env.writeFile("subdir/b.ts", "export const b = 2;");
const entries = await env.readdir("subdir");
assert(
"readdir returns names",
entries.length === 2 && entries.includes("a.ts")
);
await env.rm("subdir/b.ts");
const after = await env.readdir("subdir");
assert("rm removes file", after.length === 1 && after[0] === "a.ts");
await env.rm("subdir", { recursive: true });
assert("rm recursive removes dir", (await env.exists("subdir")) === false);
console.log("\n=== Shell exec ===");
const echoRes = await env.exec("echo 'adapter shell works'");
assert("exec echo exit code", echoRes.exitCode === 0);
assert("exec echo stdout", echoRes.stdout.trim() === "adapter shell works");
const pipeRes = await env.exec("echo 'hello' | tr a-z A-Z");
assert("exec pipe", pipeRes.stdout.trim() === "HELLO");
const lsRes = await env.exec("ls", { cwd: "/workspace" });
assert("exec with cwd", lsRes.stdout.includes("test.txt"));
const envRes = await env.exec("echo $TEST_VAR", {
env: { TEST_VAR: "injected" },
});
assert("exec with env", envRes.stdout.trim() === "injected");
console.log(`\n=== ${pass} passed, ${fail} failed ===`);
if (fail > 0) {
process.exit(1);
}
};
try {
await main();
} catch (error) {
console.error(error);
process.exit(1);
}

View File

@@ -1,142 +0,0 @@
/**
* Reference: agentOS VM as a sandbox backend for Flue.
*
* This script demonstrates the core idea behind a Flue sandbox adapter that
* delegates file/shell operations to an agentOS VM. It does NOT wire into the
* Flue agent yet — it proves the primitives work end-to-end so you can see
* exactly how the adapter will map calls.
*
* Run: bun --env-file=../../.env packages/agents/scripts/agentos-sandbox-ref.ts
*
* Architecture:
*
* Flue agent (host) agentOS VM (isolated Wasm+V8)
* ┌─────────────────────┐ ┌──────────────────────┐
* │ defineAgent(...) │ │ Linux-like sandbox │
* │ sandbox: agentOs()│── readFile ──► │ persistent FS │
* │ │── writeFile ─► │ shell (sh, coreutils)│
* │ │── exec ──────► │ ~6ms cold start │
* └─────────────────────┘ └──────────────────────┘
*
* The Flue SandboxApi maps 1:1 to AgentOs methods:
*
* Flue SandboxApi AgentOs (core SDK)
* ───────────────────────── ──────────────────────────
* readFile(path) vm.readFile(path)
* readFileBuffer(path) vm.readFile(path)
* writeFile(path, content) vm.writeFile(path, content)
* stat(path) vm.stat(path)
* readdir(path) vm.readdir(path)
* exists(path) vm.exists(path)
* mkdir(path) vm.mkdir(path)
* rm(path) vm.remove(path)
* exec(command, opts) vm.exec(command, opts)
*/
import { AgentOs } from "@rivet-dev/agentos-core";
import type { VirtualStat } from "@rivet-dev/agentos-core";
const formatStat = (stat: VirtualStat): string =>
JSON.stringify({
isDirectory: stat.isDirectory,
isSymbolicLink: stat.isSymbolicLink,
mtime: new Date(stat.mtimeMs).toISOString(),
size: stat.size,
});
const main = async () => {
console.log("=== Booting agentOS VM ===\n");
// AgentOs.create() boots a local VM with the default software bundle
// (sh + coreutils). The VM sleeps when idle and wakes on the next action.
const vm = await AgentOs.create();
console.log("VM booted.\n");
// ── File operations ──────────────────────────────────────────────
console.log("=== writeFile ===");
await vm.writeFile("/workspace/hello.txt", "Hello from agentOS VM!");
console.log("wrote /workspace/hello.txt\n");
console.log("=== readFile ===");
const content = await vm.readFile("/workspace/hello.txt");
console.log("content:", new TextDecoder().decode(content), "\n");
console.log("=== stat ===");
const stat = await vm.stat("/workspace/hello.txt");
console.log("stat:", formatStat(stat), "\n");
console.log("=== exists ===");
console.log(
"exists /workspace/hello.txt:",
await vm.exists("/workspace/hello.txt")
);
console.log(
"exists /workspace/nope.txt:",
await vm.exists("/workspace/nope.txt"),
"\n"
);
console.log("=== mkdir + readdir ===");
await vm.mkdir("/workspace/src", { recursive: true });
await vm.writeFile("/workspace/src/a.ts", "export const a = 1;");
await vm.writeFile("/workspace/src/b.ts", "export const b = 2;");
console.log(
"readdir /workspace/src:",
await vm.readdir("/workspace/src"),
"\n"
);
// ── Shell exec ───────────────────────────────────────────────────
console.log("=== exec: echo ===");
const echoResult = await vm.exec("echo 'shell works!'");
console.log(
"stdout:",
echoResult.stdout.trim(),
`(exit ${echoResult.exitCode})\n`
);
console.log("=== exec: pipe + coreutils ===");
const pipeResult = await vm.exec("echo 'hello world' | tr a-z A-Z | wc -w");
console.log(
"stdout:",
pipeResult.stdout.trim(),
`(exit ${pipeResult.exitCode})\n`
);
console.log("=== exec: with cwd + env ===");
await vm.mkdir("/workspace/project", { recursive: true });
await vm.writeFile("/workspace/project/file.txt", "data");
const cwdResult = await vm.exec("pwd && ls", {
cwd: "/workspace/project",
env: { CUSTOM_VAR: "from-env" },
});
console.log(
"stdout:",
cwdResult.stdout.trim(),
`(exit ${cwdResult.exitCode})\n`
);
// ── Remove ───────────────────────────────────────────────────────
console.log("=== remove ===");
await vm.remove("/workspace/src/b.ts");
console.log(
"after remove, readdir:",
await vm.readdir("/workspace/src"),
"\n"
);
// ── Cleanup ──────────────────────────────────────────────────────
await vm.dispose();
console.log("=== VM disposed. All primitives work. ===");
};
try {
await main();
} catch (error) {
console.error(error);
process.exit(1);
}

View File

@@ -1,223 +0,0 @@
import { exec, execFile } from "node:child_process";
import { promisify } from "node:util";
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { parseAgentEnv } from "@code/env/agent";
import { defineAction } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import * as v from "valibot";
import {
createGiteaHttpTransport,
runPostRunGiteaLifecycle,
} from "../git/gitea";
import { AgentOsSandboxApi } from "../sandboxes/agent-os";
import {
clonePublicRepository,
mirrorSandboxToHostCheckout,
} from "../sandboxes/host-repository-bridge";
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
const GIT_OUTPUT_LIMIT_BYTES = 8 * 1024 * 1024;
const createHostGitRunner = () => ({
async run(
command: string,
options?: { cwd?: string; env?: Record<string, string> }
) {
try {
const result = await execAsync(command, {
cwd: options?.cwd,
env: options?.env,
maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
});
return {
exitCode: 0,
stderr: String(result.stderr),
stdout: String(result.stdout),
};
} catch (error) {
const failure = error as Error & {
readonly code?: number;
readonly stderr?: string;
readonly stdout?: string;
};
return {
exitCode:
typeof failure.code === "number" && failure.code > 0
? failure.code
: 1,
stderr: failure.stderr ?? failure.message,
stdout: failure.stdout ?? "",
};
}
},
});
const makeAuthenticatedRepositoryUrl = (
repositoryUrl: string,
repositoryPath: string,
token: string
): string => {
const [owner] = repositoryPath.split("/");
if (!owner) {
throw new Error("Gitea repository path has no owner");
}
const url = new URL(repositoryUrl);
url.username = owner;
url.password = token;
return url.toString();
};
const pullRequestOutput = v.object({
baseBranch: v.string(),
branch: v.string(),
number: v.number(),
status: v.picklist(["open", "closed", "merged"]),
url: v.string(),
});
const output = v.object({
baseBranch: v.string(),
branch: v.string(),
commitSha: v.optional(v.string()),
pullRequest: v.optional(pullRequestOutput),
status: v.picklist([
"no_changes",
"committed",
"pushed",
"pull_request_open",
"failed",
]),
});
export const createFinalizeGiteaLifecycle = (
issueAgentId: string,
runtimeEnv: Record<string, string | undefined>
) => {
const env = parseAgentEnv(runtimeEnv);
const client = new ConvexHttpClient(env.CONVEX_URL);
const issueId = issueAgentId as Id<"projectIssues">;
return defineAction({
description:
"After verification, inspect the issue workspace, commit and push its work branch, and create an open Gitea pull request. Never merge.",
input: v.object({
commitMessage: v.optional(v.pipe(v.string(), v.maxLength(120))),
verified: v.boolean(),
}),
name: "finalize_gitea_lifecycle",
output,
async run({ input, log }) {
const context = await client.query(api.agentWorkspace.get, {
issueId,
token: env.FLUE_DB_TOKEN,
});
if (!context.source) {
throw new Error("Project has no Git source configured");
}
if (!context.source.defaultBranch) {
throw new Error("Project Git source has no default branch");
}
if (!env.GITEA_TOKEN) {
throw new Error(
"GITEA_TOKEN is required for Gitea pull request creation"
);
}
if (!context.run) {
throw new Error("Project work run is not initialized");
}
const sandbox = new AgentOsSandboxApi(
client,
env.DAEMON_ID,
context.run.actorKey
);
const checkout = await clonePublicRepository({
branchName:
context.run.branchName ?? `work/issue-${context.issue.number}`,
repositoryUrl: context.source.url,
});
const runner = createHostGitRunner();
const transport = createGiteaHttpTransport({
baseUrl: env.GITEA_URL,
token: env.GITEA_TOKEN,
});
try {
await mirrorSandboxToHostCheckout({
checkoutDirectory: checkout.checkoutDirectory,
sandbox,
sandboxDirectory: context.run.checkoutPath ?? "/workspace/repository",
});
await execFileAsync(
"git",
[
"remote",
"set-url",
"origin",
makeAuthenticatedRepositoryUrl(
context.source.url,
context.source.repositoryPath,
env.GITEA_TOKEN
),
],
{
cwd: checkout.checkoutDirectory,
maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
}
);
const result = await runPostRunGiteaLifecycle({
baseBranch: context.source.defaultBranch,
body: `Verified changes for project issue #${context.issue.number}. Merge remains a manual review action.`,
commitMessage: input.commitMessage,
issueNumber: context.issue.number,
issueTitle: context.issue.title,
repositoryPath: context.source.repositoryPath,
runner,
title: `Issue #${context.issue.number}: ${context.issue.title}`,
transport,
verification: input.verified ? "passed" : "failed",
workspace: checkout.checkoutDirectory,
});
await client.mutation(api.agentWorkspace.recordGiteaLifecycle, {
baseBranch: result.baseBranch,
branch: result.branch,
...(result.commitSha === undefined
? {}
: { commitSha: result.commitSha }),
issueId,
...(result.pullRequest === undefined
? {}
: { pullRequest: result.pullRequest }),
status: result.status,
token: env.FLUE_DB_TOKEN,
});
log.info("Gitea lifecycle completed", {
branch: result.branch,
status: result.status,
});
return result;
} catch (error) {
const branchResult = await runner.run("git branch --show-current", {
cwd: checkout.checkoutDirectory,
});
const branch = branchResult.stdout.trim() || "unknown";
const message = error instanceof Error ? error.message : String(error);
await client.mutation(api.agentWorkspace.recordGiteaLifecycle, {
baseBranch: context.source.defaultBranch,
branch,
error: message,
issueId,
status: "failed",
token: env.FLUE_DB_TOKEN,
});
throw error;
} finally {
await checkout.cleanup();
}
},
});
};

View File

@@ -1,32 +0,0 @@
import { parseAgentEnv } from "@code/env/agent";
import { defineAgent } from "@flue/runtime";
import type { AgentRouteHandler } from "@flue/runtime";
import { createFinalizeGiteaLifecycle } from "../actions/finalize-gitea-lifecycle";
import { agentOs } from "../sandboxes/agent-os";
import { createProjectTools } from "../tools/project";
export const description =
"Works one repository issue inside an isolated AgentOS workspace.";
export const route: AgentRouteHandler = (_context, next) => next();
export default defineAgent(({ env, id }) => {
const { AGENT_MODEL_NAME, AGENT_MODEL_PROVIDER } = parseAgentEnv(env);
return {
actions: [createFinalizeGiteaLifecycle(id, env)],
cwd: "/workspace/repository",
description,
instructions: `You are the issue-scoped project manager and coding agent.
Start every run by calling lookup_issue_context, reading /workspace/control/issue.md, the canonical context files under /workspace/control/context, and the operational artifacts under /workspace/control/artifacts. Call report_work_status with working before editing.
Work only on the bound issue. The repository checkout is the current working directory; inspect existing source files before changing them. Git metadata stays on the trusted host bridge, so do not run git commands inside AgentOS—the final lifecycle action mirrors verified files into the host checkout before committing and pushing. If a missing product decision makes safe progress impossible, publish the current work.md and steps.md, report needs-input, then ask one focused question. Otherwise implement the complete issue, run the relevant install, edit, test, or scenario command in AgentOS, and preserve command evidence.
Before finishing, update the operational files under /workspace/control/artifacts and publish each changed canonical artifact with publish_project_artifact. After verification, call finalize_gitea_lifecycle with verified=true; it owns the post-run Git/Gitea lifecycle and never merges. Report completed only after that action succeeds or reports no_changes. On an unrecoverable error, report failed with the exact blocker. Never claim a repository change or command result you did not observe.`,
model: `${AGENT_MODEL_PROVIDER}/${AGENT_MODEL_NAME}`,
sandbox: agentOs(env),
tools: createProjectTools(id, env),
};
});

View File

@@ -1,51 +0,0 @@
import { parseAgentEnv } from "@code/env/agent";
import { defineAgent } from "@flue/runtime";
import { local } from "@flue/runtime/node";
import { createGitRemoteTools, makeGitRemoteConfig } from "../tools/git-remote";
import { createWorkflowTools } from "../tools/workflow";
const INSTRUCTIONS = `You are Zopu Dev, the development agent for the canonical zopu-code repository (self-hosted Gitea: puter/zopu-code).
## Your job
You talk with the user and turn agreed-upon work into tracked issues, then kick off autonomous implementation. You operate on exactly one repository.
## Loop
1. Understand the request. Ask one focused clarifying question only when genuinely ambiguous. Do not create work from casual chat.
2. Check for duplicates. Call list_issues to see what already exists.
3. Create the issue. Call create_issue with a clear title and a body that captures the acceptance criteria. Report the issue number and URL back to the user.
4. Start work only on explicit confirmation. When the user says to start (e.g. "go", "start", "work on it"), call start_workflow with the issue number. This spins up a Codex agent in an isolated worktree that implements, verifies, commits, and opens a pull request.
5. Report outcomes plainly: "Created issue #N: <title> — <url>" and "Started run <id> (status <status>)".
## Rules
- Never invent issue numbers. Always create or list first.
- Never start work without explicit user confirmation.
- Titles are concise; bodies carry the acceptance criteria.
- If a tool returns an error with a reason, surface it and suggest next steps instead of retrying blindly.`;
export default defineAgent(({ env }) => {
const agentEnv = parseAgentEnv(env);
const gitConfig = makeGitRemoteConfig(agentEnv);
return {
description:
"Development agent that creates issues on the canonical zopu-code repo and starts autonomous Codex work runs.",
instructions: INSTRUCTIONS,
model: `${agentEnv.AGENT_MODEL_PROVIDER}/${agentEnv.AGENT_MODEL_NAME}`,
sandbox: local({ cwd: process.cwd() }),
tools: [
...createGitRemoteTools(gitConfig),
...createWorkflowTools({
convexUrl: agentEnv.CONVEX_URL,
token: agentEnv.FLUE_DB_TOKEN,
}),
],
};
});

View File

@@ -49,8 +49,8 @@ When a user sends a message, follow this decision flow:
- Proposed Work is the only Work status in this slice.`;
export {
authenticatedAgentRoute as attachments,
authenticatedAgentRoute as route,
convexAgentRoute as attachments,
convexAgentRoute as route,
} from "../auth";
export default defineAgent(({ env, id }) => {

View File

@@ -3,8 +3,6 @@ import { registerProvider } from "@flue/runtime";
import { flue } from "@flue/runtime/routing";
import { Hono } from "hono";
import { projectRequestRoute } from "./project-request";
const agentEnv = parseAgentEnv(process.env);
registerProvider(agentEnv.AGENT_MODEL_PROVIDER, {
@@ -27,7 +25,6 @@ registerProvider(agentEnv.AGENT_MODEL_PROVIDER, {
});
const app = new Hono();
app.post("/project-requests", projectRequestRoute);
app.route("/", flue() as unknown as Hono);
export default app;

View File

@@ -1,321 +1,18 @@
/**
* Authenticated Flue route middleware for the organization-scoped global agent.
*
* Every request to the Zopu agent routes through here. The middleware:
*
* 1. Requires a Bearer access token (the Better Auth/Convex JWT).
* 2. Creates a fresh, request-scoped {@link ConvexHttpClient} and sets the
* token on it — never on a shared/global client. Auth is per-request.
* 3. Resolves (ensuring) the caller's current personal organization.
* 4. Requires the agent instance id (`:id`) to equal that organization id, so
* one organization cannot use or observe another's agent instance.
* 5. Authorizes GET/SSE observation routes as strictly as POST.
* 6. For POST only: captures exact user-message evidence *before* Flue
* admission (`beginUserMessage`, status `admitting`), then patches it to
* `admitted` with the Flue receipt submission id, or `failed` on error.
* Observation requests (GET/HEAD) never create evidence.
*
* The organization id, conversation id, message id, role, and timestamp are
* never trusted from the client or an agent tool — they are resolved
* server-side. Only the raw message text travels from the user, and it is
* stored verbatim (never trimmed or rewritten).
*/
import { parseAgentEnv } from "@code/env/agent";
import type { AgentRouteHandler } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import { makeFunctionReference } from "convex/server";
// ---------------------------------------------------------------------------
// Typed function references (no generated backend bindings imported).
// ---------------------------------------------------------------------------
/** Only Convex may invoke or observe the organization-scoped Flue agent. */
export const convexAgentRoute: AgentRouteHandler = async (context, next) => {
const env = parseAgentEnv(process.env);
const authorization = context.req.header("authorization");
if (authorization !== `Bearer ${env.FLUE_DB_TOKEN}`) {
return context.json({ error: "Unauthorized" }, 401);
}
interface OrganizationView {
readonly _id: string;
readonly _creationTime: number;
readonly name: string;
readonly kind: "personal" | "team";
readonly createdBy: string;
readonly createdAt: number;
}
const organizationId = context.req.header("x-zopu-organization-id");
if (!organizationId || organizationId !== context.req.param("id")) {
return context.json({ error: "Forbidden" }, 403);
}
interface ConversationMessageView {
readonly _id: string;
readonly _creationTime: number;
readonly organizationId: string;
readonly conversationId: string;
readonly messageId: string;
readonly submissionId: string | null;
readonly clientRequestId: string;
readonly role: "user";
readonly rawText: string;
readonly status: "admitting" | "admitted" | "failed";
readonly createdAt: number;
}
const ensurePersonalOrganization = makeFunctionReference<
"mutation",
Record<string, never>,
OrganizationView
>("organizations:ensurePersonalOrganization");
const beginUserMessage = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly clientRequestId: string;
readonly rawText: string;
},
ConversationMessageView
>("conversationMessages:beginUserMessage");
const markAdmitted = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly clientRequestId: string;
readonly submissionId: string;
},
ConversationMessageView
>("conversationMessages:markAdmitted");
const markFailed = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly clientRequestId: string;
},
ConversationMessageView
>("conversationMessages:markFailed");
// ---------------------------------------------------------------------------
// Request-scoped authenticated Convex client.
// ---------------------------------------------------------------------------
const { CONVEX_URL } = parseAgentEnv(process.env);
/**
* A short-lived authenticated Convex client bound to one HTTP request. The
* caller's JWT is set on this instance only and discarded when the request
* ends. We never mutate auth on a shared/global Convex client.
*/
export const createAuthenticatedClient = (
accessToken: string
): ConvexHttpClient => {
const client = new ConvexHttpClient(CONVEX_URL);
client.setAuth(accessToken);
return client;
};
/**
* Minimal structural shape the header helpers read from an incoming request.
* Using this avoids a structural clash between the global (Bun) `Request`/
* `Headers` and the undici types that Hono's context exposes, while staying
* type-safe.
*/
interface HeaderSource {
readonly headers: {
readonly get: (name: string) => string | null;
};
}
/**
* Extract and validate the Bearer access token from the request. Returns null
* when absent or malformed so the caller can produce a clean 401.
*/
export const extractBearerToken = (request: HeaderSource): string | null => {
const header = request.headers.get("authorization");
if (!header) {
return null;
}
const match = /^Bearer\s+(?<token>\S+)$/u.exec(header);
return match?.groups?.token ?? null;
};
/**
* Read the stable per-send request id supplied by the web client. This is
* generated once when the user sends a message and reused across fetch/stream
* retries, so it is a reliable idempotency key for evidence capture.
*/
const extractClientRequestId = (request: HeaderSource): string | null => {
const header = request.headers.get("x-zopu-request-id");
if (!header || header.length === 0) {
return null;
}
return header;
};
/**
* Safely parse the direct agent payload to extract the exact user message
* text. Mirrors Flue's `DirectAgentPayload` shape `{ message, images? }`.
* Returns null for non-JSON or missing `message` so the request is rejected
* with 400 rather than crashing the middleware.
*/
const extractMessageText = async (
request: HeaderSource & { readonly json: () => Promise<unknown> }
): Promise<string | null> => {
const contentType = request.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
return null;
}
try {
const body = (await request.json()) as unknown;
if (
typeof body !== "object" ||
body === null ||
!("message" in body) ||
typeof (body as { message?: unknown }).message !== "string"
) {
return null;
}
return (body as { message: string }).message;
} catch {
return null;
}
};
/**
* Read the Flue admission receipt submission id from the response Flue
* produced after `next()`. The response body is `202 { streamUrl, offset,
* submissionId }`. Returns null when the body has no submission id (e.g. an
* error response).
*/
const extractSubmissionId = async (
response: HeaderSource & {
readonly clone: () => { readonly json: () => Promise<unknown> };
}
): Promise<string | null> => {
const contentType = response.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
return null;
}
try {
const body = (await response.clone().json()) as unknown;
if (
typeof body === "object" &&
body !== null &&
"submissionId" in body &&
typeof (body as { submissionId?: unknown }).submissionId === "string"
) {
return (body as { submissionId: string }).submissionId;
}
} catch {
// Non-JSON or unreadable body: no submission id to record.
}
return null;
};
/**
* Admit a direct submission through Flue and record the admission outcome on
* the normalized evidence row. On admission failure, the evidence is marked
* failed and the original error is rethrown — never swallowed. On success,
* the Flue receipt submission id (if present) patches the evidence to
* admitted.
*/
const admitAndRecordEvidence = async (
continueAdmission: () => Promise<void>,
client: ConvexHttpClient,
getResponse: () => Response | undefined,
evidence: {
readonly organizationId: string;
readonly clientRequestId: string;
}
): Promise<void> => {
try {
await continueAdmission();
} catch (error) {
try {
await client.mutation(markFailed, evidence);
} catch {
// Best-effort: the original error is the primary concern.
}
throw error;
}
// Patch the evidence with the Flue receipt submission id. If the response
// carries no submission id (unexpected), leave the evidence in its begun
// state rather than guessing.
const response = getResponse();
if (!response) {
return;
}
const submissionId = await extractSubmissionId(response);
if (!submissionId) {
return;
}
try {
await client.mutation(markAdmitted, {
...evidence,
submissionId,
});
} catch {
// Best-effort: the admission already succeeded and the response is
// finalized. A failure to patch metadata must not break the request.
}
};
/**
* The authenticated Flue route middleware. Authorizes every method, and for
* POST captures normalized user-message evidence around Flue admission.
*/
export const authenticatedAgentRoute: AgentRouteHandler = async (c, next) => {
const accessToken = extractBearerToken(c.req.raw);
if (!accessToken) {
return c.json({ error: "Unauthorized" }, 401);
}
const client = createAuthenticatedClient(accessToken);
// Resolve (ensuring) the caller's current personal organization.
let organization: OrganizationView;
try {
organization = await client.mutation(ensurePersonalOrganization, {});
} catch {
return c.json({ error: "Unauthorized" }, 401);
}
// The agent instance id must be the caller's organization id. This is the
// hard tenancy boundary: one organization cannot use or observe another's
// agent instance.
const instanceId = c.req.param("id") ?? "";
if (instanceId !== organization._id) {
return c.json({ error: "Forbidden" }, 403);
}
// Observation routes (GET/HEAD) are authorized but never create evidence.
if (c.req.method !== "POST") {
return next();
}
// --- Evidence capture (POST only) -------------------------------------
const clientRequestId = extractClientRequestId(c.req.raw);
const messageText = await extractMessageText(c.req.raw.clone());
if (!clientRequestId) {
return c.json({ error: "Missing x-zopu-request-id" }, 400);
}
if (messageText === null) {
return c.json({ error: "Invalid message payload" }, 400);
}
// Begin evidence before Flue admission so the message is durable even if
// admission fails or the process is interrupted.
try {
await client.mutation(beginUserMessage, {
clientRequestId,
organizationId: organization._id,
rawText: messageText,
});
} catch {
return c.json({ error: "Evidence capture failed" }, 500);
}
// Admit through Flue. After next(), c.res holds the admission response.
// Evidence is patched from the admission receipt, or marked failed without
// swallowing the original error.
await admitAndRecordEvidence(next, client, () => c.res, {
clientRequestId,
organizationId: organization._id,
});
return c.res;
return await next().then(() => context.res);
};

View File

@@ -1,155 +0,0 @@
import { describe, expect, test } from "vitest";
import { createGiteaHttpTransport, runPostRunGiteaLifecycle } from "./gitea";
import type { GitCommandRunner, GiteaTransport } from "./gitea";
const repository = {
cloneUrl: "https://git.openputer.com/puter/zopu-code.git",
defaultBranch: "main",
htmlUrl: "https://git.openputer.com/puter/zopu-code",
name: "zopu-code",
sshUrl: "ssh://git@git.openputer.com:2222/puter/zopu-code.git",
};
const makeRunner = (): GitCommandRunner & { readonly commands: string[] } => {
const commands: string[] = [];
let statusCalls = 0;
return {
commands,
run(command) {
commands.push(command);
if (command === "git branch --show-current") {
return Promise.resolve({
exitCode: 0,
stderr: "",
stdout: "work/issue-5\n",
});
}
if (command === "git status --porcelain=v1") {
statusCalls += 1;
return Promise.resolve({
exitCode: 0,
stderr: "",
stdout: statusCalls === 1 ? " M src/gitea.ts\n" : "",
});
}
if (command === "git diff --no-ext-diff --binary") {
return Promise.resolve({
exitCode: 0,
stderr: "",
stdout: "diff --git ...",
});
}
if (command === "git rev-parse HEAD") {
return Promise.resolve({
exitCode: 0,
stderr: "",
stdout: "abc123\n",
});
}
if (command.includes("git status --porcelain=v1")) {
return Promise.resolve({ exitCode: 0, stderr: "", stdout: "" });
}
return Promise.resolve({ exitCode: 0, stderr: "", stdout: "" });
},
};
};
describe("Gitea lifecycle adapter", () => {
test("inspects, commits, pushes, and creates an open PR through mocked boundaries", async () => {
const runner = makeRunner();
const pullRequests: unknown[] = [];
const transport: GiteaTransport = {
createPullRequest(input) {
pullRequests.push(input);
return Promise.resolve({
base: { ref: input.base },
head: { ref: input.head },
htmlUrl: "https://git.openputer.com/puter/zopu-code/pulls/5",
number: 5,
state: "open",
});
},
getRepository() {
return Promise.resolve(repository);
},
};
const result = await runPostRunGiteaLifecycle({
baseBranch: "main",
body: "Generated by the verified project run.",
issueNumber: 5,
issueTitle: "Publish verified changes",
repositoryPath: "puter/zopu-code",
runner,
transport,
verification: "passed",
workspace: "/workspace",
});
expect(result).toMatchObject({
branch: "work/issue-5",
commitSha: "abc123",
pullRequest: {
baseBranch: "main",
branch: "work/issue-5",
number: 5,
status: "open",
},
status: "pull_request_open",
});
expect(runner.commands).toEqual([
"git branch --show-current",
"git status --porcelain=v1",
"git diff --no-ext-diff --binary",
"git add --all && git commit -m 'feat(issue-5): Publish verified changes'",
"git rev-parse HEAD",
"git status --porcelain=v1",
"git push origin HEAD:'work/issue-5'",
]);
expect(pullRequests).toHaveLength(1);
});
test("mocks the HTTP Gitea boundary without calling the network", async () => {
const requests: Request[] = [];
const transport = createGiteaHttpTransport({
baseUrl: "https://git.openputer.com",
fetch: (input, init) => {
const request = new Request(String(input), init);
requests.push(request);
return Promise.resolve(
new Response(
request.method === "GET"
? JSON.stringify(repository)
: JSON.stringify({
base: { ref: "main" },
head: { ref: "work/issue-5" },
html_url: "https://git.openputer.com/puter/zopu-code/pulls/5",
number: 5,
state: "open",
}),
{ headers: { "content-type": "application/json" } }
)
);
},
token: "scoped-test-token",
});
await transport.getRepository("puter/zopu-code");
await transport.createPullRequest({
base: "main",
body: "body",
head: "work/issue-5",
repositoryPath: "puter/zopu-code",
title: "title",
});
expect(requests).toHaveLength(2);
expect(requests[0]?.url).toBe(
"https://git.openputer.com/api/v1/repos/puter/zopu-code"
);
expect(requests[1]?.headers.get("authorization")).toBe(
"token scoped-test-token"
);
});
});

View File

@@ -1,307 +0,0 @@
import {
decideGitLifecycle,
GitLifecycleError,
inspectGitWorkspace,
makeCommitMessage,
validatePullRequestMetadata,
} from "@code/primitives/git";
import type {
GitLifecycleDecisionResult,
GitLifecycleResult,
GitWorkspaceInspection,
} from "@code/primitives/git";
import { Effect } from "effect";
export interface GitCommandResult {
readonly exitCode: number;
readonly stderr: string;
readonly stdout: string;
}
export interface GitCommandRunner {
readonly run: (
command: string,
options?: {
readonly cwd?: string;
readonly env?: Record<string, string>;
}
) => Promise<GitCommandResult>;
}
export interface GiteaRepository {
readonly cloneUrl: string;
readonly defaultBranch: string;
readonly htmlUrl: string;
readonly name: string;
readonly sshUrl: string;
}
export interface GiteaPullRequest {
readonly base: { readonly ref: string };
readonly head: { readonly ref: string };
readonly htmlUrl: string;
readonly number: number;
readonly state: "open" | "closed" | "merged";
}
export interface GiteaTransport {
readonly createPullRequest: (input: {
readonly base: string;
readonly body: string;
readonly head: string;
readonly repositoryPath: string;
readonly title: string;
}) => Promise<GiteaPullRequest>;
readonly getRepository: (repositoryPath: string) => Promise<GiteaRepository>;
}
export interface GiteaHttpTransportOptions {
readonly baseUrl: string;
readonly fetch?: (
input: string | URL | Request,
init?: RequestInit
) => Promise<Response>;
readonly token: string;
}
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'"'"'`)}'`;
const providerFailure = (
message: string,
reason: "CommandFailed" | "RemoteRejected"
) => new GitLifecycleError({ message, reason });
const runChecked = async (
runner: GitCommandRunner,
command: string,
options?: Parameters<GitCommandRunner["run"]>[1]
): Promise<string> => {
let result: GitCommandResult;
try {
result = await runner.run(command, options);
} catch (error) {
throw new GitLifecycleError({
message: `Git command could not run: ${
error instanceof Error ? error.message : String(error)
}`,
reason: "CommandFailed",
});
}
if (result.exitCode !== 0) {
throw providerFailure(
result.stderr.trim() || `Git command failed: ${command}`,
command.startsWith("git push") ? "RemoteRejected" : "CommandFailed"
);
}
return result.stdout;
};
const toHttpPath = (repositoryPath: string): string =>
repositoryPath
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
const requestJson = async <T>(
options: GiteaHttpTransportOptions,
path: string,
init?: RequestInit
): Promise<T> => {
let response: Response;
try {
response = await (options.fetch ?? globalThis.fetch)(
`${options.baseUrl.replace(/\/$/u, "")}${path}`,
{
...init,
headers: {
Accept: "application/json",
Authorization: `token ${options.token}`,
"Content-Type": "application/json",
...init?.headers,
},
}
);
} catch (error) {
throw new GitLifecycleError({
message: `Gitea request could not run: ${
error instanceof Error ? error.message : String(error)
}`,
reason: "RequestFailed",
});
}
if (!response.ok) {
const detail = await response.text();
throw new GitLifecycleError({
message: `Gitea request failed (${response.status}): ${detail}`,
reason:
response.status === 401 || response.status === 403
? "Authentication"
: "RequestFailed",
});
}
return (await response.json()) as T;
};
export const createGiteaHttpTransport = (
options: GiteaHttpTransportOptions
): GiteaTransport => ({
async createPullRequest(input) {
const response = await requestJson<{
base: { ref: string };
head: { ref: string };
html_url: string;
number: number;
state: "open" | "closed" | "merged";
}>(options, `/api/v1/repos/${toHttpPath(input.repositoryPath)}/pulls`, {
body: JSON.stringify({
base: input.base,
body: input.body,
head: input.head,
title: input.title,
}),
method: "POST",
});
return {
base: response.base,
head: response.head,
htmlUrl: response.html_url,
number: response.number,
state: response.state,
};
},
async getRepository(repositoryPath) {
const response = await requestJson<{
clone_url: string;
default_branch: string;
html_url: string;
name: string;
ssh_url: string;
}>(options, `/api/v1/repos/${toHttpPath(repositoryPath)}`);
return {
cloneUrl: response.clone_url,
defaultBranch: response.default_branch,
htmlUrl: response.html_url,
name: response.name,
sshUrl: response.ssh_url,
};
},
});
export interface RunPostRunGiteaLifecycleInput {
readonly baseBranch: string;
readonly body: string;
readonly commitMessage?: string;
readonly issueNumber: number;
readonly issueTitle: string;
readonly repositoryPath: string;
readonly runner: GitCommandRunner;
readonly title?: string;
readonly transport: GiteaTransport;
readonly verification: "passed" | "failed" | "not-run";
readonly workspace: string;
}
const inspect = async (
input: RunPostRunGiteaLifecycleInput
): Promise<GitWorkspaceInspection> => {
const [branch, status, diff] = await Promise.all([
runChecked(input.runner, "git branch --show-current", {
cwd: input.workspace,
}),
runChecked(input.runner, "git status --porcelain=v1", {
cwd: input.workspace,
}),
runChecked(input.runner, "git diff --no-ext-diff --binary", {
cwd: input.workspace,
}),
]);
return await Effect.runPromise(
inspectGitWorkspace({
branch: branch.trim(),
diff,
status,
})
);
};
export const runPostRunGiteaLifecycle = async (
input: RunPostRunGiteaLifecycleInput
): Promise<GitLifecycleResult> => {
const inspection = await inspect(input);
const initialDecision = (await Effect.runPromise(
decideGitLifecycle({
baseBranch: input.baseBranch,
inspection,
pushed: false,
verification: input.verification,
})
)) as GitLifecycleDecisionResult;
if (initialDecision.decision === "finish") {
return {
baseBranch: input.baseBranch as GitLifecycleResult["baseBranch"],
branch: inspection.branch,
commitSha: undefined,
pullRequest: undefined,
status: "no_changes",
};
}
await input.transport.getRepository(input.repositoryPath);
await runChecked(
input.runner,
`git add --all && git commit -m ${shellQuote(
input.commitMessage ??
makeCommitMessage(input.issueNumber, input.issueTitle)
)}`,
{ cwd: input.workspace }
);
const commitOutput = await runChecked(input.runner, "git rev-parse HEAD", {
cwd: input.workspace,
});
const commitSha = commitOutput.trim();
const cleanStatus = await runChecked(
input.runner,
"git status --porcelain=v1",
{ cwd: input.workspace }
);
if (cleanStatus.trim().length > 0) {
throw providerFailure(
"Git workspace remained dirty after commit",
"CommandFailed"
);
}
await runChecked(
input.runner,
`git push origin HEAD:${shellQuote(inspection.branch)}`,
{ cwd: input.workspace }
);
const pullRequest = await input.transport.createPullRequest({
base: input.baseBranch,
body: input.body,
head: inspection.branch,
repositoryPath: input.repositoryPath,
title: input.title ?? `Issue #${input.issueNumber}: ${input.issueTitle}`,
});
const metadata = await Effect.runPromise(
validatePullRequestMetadata({
baseBranch: pullRequest.base.ref,
branch: pullRequest.head.ref,
number: pullRequest.number,
status: pullRequest.state,
url: pullRequest.htmlUrl,
})
);
return {
baseBranch: input.baseBranch as GitLifecycleResult["baseBranch"],
branch: inspection.branch,
commitSha,
pullRequest: metadata,
status: "pull_request_open",
};
};

View File

@@ -1,105 +0,0 @@
# Orb Runtime
One logical execution workspace for one ProjectIssue run. An Orb bundles an AgentOS actor, an OpenCode harness session, a Docker sandbox, a mounted repository workspace, project context, model-gateway configuration, process/log handling, normalized execution events, and a cleanup lifecycle.
## Architecture
```
┌──────────────────────────────────────────────────┐
│ OrbRuntime │
│ creates OrbHandle instances │
├──────────────────────────────────────────────────┤
│ OrbHandle │
│ ┌─────────────┐ ┌────────────────────────┐ │
│ │ AgentOS VM │ │ SandboxAgent + Docker │ │
│ │ (OpenCode │◄──►│ (sandbox-agent server │ │
│ │ ACP agent) │ │ in a Docker container)│ │
│ └─────────────┘ └────────────────────────┘ │
│ │ │ │
│ session events runProcess / │
│ → normalized createProcess │
│ OrbEvent │
└──────────────────────────────────────────────────┘
```
The AgentOS VM runs the OpenCode ACP adapter (lightweight agent loop, session management, durable identity). Heavy execution — package installs, test suites, builds — runs inside a Docker container hosting a sandbox-agent server. The `DockerSandboxProvider` calls `SandboxAgent.start({ sandbox: docker(...) })`, which starts the server in a Docker container with a dynamically-mapped host port and returns a `SandboxAgent` client whose `baseUrl` both the main process and the AgentOS sidecar subprocess reach over `127.0.0.1`. The sandbox filesystem is mounted into the VM at `/mnt/sandbox`.
## Domain model
| Type | Description |
| --- | --- |
| `OrbId` | Branded identifier for one Orb |
| `OrbRunId` | Branded identifier for one run attempt |
| `OrbSessionId` | Branded identifier for one OpenCode session |
| `OrbIdentity` | `{ projectId, runId, workUnitId }` — derives the actor key |
| `OrbState` | `creating → prepared → running → needs-input → completed/failed/cancelled → disposed` |
| `RunState` | `queued → provisioning → preparing → running → verifying → succeeded/failed/cancelled` |
| `OrbEvent` | Normalized, secret-free execution event |
Orb state and run state are separate state machines. The VM/sandbox lease state is never conflated with the product work-unit state.
## Tagged errors
| Error | Reasons |
| --- | --- |
| `OrbStateError` | `InvalidTransition`, `AlreadyDisposed`, `NotRunning` |
| `OrbSandboxError` | `DockerUnavailable`, `ContainerStart`, `CommandFailed`, `ContainerCleanup` |
| `OrbSessionError` | `OpenSession`, `PromptFailed`, `AgentNotInstalled`, `SessionNotFound` |
| `OrbConfigurationError` | `MissingGateway`, `MissingIdentity`, `InvalidModelConfig` |
## Environment variables
| Variable | Required | Description |
| --- | --- | --- |
| `ORB_PROOF` | Proof only | Set to `1` to run the proof fixture |
| `ORB_GATEWAY_API_KEY` | Proof only | Model gateway API key |
| `ORB_GATEWAY_BASE_URL` | Proof only | Model gateway base URL (OpenAI-compatible `/v1`) |
| `ORB_GATEWAY_MODEL` | Proof only | Model name |
| `ORB_GATEWAY_PROVIDER` | Proof only | Provider identifier |
| `ORB_DOCKER_IMAGE` | Optional | Docker image (default: `oven/bun:1.3-debian`) |
| `ORB_DOCKER_WORKSPACE` | Optional | Host workspace root (default: `/tmp/orb-workspaces`) |
| `RIVET_ENDPOINT` | Optional | AgentOS/RivetKit sidecar endpoint |
No permanent provider credentials are stored in project files. API keys are injected at runtime via the OpenCode config written to the VM filesystem, and all event output is passed through `redactSecrets`.
## Docker requirements
- Docker daemon running and accessible via the Docker socket (`/var/run/docker.sock`)
- The sandbox uses `rivetdev/sandbox-agent` as its Docker image by default
- The `sandbox-agent/docker` provider creates containers with `AutoRemove` and a dynamically allocated host port
- Writable bind mount is the project workspace only (mounted at `/home/sandbox` inside the container)
- The AgentOS sidecar subprocess reaches the sandbox-agent server over `127.0.0.1:<hostPort>`
## Local startup
```bash
# Run the proof fixture
ORB_PROOF=1 \
ORB_GATEWAY_API_KEY=your-key \
ORB_GATEWAY_BASE_URL=https://ai.example.com/v1 \
ORB_GATEWAY_MODEL=glm-5.2 \
ORB_GATEWAY_PROVIDER=cheaptricks \
bun run scripts/orb-proof.ts
```
Stable markers: `ORB_PROOF_PASSED` (exit 0), `ORB_PROOF_BLOCKED` (exit 2), `ORB_PROOF_FAILED` (exit 1).
## Filesystem layout
```
SandboxAgent container (/home/sandbox = host bind mount)
/home/sandbox/repository/ — project checkout
/home/sandbox/control/ — issue + context files
AgentOS VM (host process)
/mnt/sandbox/ — sandbox mount (via SandboxAgent baseUrl)
/mnt/sandbox/repository/ — repo (via sandbox)
/root/.config/opencode/ — OpenCode config (chmod 600)
```
## Current limitations
- No automatic merge or production deployment capability.
- No multi-region support.
- Interactive PTY sessions are not wired through the sandbox agent.
- The model turn stage depends on a reachable OpenAI-compatible gateway; if the gateway is unreachable the proof reports BLOCKED at that stage but still passes Docker and AgentOS/OpenCode.

View File

@@ -1,109 +0,0 @@
import { Schema } from "effect";
// ---------------------------------------------------------------------------
// Context pack — assembled from ProjectIssue, evidence, project docs, artifacts
// ---------------------------------------------------------------------------
export const ContextFile = Schema.Struct({
content: Schema.String,
label: Schema.String,
});
export type ContextFile = typeof ContextFile.Type;
export const ContextPackInput = Schema.Struct({
artifacts: Schema.Array(
Schema.Struct({
content: Schema.String,
path: Schema.String,
})
),
contextFiles: Schema.Array(ContextFile),
evidence: Schema.Array(
Schema.Struct({
content: Schema.String,
source: Schema.String,
})
),
issueBody: Schema.String,
issueNumber: Schema.Int,
issueTitle: Schema.String,
repositoryMetadata: Schema.Struct({
baseBranch: Schema.String,
repositoryName: Schema.String,
repositoryUrl: Schema.String,
}),
});
export type ContextPackInput = typeof ContextPackInput.Type;
const section = (heading: string, lines: readonly string[]): string => {
if (lines.length === 0) {
return "";
}
return `## ${heading}\n\n${lines.join("\n")}`;
};
const OPERATIONAL_INSTRUCTIONS = `## Operational Instructions
You are working inside an isolated sandbox on a dedicated work branch. The repository checkout is your working directory.
1. Inspect existing source before changing anything.
2. Implement the complete issue scope. Run the project's test or verification command.
3. If you need human input to proceed safely, emit exactly one line starting with \`NEEDS_INPUT:\` followed by your question, then stop.
4. When implementation and verification are complete, emit exactly one line starting with \`WORK_COMPLETE:\` followed by a one-sentence summary, then stop.
5. Do not merge, deploy, or push. The orchestrator handles the Git lifecycle after you signal completion.
6. Never claim a change you did not observe. Preserve command evidence.`;
/**
* Build a concise context pack prompt for the OpenCode session. The pack is
* sent as the first task and includes: issue details, project docs, evidence,
* prior artifacts, repository metadata, and operational instructions with the
* needs-input / work-complete marker protocol.
*/
export const buildContextPack = (input: ContextPackInput): string => {
const parts: string[] = [
`# Issue #${input.issueNumber}: ${input.issueTitle}\n\n${input.issueBody}`,
];
if (input.contextFiles.length > 0) {
parts.push(
section(
"Project Context",
input.contextFiles.map(
(file) => `### ${file.label}\n\n\`\`\`\n${file.content}\n\`\`\``
)
)
);
}
if (input.evidence.length > 0) {
parts.push(
section(
"Supporting Evidence",
input.evidence.map((item) => `- **${item.source}**: ${item.content}`)
)
);
}
if (input.artifacts.length > 0) {
parts.push(
section(
"Previous Work Artifacts",
input.artifacts.map(
(artifact) =>
`### ${artifact.path}\n\n\`\`\`\n${artifact.content}\n\`\`\``
)
)
);
}
parts.push(
section("Repository", [
`- Name: ${input.repositoryMetadata.repositoryName}`,
`- URL: ${input.repositoryMetadata.repositoryUrl}`,
`- Base branch: ${input.repositoryMetadata.baseBranch}`,
]),
OPERATIONAL_INSTRUCTIONS
);
return parts.filter((part) => part.length > 0).join("\n\n---\n\n");
};

View File

@@ -1,170 +0,0 @@
/* eslint-disable no-console -- diagnostic skip messages in a Docker-guarded suite */
import { spawn } from "node:child_process";
import { setTimeout as sleepTimer } from "node:timers/promises";
import { Effect } from "effect";
import { describe, expect, it as vitestIt } from "vitest";
import { DockerSandboxProvider } from "./docker-sandbox";
import { OrbSandboxError } from "./domain";
// Real containers need more than the 5s default; bind a generous timeout here.
const it = (name: string, fn: () => Promise<void>): void => {
vitestIt(name, fn, 60_000);
};
// Node-compatible Docker availability check.
const runCliExit = (args: readonly string[]): Promise<number | null> =>
// eslint-disable-next-line promise/avoid-new -- wrapping one-shot child close in a single promise
new Promise((resolve) => {
const [command = "docker", ...rest] = args;
const proc = spawn(command, rest, {
stdio: ["ignore", "pipe", "pipe"],
});
proc.on("error", () => resolve(null));
proc.on("close", (code) => resolve(code));
});
const dockerAvailable = async (): Promise<boolean> => {
try {
const code = await runCliExit([
"docker",
"version",
"--format",
"{{.Server.Version}}",
]);
return code === 0;
} catch {
return false;
}
};
// Top-level await so describe.skipIf evaluates Docker availability at registration.
const HAVE_DOCKER = await dockerAvailable();
const tmpDir = (): string =>
`/tmp/orb-test-${Date.now()}-${Math.trunc(Math.random() * 1e6)}`;
describe.skipIf(!HAVE_DOCKER)(
"DockerSandboxProvider (SandboxAgent + Docker)",
() => {
it("starts a SandboxAgent server and exposes a reachable baseUrl", async () => {
const provider = await Effect.runPromise(
DockerSandboxProvider.create({
hostWorkspacePath: tmpDir(),
})
);
try {
const client = await provider.start();
expect(provider.isStarted).toBe(true);
// The SandboxAgent client must have a baseUrl property — this is what
// AgentOS serializes so the sidecar can reach the sandbox.
const { baseUrl } = client as unknown as { baseUrl: string };
expect(baseUrl).toBeTruthy();
expect(baseUrl).toMatch(/^https?:\/\//u);
// Run a command to verify the sandbox-agent server actually works.
const result = await client.runProcess({
args: ["-c", "echo hello-orb"],
command: "sh",
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("hello-orb");
} finally {
await provider.dispose();
}
});
it("is idempotent: start returns the same client on repeated calls", async () => {
const provider = await Effect.runPromise(
DockerSandboxProvider.create({
hostWorkspacePath: tmpDir(),
})
);
try {
const c1 = await provider.start();
const c2 = await provider.start();
expect(c1).toBe(c2);
} finally {
await provider.dispose();
}
});
it("disposes cleanly and frees the Docker container", async () => {
const provider = await Effect.runPromise(
DockerSandboxProvider.create({
hostWorkspacePath: tmpDir(),
})
);
await provider.start();
expect(provider.isStarted).toBe(true);
await provider.dispose();
expect(provider.isStarted).toBe(false);
// Give AutoRemove a moment.
// eslint-disable-next-line no-await-in-loop -- single settling wait
await sleepTimer(2000);
// Second dispose is a safe no-op.
await expect(provider.dispose()).resolves.toBeUndefined();
});
it("binds the host workspace into the sandbox container", async () => {
const workspace = tmpDir();
const { spawn: nodeSpawn } = await import("node:child_process");
// eslint-disable-next-line promise/avoid-new -- one-shot shell write
await new Promise<void>((resolve) => {
const p = nodeSpawn(
"sh",
[
"-c",
`mkdir -p ${workspace} && echo proof-file > ${workspace}/marker.txt`,
],
{
stdio: ["ignore", "pipe", "pipe"],
}
);
p.on("close", () => resolve());
});
const provider = await Effect.runPromise(
DockerSandboxProvider.create({
hostWorkspacePath: workspace,
})
);
try {
const client = await provider.start();
const result = await client.runProcess({
args: ["-c", "cat /home/sandbox/marker.txt"],
command: "sh",
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("proof-file");
} finally {
await provider.dispose();
}
});
}
);
describe.skipIf(HAVE_DOCKER)("DockerSandboxProvider without Docker", () => {
it("create fails with DockerUnavailable", async () => {
const error = await Effect.runPromise(
Effect.flip(
DockerSandboxProvider.create({
hostWorkspacePath: "/tmp/orb-test-nodocker",
})
)
);
expect(error).toBeInstanceOf(OrbSandboxError);
expect(error.reason).toBe("DockerUnavailable");
});
});
if (!HAVE_DOCKER) {
console.warn(
"[docker-sandbox.test.ts] Docker daemon unavailable; SandboxAgent tests skipped."
);
}

View File

@@ -1,118 +0,0 @@
import type {
AgentOsSandboxClient,
AgentOsSandboxProvider,
} from "@rivet-dev/agentos-core";
import { Effect } from "effect";
import { OrbSandboxError } from "./domain";
// ---------------------------------------------------------------------------
// Docker sandbox — AgentOsSandboxProvider backed by sandbox-agent + Docker
// ---------------------------------------------------------------------------
//
// AgentOS serializes sandbox mounts through getSerializableClientConfig,
// which reads client.baseUrl and passes it to the sidecar. An in-process
// client object can never satisfy that contract because it has no network
// endpoint. The supported boundary is a standard SandboxAgent client:
//
// SandboxAgent.start({ sandbox: docker({ image, binds }) })
//
// starts a sandbox-agent server inside a Docker container, dynamically maps
// a host port, and returns a SandboxAgent client whose baseUrl the sidecar
// can reach over HTTP on 127.0.0.1:<hostPort>. Both the main process and
// the sidecar subprocess run on the host, so localhost connectivity works.
const SANDBOX_AGENT_IMAGE = "rivetdev/sandbox-agent:0.5.0-rc.2-full";
const DEFAULT_WORKSPACE = "/home/sandbox";
// ---------------------------------------------------------------------------
// DockerSandboxProvider — wraps SandboxAgent.start with the docker provider
// ---------------------------------------------------------------------------
export interface DockerSandboxOptions {
readonly containerName?: string;
readonly hostWorkspacePath: string;
readonly image?: string;
readonly workDir?: string;
}
export class DockerSandboxProvider implements AgentOsSandboxProvider {
private readonly image: string;
private readonly binds: string[];
private client: AgentOsSandboxClient | null = null;
private disposeFn: (() => Promise<void>) | null = null;
constructor(options: DockerSandboxOptions) {
this.image = options.image ?? SANDBOX_AGENT_IMAGE;
// Bind the host workspace read-write into the sandbox container so the
// restricted writable area is the project workspace only.
this.binds = [
`${options.hostWorkspacePath}:${options.workDir ?? DEFAULT_WORKSPACE}`,
];
}
static readonly create = Effect.fn("DockerSandboxProvider.create")(
function* createProvider(options: DockerSandboxOptions) {
// eslint-disable-next-line no-use-before-define -- defined at module bottom
yield* checkDockerAvailable();
return new DockerSandboxProvider(options);
}
);
async start(): Promise<AgentOsSandboxClient> {
if (this.client) {
return this.client;
}
const { SandboxAgent } = await import("sandbox-agent");
const { docker } = await import("sandbox-agent/docker");
const sandboxAgent = await SandboxAgent.start({
sandbox: docker({
binds: this.binds,
image: this.image,
}),
});
this.client = sandboxAgent as unknown as AgentOsSandboxClient;
this.disposeFn = async () => {
// destroySandbox permanently tears down the backing Docker container;
// dispose() alone only closes the HTTP connection.
await sandboxAgent.destroySandbox();
};
return this.client;
}
async dispose(): Promise<void> {
const dispose = this.disposeFn;
this.client = null;
this.disposeFn = null;
if (dispose) {
await dispose();
}
}
get isStarted(): boolean {
return this.client !== null;
}
}
// ---------------------------------------------------------------------------
// Docker availability check
// ---------------------------------------------------------------------------
const checkDockerAvailable = Effect.fn("Docker.checkAvailable")(
function* checkDockerAvailable() {
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Docker is not available: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "DockerUnavailable",
}),
try: async () => {
const { default: Docker } = await import("dockerode");
const docker = new Docker();
await docker.ping();
},
});
}
);

View File

@@ -1,132 +0,0 @@
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import {
orbActorKey,
OrbStateError,
transitionOrbState,
transitionRunState,
} from "./domain";
const runTransition = (from: string, to: string) =>
Effect.runSync(
Effect.flip(transitionOrbState({ from: from as never, to: to as never }))
);
const runTransitionOk = (from: string, to: string) =>
Effect.runSync(transitionOrbState({ from: from as never, to: to as never }));
const runRunState = (from: string, to: string) =>
Effect.runSync(
Effect.flip(transitionRunState({ from: from as never, to: to as never }))
);
const runRunStateOk = (from: string, to: string) =>
Effect.runSync(transitionRunState({ from: from as never, to: to as never }));
describe("orbActorKey", () => {
it("produces a stable key from the identity triple", () => {
const key = orbActorKey({
projectId: "prj-1",
runId: "run-1",
workUnitId: "wrk-1",
});
expect(key).toBe("project:prj-1:work:wrk-1:run:run-1");
});
it("preserves order across different identities", () => {
expect(orbActorKey({ projectId: "a", runId: "b", workUnitId: "c" })).toBe(
"project:a:work:c:run:b"
);
});
});
describe("transitionOrbState", () => {
it("allows creating -> prepared", () => {
expect(runTransitionOk("creating", "prepared")).toBe("prepared");
});
it("allows prepared -> running", () => {
expect(runTransitionOk("prepared", "running")).toBe("running");
});
it("allows running -> needs-input", () => {
expect(runTransitionOk("running", "needs-input")).toBe("needs-input");
});
it("allows running -> completed", () => {
expect(runTransitionOk("running", "completed")).toBe("completed");
});
it("allows completed -> disposed", () => {
expect(runTransitionOk("completed", "disposed")).toBe("disposed");
});
it("allows needs-input -> running (resume)", () => {
expect(runTransitionOk("needs-input", "running")).toBe("running");
});
it("rejects disposed -> running", () => {
const error = runTransition("disposed", "running");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("AlreadyDisposed");
});
it("rejects completed -> creating", () => {
const error = runTransition("completed", "creating");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
it("rejects prepared -> needs-input (skipping running)", () => {
const error = runTransition("prepared", "needs-input");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
it("rejects cancelled -> running", () => {
const error = runTransition("cancelled", "running");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
});
describe("transitionRunState", () => {
it("allows queued -> provisioning", () => {
expect(runRunStateOk("queued", "provisioning")).toBe("provisioning");
});
it("allows provisioning -> preparing", () => {
expect(runRunStateOk("provisioning", "preparing")).toBe("preparing");
});
it("allows running -> verifying", () => {
expect(runRunStateOk("running", "verifying")).toBe("verifying");
});
it("allows verifying -> succeeded", () => {
expect(runRunStateOk("verifying", "succeeded")).toBe("succeeded");
});
it("allows running -> cancelled", () => {
expect(runRunStateOk("running", "cancelled")).toBe("cancelled");
});
it("rejects succeeded -> running (terminal)", () => {
const error = runRunState("succeeded", "running");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
it("rejects failed -> running (terminal)", () => {
const error = runRunState("failed", "running");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
it("rejects queued -> succeeded (skipping steps)", () => {
const error = runRunState("queued", "succeeded");
expect(error).toBeInstanceOf(OrbStateError);
expect(error.reason).toBe("InvalidTransition");
});
});

View File

@@ -1,259 +0,0 @@
/* eslint-disable max-classes-per-file -- each domain failure has a distinct tagged reason. */
import { Effect, Schema } from "effect";
const MeaningfulString = Schema.String.check(
Schema.makeFilter((value) => value.trim().length > 0, {
expected: "a non-empty string",
})
);
// ---------------------------------------------------------------------------
// Branded identifiers
// ---------------------------------------------------------------------------
export const OrbId = MeaningfulString.pipe(Schema.brand("OrbId"));
export type OrbId = typeof OrbId.Type;
export const OrbRunId = MeaningfulString.pipe(Schema.brand("OrbRunId"));
export type OrbRunId = typeof OrbRunId.Type;
export const OrbSessionId = MeaningfulString.pipe(Schema.brand("OrbSessionId"));
export type OrbSessionId = typeof OrbSessionId.Type;
// ---------------------------------------------------------------------------
// Actor identity — one Orb per project/issue/run triple
// ---------------------------------------------------------------------------
export const OrbIdentity = Schema.Struct({
projectId: MeaningfulString,
runId: MeaningfulString,
workUnitId: MeaningfulString,
});
export type OrbIdentity = typeof OrbIdentity.Type;
/** Stable RivetKit actor key derived from the identity triple. */
export const orbActorKey = (identity: OrbIdentity): string =>
`project:${identity.projectId}:work:${identity.workUnitId}:run:${identity.runId}`;
// ---------------------------------------------------------------------------
// State machines — product state stays separate from run state
// ---------------------------------------------------------------------------
export const OrbState = Schema.Literals([
"creating",
"prepared",
"running",
"needs-input",
"completed",
"failed",
"cancelled",
"disposed",
]);
export type OrbState = typeof OrbState.Type;
export const RunState = Schema.Literals([
"queued",
"provisioning",
"preparing",
"running",
"verifying",
"succeeded",
"failed",
"cancelled",
]);
export type RunState = typeof RunState.Type;
const ORB_TRANSITIONS: Readonly<Record<OrbState, readonly OrbState[]>> = {
cancelled: ["disposed"],
completed: ["disposed"],
creating: ["prepared", "running", "failed", "cancelled", "disposed"],
disposed: [],
failed: ["disposed"],
"needs-input": ["running", "completed", "failed", "cancelled", "disposed"],
prepared: ["running", "failed", "cancelled", "disposed"],
running: ["needs-input", "completed", "failed", "cancelled", "disposed"],
};
const RUN_TRANSITIONS: Readonly<Record<RunState, readonly RunState[]>> = {
cancelled: [],
failed: [],
preparing: ["running", "verifying", "failed", "cancelled"],
provisioning: ["preparing", "running", "failed", "cancelled"],
queued: ["provisioning", "preparing", "running", "failed", "cancelled"],
running: ["verifying", "succeeded", "failed", "cancelled"],
succeeded: [],
verifying: ["succeeded", "failed", "cancelled"],
};
// ---------------------------------------------------------------------------
// Tagged errors
// ---------------------------------------------------------------------------
export const OrbStateErrorReason = Schema.Literals([
"InvalidTransition",
"AlreadyDisposed",
"NotRunning",
]);
export type OrbStateErrorReason = typeof OrbStateErrorReason.Type;
export class OrbStateError extends Schema.TaggedErrorClass<OrbStateError>()(
"OrbStateError",
{
from: Schema.String,
message: Schema.String,
reason: OrbStateErrorReason,
to: Schema.String,
}
) {}
export const OrbSandboxErrorReason = Schema.Literals([
"DockerUnavailable",
"ContainerStart",
"CommandFailed",
"ContainerCleanup",
]);
export type OrbSandboxErrorReason = typeof OrbSandboxErrorReason.Type;
export class OrbSandboxError extends Schema.TaggedErrorClass<OrbSandboxError>()(
"OrbSandboxError",
{
message: Schema.String,
reason: OrbSandboxErrorReason,
}
) {}
export const OrbSessionErrorReason = Schema.Literals([
"OpenSession",
"PromptFailed",
"AgentNotInstalled",
"SessionNotFound",
"PermissionDenied",
]);
export type OrbSessionErrorReason = typeof OrbSessionErrorReason.Type;
export class OrbSessionError extends Schema.TaggedErrorClass<OrbSessionError>()(
"OrbSessionError",
{
message: Schema.String,
reason: OrbSessionErrorReason,
}
) {}
export const OrbConfigurationErrorReason = Schema.Literals([
"MissingGateway",
"MissingIdentity",
"InvalidModelConfig",
]);
export type OrbConfigurationErrorReason =
typeof OrbConfigurationErrorReason.Type;
export class OrbConfigurationError extends Schema.TaggedErrorClass<OrbConfigurationError>()(
"OrbConfigurationError",
{
message: Schema.String,
reason: OrbConfigurationErrorReason,
}
) {}
// ---------------------------------------------------------------------------
// Configuration types
// ---------------------------------------------------------------------------
export const OrbModelGatewayConfig = Schema.Struct({
apiKey: MeaningfulString,
baseUrl: MeaningfulString,
model: MeaningfulString,
provider: MeaningfulString,
});
export type OrbModelGatewayConfig = typeof OrbModelGatewayConfig.Type;
export const OrbProjectContext = Schema.Struct({
artifacts: Schema.Array(
Schema.Struct({
content: Schema.String,
path: MeaningfulString,
})
),
contextFiles: Schema.Array(
Schema.Struct({
content: Schema.String,
path: MeaningfulString,
})
),
issueBody: MeaningfulString,
issueTitle: MeaningfulString,
repositoryUrl: Schema.UndefinedOr(MeaningfulString),
});
export type OrbProjectContext = typeof OrbProjectContext.Type;
// ---------------------------------------------------------------------------
// Transition helpers
// ---------------------------------------------------------------------------
export const transitionOrbState = Effect.fn("Orb.transitionState")(
function* transitionOrbState(input: {
readonly from: OrbState;
readonly to: OrbState;
}) {
if (input.from === input.to) {
return input.to;
}
if (input.from === "disposed") {
return yield* Effect.fail(
new OrbStateError({
from: input.from,
message: "Orb is already disposed",
reason: "AlreadyDisposed",
to: input.to,
})
);
}
if (!ORB_TRANSITIONS[input.from].includes(input.to)) {
return yield* Effect.fail(
new OrbStateError({
from: input.from,
message: `Cannot transition orb from ${input.from} to ${input.to}`,
reason: "InvalidTransition",
to: input.to,
})
);
}
return input.to;
}
);
export const transitionRunState = Effect.fn("Orb.transitionRunState")(
function* transitionRunState(input: {
readonly from: RunState;
readonly to: RunState;
}) {
if (input.from === input.to) {
return input.to;
}
if (
input.from === "succeeded" ||
input.from === "failed" ||
input.from === "cancelled"
) {
return yield* Effect.fail(
new OrbStateError({
from: input.from,
message: `Run is already in terminal state ${input.from}`,
reason: "InvalidTransition",
to: input.to,
})
);
}
if (!RUN_TRANSITIONS[input.from].includes(input.to)) {
return yield* Effect.fail(
new OrbStateError({
from: input.from,
message: `Cannot transition run from ${input.from} to ${input.to}`,
reason: "InvalidTransition",
to: input.to,
})
);
}
return input.to;
}
);

View File

@@ -1,134 +0,0 @@
/* eslint-disable no-non-null-assertion -- test assertions on defined events */
import { describe, expect, it } from "vitest";
import { makeOrbEvent, normalizeSessionEvent, redactSecrets } from "./events";
describe("redactSecrets", () => {
it("redacts api_key patterns", () => {
const input = "Using api_key=sk-abc123def456ghi789jkl012mno345";
const result = redactSecrets(input);
expect(result).not.toContain("sk-abc123");
expect(result).toContain("[REDACTED]");
});
it("redacts Bearer tokens", () => {
const input = "Authorization: Bearer eyJhbGciOiJIUzI1";
const result = redactSecrets(input);
expect(result).toContain("Bearer [REDACTED]");
expect(result).not.toContain("eyJhbGciOiJIUzI1");
});
it("redacts token= patterns", () => {
const input = 'token: "my-secret-token-value"';
const result = redactSecrets(input);
expect(result).not.toContain("my-secret-token-value");
});
it("preserves non-secret text", () => {
expect(redactSecrets("just regular text")).toBe("just regular text");
});
});
describe("makeOrbEvent", () => {
it("creates an event with sequence and timestamp", () => {
const event = makeOrbEvent(5, "session_opened", { text: "opened" });
expect(event.sequence).toBe(5);
expect(event.type).toBe("session_opened");
expect(event.text).toBe("opened");
expect(event.timestamp).toBeDefined();
});
it("creates an event with command and exitCode", () => {
const event = makeOrbEvent(3, "command_executed", {
command: "bun test",
exitCode: 0,
});
expect(event.command).toBe("bun test");
expect(event.exitCode).toBe(0);
});
});
describe("normalizeSessionEvent", () => {
it("normalizes agent_message_chunk", () => {
const event = normalizeSessionEvent({
rawText: "Working on the fix",
sequence: 5,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:00Z",
type: "agent_message_chunk",
});
expect(event).toBeDefined();
expect(event!.type).toBe("agent_message_chunk");
expect(event!.text).toBe("Working on the fix");
expect(event!.sequence).toBe(5);
});
it("normalizes agent_message to agent_message_completed", () => {
const event = normalizeSessionEvent({
content: [{ text: "Done", type: "text" }],
sequence: 10,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:05Z",
type: "agent_message",
});
expect(event).toBeDefined();
expect(event!.type).toBe("agent_message_completed");
expect(event!.text).toBe("Done");
});
it("normalizes tool_call", () => {
const event = normalizeSessionEvent({
sequence: 3,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:01Z",
title: "bash",
toolCallId: "tc-1",
type: "tool_call",
});
expect(event).toBeDefined();
expect(event!.type).toBe("tool_call_started");
expect(event!.toolName).toBe("bash");
expect(event!.toolCallId).toBe("tc-1");
});
it("normalizes permission_request", () => {
const event = normalizeSessionEvent({
sequence: 7,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:03Z",
type: "permission_request",
});
expect(event).toBeDefined();
expect(event!.type).toBe("permission_requested");
});
it("returns undefined for unmapped types", () => {
const event = normalizeSessionEvent({
sequence: 1,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:00Z",
type: "session_config",
});
expect(event).toBeUndefined();
});
it("returns undefined when type is missing", () => {
const event = normalizeSessionEvent({
sequence: 1,
sessionId: "sess-1",
});
expect(event).toBeUndefined();
});
it("redacts secrets in persisted event copies", () => {
const event = normalizeSessionEvent({
rawText: "Using api_key=sk-secret123456789012345678",
sequence: 2,
sessionId: "sess-1",
timestamp: "2026-07-24T12:00:00Z",
type: "agent_message_chunk",
});
expect(event).toBeDefined();
expect(event!.text).not.toContain("sk-secret");
});
});

View File

@@ -1,216 +0,0 @@
import { Schema } from "effect";
// ---------------------------------------------------------------------------
// Normalized Orb events — domain-meaningful, secret-free
// ---------------------------------------------------------------------------
export const OrbEventVariant = Schema.Literals([
"session_opened",
"agent_message_chunk",
"agent_message_completed",
"agent_thought_chunk",
"tool_call_started",
"tool_call_completed",
"permission_requested",
"permission_denied",
"command_executed",
"session_failed",
"session_closed",
"vm_booted",
"vm_shutdown",
]);
export type OrbEventVariant = typeof OrbEventVariant.Type;
export const OrbEvent = Schema.Struct({
command: Schema.UndefinedOr(Schema.String),
exitCode: Schema.UndefinedOr(Schema.Int),
sequence: Schema.Number,
text: Schema.UndefinedOr(Schema.String),
timestamp: Schema.String,
toolCallId: Schema.UndefinedOr(Schema.String),
toolName: Schema.UndefinedOr(Schema.String),
type: OrbEventVariant,
});
export type OrbEvent = typeof OrbEvent.Type;
/** Construct an OrbEvent with auto-incrementing sequence and timestamp. */
export const makeOrbEvent = (
sequence: number,
type: OrbEventVariant,
fields?: Partial<Omit<OrbEvent, "sequence" | "timestamp" | "type">>
): OrbEvent =>
({
command: fields?.command ?? undefined,
exitCode: fields?.exitCode ?? undefined,
sequence,
text: fields?.text ?? undefined,
timestamp: new Date().toISOString(),
toolCallId: fields?.toolCallId ?? undefined,
toolName: fields?.toolName ?? undefined,
type,
}) as unknown as OrbEvent;
// ---------------------------------------------------------------------------
// Secret redaction — applied only to persisted/logged event copies,
// never to prompts sent to the model.
// ---------------------------------------------------------------------------
const REDACT_PATTERNS = [
/(?:api[_-]?key|token|secret|password|credential)["'\s:=]+(?<value>[^\s"'},]+)/giu,
/sk-(?<key>[a-zA-Z0-9]{20,})/gu,
/Bearer\s+[a-zA-Z0-9._-]+/gu,
];
export const redactSecrets = (text: string): string => {
let result = text;
for (const pattern of REDACT_PATTERNS) {
result = result.replaceAll(pattern, (match) =>
match.toLowerCase().includes("bearer")
? "Bearer [REDACTED]"
: "[REDACTED]"
);
}
return result;
};
// ---------------------------------------------------------------------------
// Translation from AgentOS session stream entries to normalized OrbEvent
// ---------------------------------------------------------------------------
interface AcpSessionUpdateLike {
readonly type?: string;
readonly sessionUpdate?: string;
readonly rawText?: string;
readonly text?: string;
readonly content?: unknown;
readonly toolCallId?: string | null;
readonly toolCallStatus?: string;
readonly title?: string | null;
readonly sessionId?: string;
}
interface SessionStreamEntryLike {
readonly afterSequence?: number;
readonly content?: unknown;
readonly durability?: string;
readonly rawText?: string;
readonly sequence?: number;
readonly sessionId?: string;
readonly sessionUpdate?: string;
readonly text?: string;
readonly timestamp?: string;
readonly title?: string | null;
readonly toolCallId?: string | null;
readonly type?: string;
}
const IGNORED_TYPES = new Set([
"session_config",
"agent_description",
"agent_capability",
]);
const MESSAGE_TYPES = new Set([
"agent_message_chunk",
"agent_message",
"agent_thought_chunk",
]);
const TOOL_CALL_TYPES = new Set([
"tool_call",
"tool_call_status",
"tool_call_update",
]);
const extractText = (entry: AcpSessionUpdateLike): string | undefined => {
if (entry.rawText !== undefined) {
return entry.rawText;
}
if (entry.text !== undefined) {
return entry.text;
}
if (typeof entry.content === "string") {
return entry.content;
}
if (Array.isArray(entry.content)) {
const texts = entry.content
.filter(
(block): block is { readonly type: string; readonly text?: unknown } =>
typeof block === "object" && block !== null && "type" in block
)
.map((block) => (typeof block.text === "string" ? block.text : undefined))
.filter((text): text is string => text !== undefined);
return texts.length > 0 ? texts.join("") : undefined;
}
return undefined;
};
const optionalToolFields = (
raw: SessionStreamEntryLike
): { toolCallId?: string; toolName?: string } => ({
...(raw.toolCallId === null || raw.toolCallId === undefined
? {}
: { toolCallId: raw.toolCallId }),
...(raw.title === null || raw.title === undefined
? {}
: { toolName: raw.title }),
});
const fromMessage = (
type: string,
sequence: number,
raw: SessionStreamEntryLike
): OrbEvent | undefined => {
const text = extractText(raw);
if (text === undefined) {
// agent_message completes even without text; chunk/thought do not.
return type === "agent_message"
? makeOrbEvent(sequence, "agent_message_completed", {})
: undefined;
}
const variant = (
type === "agent_message" ? "agent_message_completed" : type
) as OrbEventVariant;
return makeOrbEvent(sequence, variant, { text: redactSecrets(text) });
};
const fromToolCall = (
type: string,
sequence: number,
raw: SessionStreamEntryLike
): OrbEvent =>
makeOrbEvent(
sequence,
type === "tool_call" ? "tool_call_started" : "tool_call_completed",
optionalToolFields(raw)
);
/**
* Translate one AgentOS SessionStreamEntry into zero or one normalized OrbEvent.
* Returns undefined for event types that have no domain-meaningful mapping yet.
* Secret redaction is applied so persisted event copies never leak credentials.
*/
export const normalizeSessionEvent = (
raw: SessionStreamEntryLike
): OrbEvent | undefined => {
const type = raw.type ?? raw.sessionUpdate;
if (type === undefined) {
return undefined;
}
const sequence = raw.sequence ?? 0;
if (IGNORED_TYPES.has(type)) {
return undefined;
}
if (type === "permission_request") {
return makeOrbEvent(sequence, "permission_requested", {
text: "Permission requested",
});
}
if (MESSAGE_TYPES.has(type)) {
return fromMessage(type, sequence, raw);
}
if (TOOL_CALL_TYPES.has(type)) {
return fromToolCall(type, sequence, raw);
}
return undefined;
};

View File

@@ -1,81 +0,0 @@
import { runPostRunGiteaLifecycle } from "../git/gitea";
import type { GitCommandRunner, GiteaTransport } from "../git/gitea";
import type {
GitLifecyclePort,
GitLifecycleResult,
GitPublishInput,
OrbRunPort,
} from "./ports";
// ---------------------------------------------------------------------------
// OrbGitCommandRunner — runs git commands inside the Orb sandbox
//
// Adapts the OrbRunPort.executeCommand interface to the GitCommandRunner
// shape expected by runPostRunGiteaLifecycle. Commands execute inside the
// Docker sandbox where OpenCode made its changes.
// ---------------------------------------------------------------------------
const createOrbGitRunner = (orb: OrbRunPort): GitCommandRunner => ({
run(
command: string,
options?: { readonly cwd?: string; readonly env?: Record<string, string> }
) {
const cwd = options?.cwd ?? "/mnt/sandbox/repository";
return orb.executeCommand(command, cwd);
},
});
// ---------------------------------------------------------------------------
// Git lifecycle adapter factory
//
// Creates a GitLifecyclePort bound to one Orb run. The command runner executes
// git inside that Orb's sandbox; the Gitea transport creates PRs via HTTP.
// This is the application-layer entry point — no interactive Flue shell needed.
// ---------------------------------------------------------------------------
export const createGitLifecyclePort = (
orb: OrbRunPort,
transport: GiteaTransport
): GitLifecyclePort => {
const runner = createOrbGitRunner(orb);
return {
async publish(input: GitPublishInput): Promise<GitLifecycleResult> {
const result = await runPostRunGiteaLifecycle({
baseBranch: input.baseBranch,
body: `Verified changes for project issue #${input.issueNumber}. Merge remains a manual review action.`,
...(input.commitMessage === undefined
? {}
: { commitMessage: input.commitMessage }),
issueNumber: input.issueNumber,
issueTitle: input.issueTitle,
repositoryPath: input.repositoryPath,
runner,
title: `Issue #${input.issueNumber}: ${input.issueTitle}`,
transport,
verification: input.verification,
workspace: input.workspace,
});
return {
baseBranch: result.baseBranch,
branch: result.branch,
...(result.commitSha === undefined
? {}
: { commitSha: result.commitSha }),
...(result.pullRequest === undefined
? {}
: {
pullRequest: {
baseBranch: result.pullRequest.baseBranch,
branch: result.pullRequest.branch,
number: result.pullRequest.number,
status: result.pullRequest.status,
url: result.pullRequest.url,
},
}),
status: result.status,
};
},
};
};

View File

@@ -1,13 +0,0 @@
// oxlint-disable-next-line no-barrel-file -- The Orb module exposes its public surface here.
export * from "./domain";
export * from "./events";
export * from "./docker-sandbox";
export * from "./opencode-config";
export * from "./permission-policy";
export * from "./runtime";
export * from "./ports";
export * from "./project-events";
export * from "./context-pack";
export * from "./orb-project-manager";
export * from "./orb-adapter";
export * from "./git-adapter";

View File

@@ -1,82 +0,0 @@
/* eslint-disable no-non-null-assertion -- test assertions on defined objects */
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { OrbConfigurationError } from "./domain";
import {
opencodeSetupCommands,
prepareOpenCodeConfig,
} from "./opencode-config";
const validGateway = {
apiKey: "test-key-123",
baseUrl: "https://gateway.example.com/v1",
model: "test-model",
provider: "test-provider",
};
const validContext = {
artifacts: [],
contextFiles: [],
issueBody: "Fix the bug",
issueTitle: "Bug fix",
repositoryUrl: undefined,
};
describe("prepareOpenCodeConfig", () => {
it("produces valid config JSON with provider and model", () => {
const result = Effect.runSync(
prepareOpenCodeConfig({
context: validContext,
gateway: validGateway,
})
);
const parsed = JSON.parse(result.configJson);
expect(parsed.model).toBe("test-provider/test-model");
expect(parsed.provider["test-provider"].baseUrl).toBe(
"https://gateway.example.com/v1"
);
expect(parsed.provider["test-provider"].apiKey).toBe("test-key-123");
});
it("sets config path under opencode config directory", () => {
const result = Effect.runSync(
prepareOpenCodeConfig({
context: validContext,
gateway: validGateway,
})
);
expect(result.configPath).toContain("opencode");
expect(result.configPath).toContain("config.json");
expect(result.instructionsPath).toBe("/workspace/control/issue.md");
});
it("rejects empty base URL", () => {
const error = Effect.runSync(
Effect.flip(
prepareOpenCodeConfig({
context: validContext,
gateway: { ...validGateway, baseUrl: " " },
})
)
);
expect(error).toBeInstanceOf(OrbConfigurationError);
expect(error.reason).toBe("InvalidModelConfig");
});
});
describe("opencodeSetupCommands", () => {
it("produces mkdir, write, and chmod commands", () => {
const config = Effect.runSync(
prepareOpenCodeConfig({
context: validContext,
gateway: validGateway,
})
);
const commands = opencodeSetupCommands(config);
expect(commands.length).toBe(3);
expect(commands[0]).toContain("mkdir");
expect(commands[1]).toContain("cat >");
expect(commands[2]).toContain("chmod 600");
});
});

View File

@@ -1,76 +0,0 @@
import { Effect } from "effect";
import { OrbConfigurationError } from "./domain";
import type { OrbModelGatewayConfig, OrbProjectContext } from "./domain";
// ---------------------------------------------------------------------------
// OpenCode configuration — prepared inside the AgentOS VM filesystem
// ---------------------------------------------------------------------------
const OPENCODE_CONFIG_DIR = "/root/.config/opencode";
const OPENCODE_CONFIG_PATH = `${OPENCODE_CONFIG_DIR}/config.json`;
const AGENT_INSTRUCTIONS_PATH = "/workspace/control/issue.md";
export interface PreparedOpenCodeConfig {
readonly configJson: string;
readonly configPath: string;
readonly instructionsPath: string;
}
const validateGateway = (
gateway: OrbModelGatewayConfig
): Effect.Effect<void, OrbConfigurationError> =>
gateway.baseUrl.trim().length === 0
? Effect.fail(
new OrbConfigurationError({
message: "Model gateway base URL must not be empty",
reason: "InvalidModelConfig",
})
)
: Effect.void;
/**
* Build the OpenCode configuration JSON and file layout for one Orb run.
* The configuration points OpenCode at the model gateway with run-scoped
* credentials injected at runtime — never committed to project files.
*/
export const prepareOpenCodeConfig = Effect.fn("Orb.prepareOpenCodeConfig")(
function* prepareOpenCodeConfig(input: {
readonly context: OrbProjectContext;
readonly gateway: OrbModelGatewayConfig;
}) {
yield* validateGateway(input.gateway);
const config = {
$schema: "https://opencode.ai/config.json",
model: `${input.gateway.provider}/${input.gateway.model}`,
provider: {
[input.gateway.provider]: {
apiKey: input.gateway.apiKey,
baseUrl: input.gateway.baseUrl,
models: {
[input.gateway.model]: {
name: input.gateway.model,
},
},
},
},
};
const configJson = JSON.stringify(config, null, 2);
return {
configJson,
configPath: OPENCODE_CONFIG_PATH,
instructionsPath: AGENT_INSTRUCTIONS_PATH,
} satisfies PreparedOpenCodeConfig;
}
);
/** Shell commands that stage the OpenCode config directory inside a VM. */
export const opencodeSetupCommands = (config: PreparedOpenCodeConfig) =>
[
`mkdir -p ${OPENCODE_CONFIG_DIR}`,
`cat > ${config.configPath} << 'ORB_EOF'\n${config.configJson}\nORB_EOF`,
`chmod 600 ${config.configPath}`,
] as const;

View File

@@ -1,132 +0,0 @@
import { Effect } from "effect";
import type { OrbEvent } from "./events";
import type {
CommandResult,
OrbAdapter,
OrbCreatePortInput,
OrbRunPort,
PrepareRepoInput,
} from "./ports";
import { OrbRuntime } from "./runtime";
import type { OrbEnv, OrbHandle } from "./runtime";
// ---------------------------------------------------------------------------
// RealOrbRun — wraps an OrbHandle behind the OrbRunPort interface
//
// Effect-based Orb methods are run to Promise here so the orchestrator and
// tests work with plain async/await. Effect failures surface as rejections.
// ---------------------------------------------------------------------------
class RealOrbRun implements OrbRunPort {
private readonly listeners = new Set<(event: OrbEvent) => void>();
private unsubscribe: (() => void) | null = null;
private readonly handle: OrbHandle;
constructor(handle: OrbHandle) {
this.handle = handle;
}
/** Called once after the handle-level listener is wired. */
_setUnsubscribe(fn: () => void): void {
this.unsubscribe = fn;
}
get orbId(): string {
return this.handle.id;
}
get runId(): string {
return this.handle.runId;
}
get sessionId(): string | undefined {
return this.handle.currentSessionId;
}
get state(): string {
return this.handle.state;
}
onEvent = (listener: (event: OrbEvent) => void): (() => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
/** Forward an OrbHandle event to all port-level listeners. */
forwardEvent = (event: OrbEvent): void => {
for (const listener of this.listeners) {
listener(event);
}
};
prepareRepository = async (input: PrepareRepoInput): Promise<void> => {
await Effect.runPromise(this.handle.prepareRepository(input));
};
openSession = async (): Promise<string> =>
(await Effect.runPromise(this.handle.openSession())) as string;
sendTask = async (prompt: string): Promise<unknown> =>
await Effect.runPromise(this.handle.sendTask(prompt));
executeCommand = async (
command: string,
cwd?: string
): Promise<CommandResult> => {
const result = (await Effect.runPromise(
this.handle.executeCommand({
command,
...(cwd === undefined ? {} : { cwd }),
})
)) as { exitCode: number | null; stderr: string; stdout: string };
return {
exitCode: result.exitCode ?? -1,
stderr: result.stderr,
stdout: result.stdout,
};
};
cancel = async (): Promise<void> => {
await Effect.runPromise(this.handle.cancel().pipe(Effect.ignore));
};
dispose = async (): Promise<void> => {
this.unsubscribe?.();
this.listeners.clear();
await Effect.runPromise(this.handle.dispose().pipe(Effect.ignore));
};
}
// ---------------------------------------------------------------------------
// Real Orb adapter — wraps OrbRuntime.createOrb behind the OrbAdapter port
// ---------------------------------------------------------------------------
export const createOrbAdapter = (env?: OrbEnv): OrbAdapter => {
const runtime = new OrbRuntime(env);
return {
createOrb: async (input: OrbCreatePortInput): Promise<OrbRunPort> => {
const handle = await Effect.runPromise(
runtime.createOrb({
context: input.context,
docker: input.docker,
gateway: input.gateway,
identity: input.identity,
})
);
const run = new RealOrbRun(handle);
// Bridge OrbHandle events to port listeners via a single forwarding point.
const unsubscribe = handle.onEvent((event) => {
run.forwardEvent(event);
});
run._setUnsubscribe(unsubscribe);
return run;
},
};
};

View File

@@ -1,132 +0,0 @@
/* eslint-disable no-console -- integration test is a CLI-style probe */
/**
* Opt-in live integration test for the Orb-wired project-manager.
*
* Only runs when ORB_PM_INTEGRATION=1 is set. Requires:
* - Docker daemon
* - Model gateway credentials (ORB_GATEWAY_* or AGENT_MODEL_*)
* - A local Gitea instance with a test repo (optional — set GITEA_*)
*
* This test exercises the full flow: Orb creation, repo preparation, session
* open, model turn, Git lifecycle (or skip if Gitea is not configured).
*
* Usage:
* ORB_PM_INTEGRATION=1 \
* ORB_GATEWAY_API_KEY=... \
* ORB_GATEWAY_BASE_URL=https://ai.example.com/v1 \
* ORB_GATEWAY_MODEL=glm-5.2 \
* ORB_GATEWAY_PROVIDER=cheaptricks \
* bun test packages/agents/src/orb/orb-project-manager.live.test.ts
*/
import { describe, expect, it } from "vitest";
import { createGiteaHttpTransport } from "../git/gitea";
import { createGitLifecyclePort } from "./git-adapter";
import { createOrbAdapter } from "./orb-adapter";
import { OrbProjectManager } from "./orb-project-manager";
const env = (key: string): string | undefined => process.env[key];
const isLive = env("ORB_PM_INTEGRATION") === "1";
const resolveGateway = () => {
const apiKey = env("ORB_GATEWAY_API_KEY") ?? env("AGENT_MODEL_API_KEY");
const baseUrl = env("ORB_GATEWAY_BASE_URL") ?? env("AGENT_MODEL_BASE_URL");
const model = env("ORB_GATEWAY_MODEL") ?? env("AGENT_MODEL_NAME");
const provider = env("ORB_GATEWAY_PROVIDER") ?? env("AGENT_MODEL_PROVIDER");
if (!apiKey || !baseUrl || !model || !provider) {
return null;
}
return { apiKey, baseUrl, model, provider };
};
const hasGitea = () =>
env("GITEA_URL") !== undefined && env("GITEA_TOKEN") !== undefined;
describe.skipIf(!isLive)("OrbProjectManager live integration", () => {
it("creates an Orb, prepares repo, sends a model turn, and projects events", async () => {
const gateway = resolveGateway();
expect(gateway, "Gateway credentials required").not.toBeNull();
const adapter = createOrbAdapter();
const events: { type: string; text?: string }[] = [];
const pm = new OrbProjectManager({
createGitLifecycle: (orb) =>
createGitLifecyclePort(
orb,
createGiteaHttpTransport({
baseUrl: env("GITEA_URL") ?? "http://localhost:3000",
token: env("GITEA_TOKEN") ?? "",
})
),
onProjectEvent: (e) => events.push({ text: e.text, type: e.type }),
orbAdapter: adapter,
});
const result = await pm.startIssue({
baseBranch: "main",
branchName: `work/orb-pm-test-${Date.now()}`,
context: {
artifacts: [],
contextFiles: [],
issueBody: "Reply with WORK_COMPLETE: hello world test passed",
issueTitle: "Integration: model echo",
repositoryUrl: undefined,
},
contextPack: {
artifacts: [],
contextFiles: [],
evidence: [],
issueBody: "Reply with WORK_COMPLETE: hello world test passed",
issueNumber: 1,
issueTitle: "Integration: model echo",
repositoryMetadata: {
baseBranch: "main",
repositoryName: "orb-pm-test",
repositoryUrl: "local",
},
},
docker: {
hostWorkspacePath: `/tmp/orb-pm-test-${Date.now()}`,
},
gateway: gateway ?? {
apiKey: "",
baseUrl: "",
model: "",
provider: "",
},
issueId: `orb-pm-integration-${Date.now()}`,
issueNumber: 1,
issueTitle: "Integration: model echo",
projectId: "orb-pm-test",
runId: `run-${Date.now()}`,
});
expect(result.orbId).toBeDefined();
expect(result.sessionId).toBeDefined();
const eventTypes = events.map((e) => e.type);
expect(eventTypes).toContain("run.started");
expect(eventTypes).toContain("run.repository_prepared");
expect(eventTypes).toContain("run.session_opened");
// If Gitea is configured, attempt the full Git lifecycle.
if (hasGitea()) {
console.log("[orb-pm] Gitea configured — attempting Git lifecycle...");
try {
const gitResult = await pm.complete({
commitMessage: "test: orb project-manager integration",
issueId: result.issueId,
});
console.log(`[orb-pm] Git lifecycle result: ${gitResult.status}`);
} catch (error) {
console.log(
`[orb-pm] Git lifecycle failed (expected in CI): ${error instanceof Error ? error.message : String(error)}`
);
}
}
await pm.cancel(result.issueId);
console.log(`[orb-pm] Events: ${eventTypes.join(", ")}`);
}, 120_000);
});

View File

@@ -1,709 +0,0 @@
/* eslint-disable no-non-null-assertion -- test assertions on controlled fakes */
import { describe, expect, it } from "vitest";
import { makeOrbEvent } from "./events";
import type { OrbEvent } from "./events";
import { OrbProjectManager, ProjectManagerError } from "./orb-project-manager";
import type {
GitLifecyclePort,
GitLifecycleResult,
GitPublishInput,
OrbAdapter,
OrbCreatePortInput,
OrbRunPort,
PrepareRepoInput,
ProjectArtifact,
} from "./ports";
import type { ProjectRunEvent } from "./project-events";
// ---------------------------------------------------------------------------
// Fake Orb run — records calls and emits configurable events on sendTask
// ---------------------------------------------------------------------------
interface FakeOrbConfig {
/** Events to emit when sendTask resolves, mapped by call index. */
readonly eventsByTurn?: readonly (readonly OrbEvent[])[];
/** Default events to emit on every sendTask if no per-turn mapping. */
readonly defaultEvents?: readonly OrbEvent[];
/** If true, sendTask rejects on the first call. */
readonly failOnFirstSend?: boolean;
/** If true, prepareRepository rejects. */
readonly failOnPrepare?: boolean;
}
class FakeOrbRun implements OrbRunPort {
readonly orbId: string;
readonly runId: string;
sessionId: string | undefined;
state = "running";
private readonly config: FakeOrbConfig;
readonly sentTasks: string[] = [];
readonly prepareCalls: PrepareRepoInput[] = [];
cancelCalled = false;
disposeCalled = false;
private listeners = new Set<(event: OrbEvent) => void>();
private sendCallCount = 0;
constructor(orbId: string, runId: string, config: FakeOrbConfig) {
this.orbId = orbId;
this.runId = runId;
this.config = config;
}
onEvent(listener: (event: OrbEvent) => void): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
private emit(events: readonly OrbEvent[]): void {
for (const event of events) {
for (const listener of this.listeners) {
listener(event);
}
}
}
prepareRepository(input: PrepareRepoInput): Promise<void> {
this.prepareCalls.push(input);
if (this.config.failOnPrepare) {
return Promise.reject(new Error("Fake: prepareRepository failed"));
}
this.state = "prepared";
return Promise.resolve();
}
openSession(): Promise<string> {
this.sessionId = `session-${this.orbId}`;
this.state = "running";
return Promise.resolve(this.sessionId);
}
sendTask(prompt: string): Promise<unknown> {
this.sentTasks.push(prompt);
const callIndex = this.sendCallCount;
this.sendCallCount += 1;
if (callIndex === 0 && this.config.failOnFirstSend) {
return Promise.reject(new Error("Fake: sendTask failed on first call"));
}
const events =
this.config.eventsByTurn?.[callIndex] ?? this.config.defaultEvents ?? [];
this.emit(events);
return Promise.resolve({ ok: true });
}
executeCommand(
command: string,
_cwd?: string
): Promise<{ exitCode: number; stderr: string; stdout: string }> {
void this.config;
return Promise.resolve({
exitCode: 0,
stderr: "",
stdout: `fake: ${command}`,
});
}
cancel(): Promise<void> {
this.cancelCalled = true;
this.state = "cancelled";
return Promise.resolve();
}
dispose(): Promise<void> {
this.disposeCalled = true;
this.state = "disposed";
return Promise.resolve();
}
}
// ---------------------------------------------------------------------------
// Fake Orb adapter
// ---------------------------------------------------------------------------
const createFakeOrbAdapter = (
config?: FakeOrbConfig,
counter?: { value: number }
): { adapter: OrbAdapter; runs: FakeOrbRun[] } => {
const runs: FakeOrbRun[] = [];
const cfg = config ?? {};
const cnt = counter ?? { value: 0 };
const adapter: OrbAdapter = {
createOrb(_input: OrbCreatePortInput): Promise<OrbRunPort> {
cnt.value += 1;
const orbId = `orb-fake-${cnt.value}`;
const runId = `run-fake-${cnt.value}`;
const run = new FakeOrbRun(orbId, runId, cfg);
runs.push(run);
return Promise.resolve(run);
},
};
return { adapter, runs };
};
// ---------------------------------------------------------------------------
// Fake Git lifecycle adapter
// ---------------------------------------------------------------------------
interface FakeGitConfig {
readonly result?: GitLifecycleResult;
readonly failWith?: Error;
readonly failOnFirstAttempt?: boolean;
}
const createFakeGitLifecycle = (
config?: FakeGitConfig
): { port: GitLifecyclePort; publishCalls: GitPublishInput[] } => {
const cfg = config ?? {};
const publishCalls: GitPublishInput[] = [];
let attemptCount = 0;
const defaultResult: GitLifecycleResult = {
baseBranch: "main",
branch: "work/issue-42",
commitSha: "abc123def",
pullRequest: {
baseBranch: "main",
branch: "work/issue-42",
number: 7,
status: "open",
url: "https://git.example.com/repo/pulls/7",
},
status: "pull_request_open",
};
const port: GitLifecyclePort = {
publish(input: GitPublishInput): Promise<GitLifecycleResult> {
publishCalls.push(input);
attemptCount += 1;
if (cfg.failWith && attemptCount === 1) {
return Promise.reject(cfg.failWith);
}
if (cfg.failOnFirstAttempt && attemptCount === 1) {
return Promise.reject(
new Error("Fake: PR creation failed on first attempt")
);
}
return Promise.resolve(cfg.result ?? defaultResult);
},
};
return { port, publishCalls };
};
// ---------------------------------------------------------------------------
// Shared fixtures
// ---------------------------------------------------------------------------
const baseStartInput = (
overrides?: Partial<StartIssueInputTest>
): StartIssueInputTest => ({
baseBranch: "main",
branchName: "work/issue-42",
context: {
artifacts: [],
contextFiles: [],
issueBody: "Add a hello world endpoint",
issueTitle: "Add hello endpoint",
repositoryUrl: undefined,
},
contextPack: {
artifacts: [],
contextFiles: [],
evidence: [],
issueBody: "Add a hello world endpoint",
issueNumber: 42,
issueTitle: "Add hello endpoint",
repositoryMetadata: {
baseBranch: "main",
repositoryName: "test-repo",
repositoryUrl: "https://git.example.com/repo",
},
},
docker: { hostWorkspacePath: "/tmp/test" },
gateway: {
apiKey: "test-key",
baseUrl: "https://gw.example.com/v1",
model: "m1",
provider: "p1",
},
issueId: "issue-42",
issueNumber: 42,
issueTitle: "Add hello endpoint",
projectId: "prj-1",
repositoryPath: "org/repo",
runId: "run-42",
...overrides,
});
type StartIssueInputTest = Parameters<OrbProjectManager["startIssue"]>[0];
const makeMessageEvent = (text: string, sequence: number): OrbEvent =>
makeOrbEvent(sequence, "agent_message_completed", { text });
const makeCommandEvent = (
command: string,
exitCode: number,
sequence: number
): OrbEvent =>
makeOrbEvent(sequence, "command_executed", { command, exitCode });
// ===========================================================================
// TESTS
// ===========================================================================
describe("OrbProjectManager", () => {
// -----------------------------------------------------------------------
// 1. First-message start
// -----------------------------------------------------------------------
describe("first-message start", () => {
it("creates an Orb run, prepares the repo, opens a session, and sends the context pack", async () => {
const { adapter, runs } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: done", 1)],
});
const events: ProjectRunEvent[] = [];
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
onProjectEvent: (e) => events.push(e),
orbAdapter: adapter,
});
const result = await pm.startIssue(baseStartInput());
expect(result.issueId).toBe("issue-42");
expect(result.status).toBe("completing");
expect(result.sessionId).toBeDefined();
expect(runs).toHaveLength(1);
expect(runs[0]!.prepareCalls).toHaveLength(1);
expect(runs[0]!.prepareCalls[0]?.branchName).toBe("work/issue-42");
expect(runs[0]!.sentTasks).toHaveLength(1);
expect(runs[0]!.sentTasks[0]).toContain("Add hello endpoint");
const eventTypes = events.map((e) => e.type);
expect(eventTypes).toContain("run.started");
expect(eventTypes).toContain("run.repository_prepared");
expect(eventTypes).toContain("run.session_opened");
});
it("maps OrbEvents into durable project events and forwards them to the sink", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [
makeOrbEvent(1, "tool_call_started", { toolName: "edit_file" }),
makeCommandEvent("npm test", 0, 2),
makeMessageEvent("WORK_COMPLETE: all tests pass", 3),
],
});
const events: ProjectRunEvent[] = [];
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
onProjectEvent: (e) => events.push(e),
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
const types = events.map((e) => e.type);
expect(types).toContain("run.agent_progress");
expect(types).toContain("run.command_executed");
expect(types).toContain("run.agent_message");
const cmdEvent = events.find((e) => e.type === "run.command_executed");
expect(cmdEvent?.text).toBe("npm test");
expect(cmdEvent?.exitCode).toBe(0);
});
});
// -----------------------------------------------------------------------
// 2. Follow-up forwarding
// -----------------------------------------------------------------------
describe("follow-up forwarding", () => {
it("forwards a contextual message to the same OpenCode session", async () => {
const { adapter, runs } = createFakeOrbAdapter({
eventsByTurn: [
[makeMessageEvent("NEEDS_INPUT: what name?", 1)],
[makeMessageEvent("WORK_COMPLETE: done", 2)],
],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
const start = await pm.startIssue(baseStartInput());
expect(start.status).toBe("needs-input");
expect(start.needsInputQuestion).toBe("what name?");
const followUp = await pm.sendMessage("issue-42", "Name it /hello");
expect(followUp.status).toBe("completing");
expect(runs[0]!.sentTasks).toHaveLength(2);
expect(runs[0]!.sentTasks[1]).toBe("Name it /hello");
});
it("rejects a follow-up for a non-existent run", async () => {
const { adapter } = createFakeOrbAdapter();
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await expect(pm.sendMessage("nope", "hello")).rejects.toThrow();
try {
await pm.sendMessage("nope", "hello");
} catch (error) {
expect(error).toBeInstanceOf(ProjectManagerError);
expect((error as ProjectManagerError).reason).toBe("RunNotFound");
}
});
it("rejects a follow-up after cancellation", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("NEEDS_INPUT: hmm", 1)],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
await pm.cancel("issue-42");
await expect(pm.sendMessage("issue-42", "hello")).rejects.toThrow();
try {
await pm.sendMessage("issue-42", "hello");
} catch (error) {
expect(error).toBeInstanceOf(ProjectManagerError);
expect((error as ProjectManagerError).reason).toBe("RunTerminal");
}
});
});
// -----------------------------------------------------------------------
// 3. Needs-input handling
// -----------------------------------------------------------------------
describe("needs-input handling", () => {
it("detects the needs-input marker and surfaces the question", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [
makeMessageEvent("NEEDS_INPUT: Should I use GET or POST?", 1),
],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
const result = await pm.startIssue(baseStartInput());
expect(result.status).toBe("needs-input");
expect(result.needsInputQuestion).toBe("Should I use GET or POST?");
const events = pm.getRunEvents("issue-42");
expect(events.some((e) => e.type === "run.needs_input")).toBe(true);
});
it("clears the needs-input condition when a follow-up is sent", async () => {
const { adapter } = createFakeOrbAdapter({
eventsByTurn: [
[makeMessageEvent("NEEDS_INPUT: clarify?", 1)],
[makeMessageEvent("WORK_COMPLETE: done", 2)],
],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
expect(pm.getRunStatus("issue-42")).toBe("needs-input");
const result = await pm.sendMessage("issue-42", "Use POST");
expect(result.status).toBe("completing");
expect(result.needsInputQuestion).toBeUndefined();
});
});
// -----------------------------------------------------------------------
// 4. Cancellation
// -----------------------------------------------------------------------
describe("cancellation", () => {
it("cancels and disposes the Orb run", async () => {
const { adapter, runs } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("NEEDS_INPUT: wait", 1)],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
await pm.cancel("issue-42");
expect(runs[0]!.cancelCalled).toBe(true);
expect(runs[0]!.disposeCalled).toBe(true);
expect(pm.getRunStatus("issue-42")).toBe("cancelled");
});
it("is idempotent — cancelling a non-existent run is a no-op", async () => {
const { adapter } = createFakeOrbAdapter();
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await expect(pm.cancel("nonexistent")).resolves.toBeUndefined();
});
it("is idempotent — cancelling twice does not error", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("working...", 1)],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
await pm.cancel("issue-42");
await pm.cancel("issue-42");
expect(pm.getRunStatus("issue-42")).toBe("cancelled");
});
});
// -----------------------------------------------------------------------
// 5. Duplicate-start prevention
// -----------------------------------------------------------------------
describe("duplicate-start prevention", () => {
it("does not create a second Orb run for an active issue", async () => {
const { adapter, runs } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("NEEDS_INPUT: hmm", 1)],
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
const first = await pm.startIssue(baseStartInput());
const second = await pm.startIssue(baseStartInput());
expect(runs).toHaveLength(1);
expect(second.orbId).toBe(first.orbId);
expect(second.status).toBe("needs-input");
});
it("allows starting a new run after the previous one completed", async () => {
const { adapter, runs } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: done", 1)],
});
const { port: gitPort } = createFakeGitLifecycle();
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
await pm.complete({ issueId: "issue-42" });
expect(pm.getRunStatus("issue-42")).toBe("completed");
// A terminal run allows re-creating via startIssue.
const second = await pm.startIssue(baseStartInput());
expect(runs.length).toBeGreaterThanOrEqual(2);
expect(second.orbId).not.toBe(runs[0]!.orbId);
});
});
// -----------------------------------------------------------------------
// 6. Successful PR completion
// -----------------------------------------------------------------------
describe("successful PR completion", () => {
it("runs the Git lifecycle, creates a PR, stores artifacts, and marks completed", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: implemented", 1)],
});
const artifacts: ProjectArtifact[] = [];
const { port: gitPort, publishCalls } = createFakeGitLifecycle();
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
onArtifact: (a) => artifacts.push(a),
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
const result = await pm.complete({ issueId: "issue-42" });
expect(result.status).toBe("pull_request_open");
expect(result.pullRequest?.number).toBe(7);
expect(pm.getRunStatus("issue-42")).toBe("completed");
expect(publishCalls).toHaveLength(1);
expect(publishCalls[0]?.branchName).toBe("work/issue-42");
const artifactTypes = artifacts.map((a) => a.type);
expect(artifactTypes).toContain("branch");
expect(artifactTypes).toContain("commit");
expect(artifactTypes).toContain("pull_request");
expect(artifactTypes).toContain("agent_summary");
});
it("marks completed with no_changes when the Git lifecycle reports no changes", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: nothing to do", 1)],
});
const { port: gitPort } = createFakeGitLifecycle({
result: {
baseBranch: "main",
branch: "work/issue-42",
status: "no_changes",
},
});
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
const result = await pm.complete({ issueId: "issue-42" });
expect(result.status).toBe("no_changes");
expect(pm.getRunStatus("issue-42")).toBe("completed");
});
});
// -----------------------------------------------------------------------
// 7. Failed PR creation recovery
// -----------------------------------------------------------------------
describe("failed PR creation recovery", () => {
it("marks the run as failed and raises a tagged error when PR creation fails", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: done", 1)],
});
const { port: gitPort } = createFakeGitLifecycle({
failWith: new Error("Remote rejected push"),
});
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
try {
await pm.complete({ issueId: "issue-42" });
expect.fail("Should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ProjectManagerError);
expect((error as ProjectManagerError).reason).toBe("GitRejection");
}
expect(pm.getRunStatus("issue-42")).toBe("failed");
});
it("allows retrying completion after a failed attempt (idempotent commit+push)", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: done", 1)],
});
const { port: gitPort, publishCalls } = createFakeGitLifecycle({
failOnFirstAttempt: true,
});
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
try {
await pm.complete({ issueId: "issue-42" });
} catch {
// expected first-attempt failure
}
expect(pm.getRunStatus("issue-42")).toBe("failed");
// Retry: the Orb run still exists, the branch is preserved.
const result = await pm.complete({ issueId: "issue-42" });
expect(result.status).toBe("pull_request_open");
expect(pm.getRunStatus("issue-42")).toBe("completed");
expect(publishCalls).toHaveLength(2);
});
});
// -----------------------------------------------------------------------
// 8. Infrastructure failure mapping
// -----------------------------------------------------------------------
describe("infrastructure failure mapping", () => {
it("maps a failed Orb creation to InfrastructureFailure", async () => {
const failingAdapter: OrbAdapter = {
createOrb: () => Promise.reject(new Error("Docker daemon unavailable")),
};
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: failingAdapter,
});
try {
await pm.startIssue(baseStartInput());
expect.fail("Should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ProjectManagerError);
expect((error as ProjectManagerError).reason).toBe(
"InfrastructureFailure"
);
}
});
it("maps a failed prepareRepository to InfrastructureFailure", async () => {
const { adapter } = createFakeOrbAdapter({
failOnPrepare: true,
});
const pm = new OrbProjectManager({
createGitLifecycle: () => createFakeGitLifecycle().port,
orbAdapter: adapter,
});
try {
await pm.startIssue(baseStartInput());
expect.fail("Should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ProjectManagerError);
expect((error as ProjectManagerError).reason).toBe(
"InfrastructureFailure"
);
}
});
it("does not create duplicate events from idempotent completion", async () => {
const { adapter } = createFakeOrbAdapter({
defaultEvents: [makeMessageEvent("WORK_COMPLETE: done", 1)],
});
const { port: gitPort } = createFakeGitLifecycle();
const pm = new OrbProjectManager({
createGitLifecycle: () => gitPort,
orbAdapter: adapter,
});
await pm.startIssue(baseStartInput());
await pm.complete({ issueId: "issue-42" });
const eventsBefore = pm.getRunEvents("issue-42").length;
const result = await pm.complete({ issueId: "issue-42" });
const eventsAfter = pm.getRunEvents("issue-42").length;
// Idempotent: returns cached result without duplicating events.
expect(result.status).toBe("pull_request_open");
expect(eventsAfter).toBe(eventsBefore);
});
});
});

View File

@@ -1,636 +0,0 @@
/* eslint-disable max-classes-per-file -- domain errors are grouped by concern. */
import { Schema } from "effect";
import { buildContextPack } from "./context-pack";
import type { ContextPackInput } from "./context-pack";
import type { OrbEvent } from "./events";
import type {
GitLifecyclePort,
GitLifecycleResult,
OrbAdapter,
OrbCreatePortInput,
OrbRunPort,
ProjectArtifact,
RunStatus,
} from "./ports";
import { isWorkComplete, mapOrbEvent } from "./project-events";
import type { ProjectRunEvent } from "./project-events";
// ---------------------------------------------------------------------------
// Tagged errors — the failure-mapping surface
// ---------------------------------------------------------------------------
export const ProjectManagerErrorReason = Schema.Literals([
"RunNotFound",
"SessionNotReady",
"RunTerminal",
"DuplicateActiveRun",
"InfrastructureFailure",
"NeedsInput",
"GitRejection",
"PullRequestFailure",
"Cancelled",
"UnrecoverableFailure",
]);
export type ProjectManagerErrorReason = typeof ProjectManagerErrorReason.Type;
export class ProjectManagerError extends Schema.TaggedErrorClass<ProjectManagerError>()(
"ProjectManagerError",
{
issueId: Schema.String,
message: Schema.String,
reason: ProjectManagerErrorReason,
}
) {}
// ---------------------------------------------------------------------------
// Active run record — one per managed issue
// ---------------------------------------------------------------------------
interface ActiveRun {
readonly issueId: string;
readonly orbId: string;
readonly runId: string;
readonly orb: OrbRunPort;
sessionId: string | undefined;
status: RunStatus;
readonly projectEvents: ProjectRunEvent[];
result: GitLifecycleResult | undefined;
needsInputQuestion: string | undefined;
readonly contextPack: string;
lastTurnEventIndex: number;
readonly baseBranch: string;
readonly branchName: string;
readonly issueNumber: number;
readonly issueTitle: string;
readonly repositoryPath: string;
readonly workspacePath: string;
}
// ---------------------------------------------------------------------------
// Dependencies injected into the orchestrator
// ---------------------------------------------------------------------------
export interface OrbProjectManagerDeps {
readonly orbAdapter: OrbAdapter;
readonly createGitLifecycle: (orb: OrbRunPort) => GitLifecyclePort;
readonly onProjectEvent?: (event: ProjectRunEvent) => void;
readonly onArtifact?: (artifact: ProjectArtifact) => void;
}
// ---------------------------------------------------------------------------
// Input types for the orchestration API
// ---------------------------------------------------------------------------
export interface StartIssueInput {
readonly issueId: string;
readonly projectId: string;
readonly runId: string;
readonly context: OrbCreatePortInput["context"];
readonly gateway: OrbCreatePortInput["gateway"];
readonly docker: OrbCreatePortInput["docker"];
readonly baseBranch: string;
readonly branchName: string;
readonly contextPack: ContextPackInput;
readonly workspacePath?: string;
readonly repositoryPath?: string;
readonly issueNumber?: number;
readonly issueTitle?: string;
}
export interface StartIssueResult {
readonly issueId: string;
readonly orbId: string;
readonly runId: string;
readonly sessionId: string | undefined;
readonly status: RunStatus;
readonly needsInputQuestion?: string;
}
export interface SendMessageResult {
readonly issueId: string;
readonly status: RunStatus;
readonly needsInputQuestion?: string;
}
export interface CompleteInput {
readonly issueId: string;
readonly verification?: "passed" | "failed" | "not-run";
readonly commitMessage?: string;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const isTerminal = (status: RunStatus): boolean =>
status === "completed" || status === "failed" || status === "cancelled";
const isSessionValid = (run: ActiveRun): boolean =>
run.sessionId !== undefined && !isTerminal(run.status);
const timestamp = () => new Date().toISOString();
const wrapError = (
error: unknown,
issueId: string,
reason: ProjectManagerErrorReason,
fallback: string
): ProjectManagerError => {
const message = error instanceof Error ? error.message : String(error);
return new ProjectManagerError({
issueId,
message: message.length > 0 ? message : fallback,
reason,
});
};
const isGitRejection = (error: unknown): boolean => {
if (!(error instanceof Error)) {
return false;
}
const message = error.message.toLowerCase();
return (
message.includes("rejected") ||
message.includes("authentication") ||
message.includes("permission denied") ||
message.includes("remote")
);
};
// ---------------------------------------------------------------------------
// OrbProjectManager — thin orchestration agent over the merged Orb runtime
//
// Responsibilities:
// - Create or resume an Orb run per issue (idempotent)
// - Assemble a context pack and send it as the implementation objective
// - Project OrbEvents into durable ProjectRunEvents (no parallel event system)
// - Detect needs-input and work-complete conditions
// - Forward follow-up messages to the same OpenCode session
// - Drive the Git publish lifecycle on completion (never auto-merge)
// - Store branch/commit/diff/PR/summary as project artifacts
// ---------------------------------------------------------------------------
export class OrbProjectManager {
private readonly activeRuns = new Map<string, ActiveRun>();
private readonly deps: OrbProjectManagerDeps;
constructor(deps: OrbProjectManagerDeps) {
this.deps = deps;
}
// -----------------------------------------------------------------------
// Public state queries
// -----------------------------------------------------------------------
getRunStatus(issueId: string): RunStatus | undefined {
return this.activeRuns.get(issueId)?.status;
}
getRunEvents(issueId: string): readonly ProjectRunEvent[] {
return this.activeRuns.get(issueId)?.projectEvents ?? [];
}
getRunResult(issueId: string): GitLifecycleResult | undefined {
return this.activeRuns.get(issueId)?.result;
}
// -----------------------------------------------------------------------
// Start or resume an Orb run for an issue
// -----------------------------------------------------------------------
async startIssue(input: StartIssueInput): Promise<StartIssueResult> {
const existing = this.activeRuns.get(input.issueId);
// Idempotency: a still-active run is reused, never duplicated.
if (existing && !isTerminal(existing.status)) {
return {
issueId: input.issueId,
needsInputQuestion: existing.needsInputQuestion,
orbId: existing.orbId,
runId: existing.runId,
sessionId: existing.sessionId,
status: existing.status,
};
}
let orb: OrbRunPort;
try {
orb = await this.deps.orbAdapter.createOrb({
context: input.context,
docker: input.docker,
gateway: input.gateway,
identity: {
projectId: input.projectId,
runId: input.runId,
workUnitId: input.issueId,
},
});
} catch (error) {
throw wrapError(
error,
input.issueId,
"InfrastructureFailure",
"Failed to create Orb run"
);
}
const contextPack = buildContextPack(input.contextPack);
const run: ActiveRun = {
baseBranch: input.baseBranch,
branchName: input.branchName,
contextPack,
issueId: input.issueId,
issueNumber: input.issueNumber ?? 0,
issueTitle: input.issueTitle ?? input.issueId,
lastTurnEventIndex: 0,
needsInputQuestion: undefined,
orb,
orbId: orb.orbId,
projectEvents: [],
repositoryPath: input.repositoryPath ?? "",
result: undefined,
runId: orb.runId,
sessionId: undefined,
status: "starting",
workspacePath: input.workspacePath ?? "/mnt/sandbox/repository",
};
this.activeRuns.set(input.issueId, run);
// Subscribe to OrbEvents and project them into durable ProjectRunEvents.
orb.onEvent((orbEvent: OrbEvent) => {
this.processOrbEvent(orbEvent, run);
});
this.emitProjectEvent(run, "run.started", {
text: `Started Orb run for issue ${input.issueId}`,
});
try {
await orb.prepareRepository({
baseBranch: input.baseBranch,
branchName: input.branchName,
});
this.emitProjectEvent(run, "run.repository_prepared", {
text: `Repository prepared on branch ${input.branchName}`,
});
const sessionId = await orb.openSession();
run.sessionId = sessionId;
run.status = "working";
this.emitProjectEvent(run, "run.session_opened", {
text: `Session ${sessionId} opened`,
});
// Record turn boundary before sending the implementation objective.
run.lastTurnEventIndex = run.projectEvents.length;
// Send the implementation objective (the assembled context pack).
await orb.sendTask(contextPack);
// After the turn, check for needs-input or work-complete signals.
OrbProjectManager.evaluateTurnOutcome(run);
} catch (error) {
if (error instanceof ProjectManagerError) {
throw error;
}
throw wrapError(
error,
input.issueId,
"InfrastructureFailure",
"Orb run failed during startup"
);
}
return {
issueId: input.issueId,
needsInputQuestion: run.needsInputQuestion,
orbId: run.orbId,
runId: run.runId,
sessionId: run.sessionId,
status: run.status,
};
}
// -----------------------------------------------------------------------
// Forward a follow-up message to the same OpenCode session
// -----------------------------------------------------------------------
async sendMessage(
issueId: string,
message: string
): Promise<SendMessageResult> {
const run = this.activeRuns.get(issueId);
if (!run) {
throw new ProjectManagerError({
issueId,
message: `No active run for issue ${issueId}`,
reason: "RunNotFound",
});
}
if (isTerminal(run.status)) {
throw new ProjectManagerError({
issueId,
message: `Run for issue ${issueId} is in terminal state ${run.status}`,
reason: "RunTerminal",
});
}
if (!isSessionValid(run)) {
throw new ProjectManagerError({
issueId,
message: `Session is not open for issue ${issueId}`,
reason: "SessionNotReady",
});
}
// Clear any prior needs-input condition and record turn boundary.
run.needsInputQuestion = undefined;
run.status = "working";
run.lastTurnEventIndex = run.projectEvents.length;
try {
await run.orb.sendTask(message);
OrbProjectManager.evaluateTurnOutcome(run);
} catch (error) {
throw wrapError(
error,
issueId,
"InfrastructureFailure",
"Failed to forward message to OpenCode session"
);
}
return {
issueId,
needsInputQuestion: run.needsInputQuestion,
status: run.status,
};
}
// -----------------------------------------------------------------------
// Cancel — terminate OpenCode and sandbox, then dispose
// -----------------------------------------------------------------------
async cancel(issueId: string): Promise<void> {
const run = this.activeRuns.get(issueId);
if (!run) {
// Idempotent cancel: a non-existent run is already "cancelled".
return;
}
if (run.status === "cancelled") {
return;
}
try {
await run.orb.cancel();
} catch {
// best-effort: proceed to dispose even if cancel failed
}
try {
await run.orb.dispose();
} catch {
// best-effort cleanup
}
run.status = "cancelled";
this.emitProjectEvent(run, "run.cancelled", {
text: "Run cancelled by user",
});
}
// -----------------------------------------------------------------------
// Complete — run Git publish lifecycle, store artifacts, mark completed
// -----------------------------------------------------------------------
async complete(input: CompleteInput): Promise<GitLifecycleResult> {
const run = this.activeRuns.get(input.issueId);
if (!run) {
throw new ProjectManagerError({
issueId: input.issueId,
message: `No active run for issue ${input.issueId}`,
reason: "RunNotFound",
});
}
// Idempotency: a completed run with an existing result is returned as-is.
if (run.status === "completed" && run.result !== undefined) {
return run.result;
}
if (run.status === "cancelled") {
throw new ProjectManagerError({
issueId: input.issueId,
message: "Cannot complete a cancelled run",
reason: "Cancelled",
});
}
const git = this.deps.createGitLifecycle(run.orb);
const verification = input.verification ?? "passed";
run.status = "completing";
let gitResult: GitLifecycleResult;
try {
gitResult = await git.publish({
baseBranch: run.baseBranch,
branchName: run.branchName,
commitMessage: input.commitMessage,
issueNumber: run.issueNumber,
issueTitle: run.issueTitle,
repositoryPath: run.repositoryPath,
verification,
workspace: run.workspacePath,
});
} catch (error) {
run.status = "failed";
const reason = isGitRejection(error)
? "GitRejection"
: "PullRequestFailure";
this.emitProjectEvent(run, "run.failed", {
text: error instanceof Error ? error.message : String(error),
});
throw wrapError(
error,
input.issueId,
reason,
"Git publish lifecycle failed"
);
}
run.result = gitResult;
this.storeArtifacts(run, gitResult);
// Mark completed only when a PR exists or a verified no-change result.
if (
(gitResult.status === "pull_request_open" && gitResult.pullRequest) ||
gitResult.status === "no_changes"
) {
run.status = "completed";
this.emitProjectEvent(run, "run.completed", {
text: gitResult.pullRequest
? `PR #${gitResult.pullRequest.number} created: ${gitResult.pullRequest.url}`
: "No changes to publish",
});
} else {
run.status = "failed";
this.emitProjectEvent(run, "run.failed", {
text: `Git lifecycle stopped at ${gitResult.status} without a pull request`,
});
throw new ProjectManagerError({
issueId: input.issueId,
message: `Git lifecycle did not produce a pull request (status: ${gitResult.status})`,
reason: "PullRequestFailure",
});
}
return gitResult;
}
// -----------------------------------------------------------------------
// Dispose all runs (for graceful shutdown)
// -----------------------------------------------------------------------
async disposeAll(): Promise<void> {
const issues = [...this.activeRuns.keys()];
await Promise.allSettled(
issues.map(async (issueId) => {
const run = this.activeRuns.get(issueId);
if (run && !isTerminal(run.status)) {
try {
await run.orb.dispose();
} catch {
// best-effort
}
}
})
);
}
// -----------------------------------------------------------------------
// Internal: OrbEvent processing
// -----------------------------------------------------------------------
private processOrbEvent(orbEvent: OrbEvent, run: ActiveRun): void {
const projectEvent = mapOrbEvent(orbEvent, run.issueId, run.runId);
if (projectEvent !== undefined) {
run.projectEvents.push(projectEvent);
this.deps.onProjectEvent?.(projectEvent);
if (
projectEvent.type === "run.needs_input" &&
run.needsInputQuestion === undefined
) {
run.needsInputQuestion = projectEvent.text;
}
}
}
// -----------------------------------------------------------------------
// Internal: evaluate the outcome of a completed model turn
// -----------------------------------------------------------------------
private static evaluateTurnOutcome(run: ActiveRun): void {
// Only scan events from the current turn (after the last turn boundary).
const turnEvents = run.projectEvents.slice(run.lastTurnEventIndex);
// Check for needs-input: the mapOrbEvent step already extracted the marker
// into a run.needs_input event with the question text. A run.needs_input
// event IS the signal — no need to re-extract the marker from its text.
const needsInputEvent = [...turnEvents]
.toReversed()
.find((event) => event.type === "run.needs_input");
if (needsInputEvent !== undefined) {
run.status = "needs-input";
run.needsInputQuestion = needsInputEvent.text ?? "Agent requires input";
return;
}
// Check for work-complete marker in agent messages from this turn.
const turnMessages = turnEvents.filter(
(event) => event.type === "run.agent_message"
);
const hasWorkComplete = turnMessages.some(
(event) => event.text !== undefined && isWorkComplete(event.text)
);
if (hasWorkComplete && run.status === "working") {
run.status = "completing";
}
}
// -----------------------------------------------------------------------
// Internal: emit a synthetic project event (not derived from an OrbEvent)
// -----------------------------------------------------------------------
private emitProjectEvent(
run: ActiveRun,
type: ProjectRunEvent["type"],
fields: { text?: string; exitCode?: number; toolName?: string }
): void {
const event: ProjectRunEvent = {
exitCode: fields.exitCode,
issueId: run.issueId,
runId: run.runId,
sequence: run.projectEvents.length + 1,
text: fields.text,
timestamp: timestamp(),
toolName: fields.toolName,
type,
};
run.projectEvents.push(event);
this.deps.onProjectEvent?.(event);
}
// -----------------------------------------------------------------------
// Internal: store artifacts from the Git lifecycle result
// -----------------------------------------------------------------------
private storeArtifacts(run: ActiveRun, result: GitLifecycleResult): void {
const ts = timestamp();
const base = { issueId: run.issueId, runId: run.runId };
const emitArtifact = (
type: ProjectArtifact["type"],
path: string,
content: string
): void => {
const artifact: ProjectArtifact = {
...base,
content,
path,
timestamp: ts,
type,
};
this.deps.onArtifact?.(artifact);
};
emitArtifact("branch", "branch.txt", result.branch);
if (result.commitSha) {
emitArtifact("commit", "commit.txt", result.commitSha);
}
if (result.pullRequest) {
emitArtifact(
"pull_request",
"pull_request.json",
JSON.stringify(result.pullRequest, null, 2)
);
}
const lastMessage = [...run.projectEvents]
.toReversed()
.find(
(event) =>
event.type === "run.agent_message" || event.type === "run.needs_input"
);
if (lastMessage?.text) {
emitArtifact("agent_summary", "summary.md", lastMessage.text);
}
}
}

View File

@@ -1,107 +0,0 @@
import { describe, expect, it } from "vitest";
import { evaluatePermission, isDangerousPermission } from "./permission-policy";
const allowOption = { id: "allow", title: "Allow" };
const denyOption = { id: "deny", title: "Deny" };
describe("isDangerousPermission", () => {
it("flags merge operations", () => {
expect(
isDangerousPermission({
requestId: "r1",
toolCall: { title: "git merge main" },
})
).toBe(true);
});
it("flags production deployment", () => {
expect(
isDangerousPermission({
requestId: "r2",
toolCall: { title: "deploy to production" },
})
).toBe(true);
});
it("flags secret access", () => {
expect(
isDangerousPermission({
requestId: "r3",
toolCall: { title: "read secrets" },
})
).toBe(true);
});
it("flags credential access", () => {
expect(
isDangerousPermission({
requestId: "r4",
toolCall: { title: "access credentials" },
})
).toBe(true);
});
it("does not flag safe operations", () => {
expect(
isDangerousPermission({
requestId: "r5",
toolCall: { title: "run tests" },
})
).toBe(false);
});
it("does not flag file edits", () => {
expect(
isDangerousPermission({
requestId: "r6",
toolCall: { title: "edit src/index.ts" },
})
).toBe(false);
});
});
describe("evaluatePermission", () => {
it("allows safe operations and picks allow option", () => {
const decision = evaluatePermission({
options: [allowOption, denyOption],
requestId: "r1",
toolCall: { title: "run bun test" },
});
expect(decision.allow).toBe(true);
expect(decision.optionId).toBe("allow");
});
it("denies dangerous operations and picks deny option", () => {
const decision = evaluatePermission({
options: [allowOption, denyOption],
requestId: "r2",
toolCall: { title: "git merge main" },
});
expect(decision.allow).toBe(false);
expect(decision.optionId).toBe("deny");
});
it("falls back to last option when no explicit deny exists", () => {
const decision = evaluatePermission({
options: [
{ id: "ok", title: "OK" },
{ id: "cancel", title: "Cancel" },
],
requestId: "r3",
toolCall: { title: "deploy to production" },
});
expect(decision.allow).toBe(false);
expect(decision.optionId).toBe("cancel");
});
it("handles empty options", () => {
const decision = evaluatePermission({
options: [],
requestId: "r4",
toolCall: { title: "run tests" },
});
expect(decision.allow).toBe(true);
expect(decision.optionId).toBeUndefined();
});
});

View File

@@ -1,90 +0,0 @@
/**
* Narrow permission policy for Orb sessions.
*
* Denies merge, production deployment, secret access, and external
* communications. Allows all other operations. Used as the callback for
* ACP permission_request events with permissionPolicy: "ask".
*/
interface PermissionOption {
readonly id: string;
readonly title?: string;
readonly description?: string;
}
interface PermissionRequestLike {
readonly requestId: string;
readonly options?: readonly PermissionOption[];
readonly toolCall?: {
readonly title?: string;
readonly kind?: string;
readonly name?: string;
};
}
const DENY_PATTERNS = [
/\bmerge\b/iu,
/\bdeploy\b.*\bprod/iu,
/\bproduction\b/iu,
/\bsecret/iu,
/\bcredential/iu,
/\bpassword\b/iu,
/\bapi[_-]?key\b/iu,
/\bpush\s+to\s+(?<branch>main|master)\b/iu,
];
/** Evaluate whether a permission request is dangerous. */
export const isDangerousPermission = (
request: PermissionRequestLike
): boolean => {
const text = [
request.toolCall?.title,
request.toolCall?.kind,
request.toolCall?.name,
]
.filter((s): s is string => typeof s === "string")
.join(" ");
return DENY_PATTERNS.some((pattern) => pattern.test(text));
};
/**
* Pick the option ID that matches the desired decision. Falls back to the
* last option (typically deny) for safety when no explicit deny option exists,
* or the first option (typically allow) when no explicit allow option exists.
*/
const pickOption = (
options: readonly PermissionOption[],
allow: boolean
): string | undefined => {
if (options.length === 0) {
return undefined;
}
if (allow) {
const match = options.find(
(o) =>
/allow|accept|yes|permit/iu.test(o.title ?? "") ||
/allow|accept|yes|permit/iu.test(o.description ?? "")
);
return match?.id ?? options[0]?.id;
}
const match = options.find(
(o) =>
/deny|reject|no|cancel/iu.test(o.title ?? "") ||
/deny|reject|no|cancel/iu.test(o.description ?? "")
);
return match?.id ?? options.at(-1)?.id;
};
export interface PermissionDecision {
readonly allow: boolean;
readonly optionId: string | undefined;
}
/** Evaluate a permission request and return the decision. */
export const evaluatePermission = (
request: PermissionRequestLike
): PermissionDecision => {
const dangerous = isDangerousPermission(request);
const optionId = pickOption(request.options ?? [], !dangerous);
return { allow: !dangerous, optionId };
};

View File

@@ -1,136 +0,0 @@
/* eslint-disable max-classes-per-file -- domain errors are grouped by concern. */
import { Schema } from "effect";
import type {
OrbIdentity,
OrbModelGatewayConfig,
OrbProjectContext,
} from "./domain";
import type { OrbEvent } from "./events";
// ---------------------------------------------------------------------------
// Command result — shared shape for sandbox command execution
// ---------------------------------------------------------------------------
export interface CommandResult {
readonly exitCode: number;
readonly stderr: string;
readonly stdout: string;
}
// ---------------------------------------------------------------------------
// Orb port — abstracts OrbRuntime/OrbHandle for testability
// ---------------------------------------------------------------------------
export interface PrepareRepoInput {
readonly baseBranch?: string;
readonly branchName?: string;
}
export interface OrbRunPort {
readonly orbId: string;
readonly runId: string;
readonly sessionId: string | undefined;
readonly state: string;
readonly onEvent: (listener: (event: OrbEvent) => void) => () => void;
readonly prepareRepository: (input: PrepareRepoInput) => Promise<void>;
readonly openSession: () => Promise<string>;
readonly sendTask: (prompt: string) => Promise<unknown>;
readonly executeCommand: (
command: string,
cwd?: string
) => Promise<CommandResult>;
readonly cancel: () => Promise<void>;
readonly dispose: () => Promise<void>;
}
export interface OrbCreatePortInput {
readonly context: OrbProjectContext;
readonly gateway: OrbModelGatewayConfig;
readonly identity: OrbIdentity;
readonly docker: {
readonly hostWorkspacePath: string;
readonly containerName?: string;
readonly image?: string;
};
}
export interface OrbAdapter {
readonly createOrb: (input: OrbCreatePortInput) => Promise<OrbRunPort>;
}
// ---------------------------------------------------------------------------
// Git lifecycle port — abstracts the Gitea lifecycle for testability
// ---------------------------------------------------------------------------
export interface GitPublishInput {
readonly workspace: string;
readonly baseBranch: string;
readonly branchName: string;
readonly issueNumber: number;
readonly issueTitle: string;
readonly repositoryPath: string;
readonly commitMessage?: string;
readonly verification: "passed" | "failed" | "not-run";
}
export interface GitPullRequestMeta {
readonly baseBranch: string;
readonly branch: string;
readonly number: number;
readonly status: "open" | "closed" | "merged";
readonly url: string;
}
export interface GitLifecycleResult {
readonly baseBranch: string;
readonly branch: string;
readonly commitSha?: string;
readonly pullRequest?: GitPullRequestMeta;
readonly status:
| "no_changes"
| "committed"
| "pushed"
| "pull_request_open"
| "failed";
}
export interface GitLifecyclePort {
readonly publish: (input: GitPublishInput) => Promise<GitLifecycleResult>;
}
// ---------------------------------------------------------------------------
// Project artifact — durable output stored after a run
// ---------------------------------------------------------------------------
export const ProjectArtifactSchema = Schema.Struct({
content: Schema.String,
issueId: Schema.String,
path: Schema.String,
runId: Schema.String,
timestamp: Schema.String,
type: Schema.Literals([
"branch",
"commit",
"diff",
"verification_report",
"pull_request",
"agent_summary",
]),
});
export type ProjectArtifact = typeof ProjectArtifactSchema.Type;
// ---------------------------------------------------------------------------
// Orchestration status for a managed issue run
// ---------------------------------------------------------------------------
export const RunStatus = Schema.Literals([
"starting",
"working",
"needs-input",
"completing",
"completed",
"failed",
"cancelled",
]);
export type RunStatus = typeof RunStatus.Type;

View File

@@ -1,123 +0,0 @@
import { describe, expect, it } from "vitest";
import { makeOrbEvent } from "./events";
import {
extractNeedsInputQuestion,
isWorkComplete,
mapOrbEvent,
NEEDS_INPUT_MARKER,
WORK_COMPLETE_MARKER,
} from "./project-events";
describe("marker detection", () => {
it("extracts the needs-input question from a marker message", () => {
const text = `Some preamble\n${NEEDS_INPUT_MARKER} Which port should I use?`;
expect(extractNeedsInputQuestion(text)).toBe("Which port should I use?");
});
it("returns undefined for a message without the marker", () => {
expect(extractNeedsInputQuestion("just working")).toBeUndefined();
});
it("returns a default question when marker has no text after it", () => {
expect(extractNeedsInputQuestion(NEEDS_INPUT_MARKER)).toBe(
"Agent requires input"
);
});
it("detects the work-complete marker", () => {
expect(isWorkComplete(`${WORK_COMPLETE_MARKER} all good`)).toBe(true);
expect(isWorkComplete("still working")).toBe(false);
});
});
describe("mapOrbEvent", () => {
const issueId = "issue-1";
const runId = "run-1";
it("maps session_opened to run.session_opened", () => {
const event = mapOrbEvent(
makeOrbEvent(1, "session_opened", { text: "Session abc opened" }),
issueId,
runId
);
expect(event?.type).toBe("run.session_opened");
expect(event?.text).toBe("Session abc opened");
expect(event?.issueId).toBe(issueId);
expect(event?.runId).toBe(runId);
});
it("maps agent_message_completed with needs-input marker to run.needs_input", () => {
const event = mapOrbEvent(
makeOrbEvent(2, "agent_message_completed", {
text: `${NEEDS_INPUT_MARKER} What name?`,
}),
issueId,
runId
);
expect(event?.type).toBe("run.needs_input");
expect(event?.text).toBe("What name?");
});
it("maps agent_message_completed without marker to run.agent_message", () => {
const event = mapOrbEvent(
makeOrbEvent(3, "agent_message_completed", { text: "I fixed the bug" }),
issueId,
runId
);
expect(event?.type).toBe("run.agent_message");
expect(event?.text).toBe("I fixed the bug");
});
it("maps command_executed to run.command_executed with exit code", () => {
const event = mapOrbEvent(
makeOrbEvent(4, "command_executed", { command: "npm test", exitCode: 0 }),
issueId,
runId
);
expect(event?.type).toBe("run.command_executed");
expect(event?.exitCode).toBe(0);
expect(event?.text).toBe("npm test");
});
it("maps tool_call events to run.agent_progress", () => {
const started = mapOrbEvent(
makeOrbEvent(5, "tool_call_started", { toolName: "edit_file" }),
issueId,
runId
);
expect(started?.type).toBe("run.agent_progress");
expect(started?.toolName).toBe("edit_file");
});
it("maps session_failed to run.failed", () => {
const event = mapOrbEvent(
makeOrbEvent(6, "session_failed", { text: "crashed" }),
issueId,
runId
);
expect(event?.type).toBe("run.failed");
});
it("returns undefined for chunked events and vm_booted", () => {
expect(
mapOrbEvent(
makeOrbEvent(7, "agent_message_chunk", { text: "partial" }),
issueId,
runId
)
).toBeUndefined();
expect(
mapOrbEvent(makeOrbEvent(8, "vm_booted"), issueId, runId)
).toBeUndefined();
});
it("maps permission_requested to run.permission_requested", () => {
const event = mapOrbEvent(
makeOrbEvent(9, "permission_requested", { text: "needs approval" }),
issueId,
runId
);
expect(event?.type).toBe("run.permission_requested");
});
});

View File

@@ -1,171 +0,0 @@
import { Schema } from "effect";
import type { OrbEvent } from "./events";
// ---------------------------------------------------------------------------
// Durable project events — human-meaningful projections of Orb execution
//
// These are NOT raw OpenCode events. Each variant maps to a product-level
// concept the UI and work-graph understand. Raw OrbEvents are preserved for
// audit; this is the durable projection layer.
// ---------------------------------------------------------------------------
export const ProjectRunEventVariant = Schema.Literals([
"run.started",
"run.repository_prepared",
"run.session_opened",
"run.agent_message",
"run.agent_progress",
"run.command_executed",
"run.needs_input",
"run.permission_requested",
"run.completed",
"run.failed",
"run.cancelled",
"run.session_closed",
]);
export type ProjectRunEventVariant = typeof ProjectRunEventVariant.Type;
export const ProjectRunEvent = Schema.Struct({
exitCode: Schema.UndefinedOr(Schema.Int),
issueId: Schema.String,
runId: Schema.String,
sequence: Schema.Number,
text: Schema.UndefinedOr(Schema.String),
timestamp: Schema.String,
toolName: Schema.UndefinedOr(Schema.String),
type: ProjectRunEventVariant,
});
export type ProjectRunEvent = typeof ProjectRunEvent.Type;
// ---------------------------------------------------------------------------
// Marker detection — OpenCode signals product-level conditions via markers
// ---------------------------------------------------------------------------
/** Prefix the agent emits when it cannot proceed without human input. */
export const NEEDS_INPUT_MARKER = "NEEDS_INPUT:";
/**
* Prefix the agent emits when implementation and verification are complete
* and the orchestrator should proceed to the Git publish lifecycle.
*/
export const WORK_COMPLETE_MARKER = "WORK_COMPLETE:";
export const extractNeedsInputQuestion = (text: string): string | undefined => {
const index = text.indexOf(NEEDS_INPUT_MARKER);
if (index === -1) {
return undefined;
}
const after = text.slice(index + NEEDS_INPUT_MARKER.length).trim();
return after.length > 0 ? after.slice(0, 4000) : "Agent requires input";
};
export const isWorkComplete = (text: string): boolean =>
text.includes(WORK_COMPLETE_MARKER);
// ---------------------------------------------------------------------------
// OrbEvent → ProjectRunEvent translation
// ---------------------------------------------------------------------------
/**
* Translate one normalized OrbEvent into zero or one durable ProjectRunEvent.
* Returns undefined for OrbEvents that have no product-meaningful projection
* (e.g. chunked intermediate output that is only useful in the raw audit log).
*/
export const mapOrbEvent = (
orbEvent: OrbEvent,
issueId: string,
runId: string
): ProjectRunEvent | undefined => {
const base: {
exitCode: number | undefined;
issueId: string;
runId: string;
sequence: number;
text: string | undefined;
timestamp: string;
toolName: string | undefined;
} = {
exitCode: undefined,
issueId,
runId,
sequence: orbEvent.sequence,
text: undefined,
timestamp: orbEvent.timestamp,
toolName: undefined,
};
switch (orbEvent.type) {
case "session_opened": {
return {
...base,
text: orbEvent.text ?? "Session opened",
type: "run.session_opened",
};
}
case "vm_booted": {
return undefined;
}
case "agent_message_completed": {
const text = orbEvent.text ?? "";
if (extractNeedsInputQuestion(text) !== undefined) {
return {
...base,
text: extractNeedsInputQuestion(text),
type: "run.needs_input",
};
}
return {
...base,
text,
type: "run.agent_message",
};
}
case "agent_message_chunk":
case "agent_thought_chunk": {
return undefined;
}
case "tool_call_started":
case "tool_call_completed": {
return {
...base,
text: undefined,
toolName: orbEvent.toolName,
type: "run.agent_progress",
};
}
case "command_executed": {
return {
...base,
exitCode: orbEvent.exitCode,
text: orbEvent.command,
type: "run.command_executed",
};
}
case "permission_requested":
case "permission_denied": {
return {
...base,
text: orbEvent.text ?? "Permission requested",
type: "run.permission_requested",
};
}
case "session_failed": {
return {
...base,
text: orbEvent.text ?? "Session failed",
type: "run.failed",
};
}
case "session_closed": {
return {
...base,
text: orbEvent.text ?? "Session closed",
type: "run.session_closed",
};
}
default: {
return undefined;
}
}
};

View File

@@ -1,125 +0,0 @@
/* eslint-disable no-non-null-assertion -- test assertions on defined objects */
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import { OrbConfigurationError } from "./domain";
import { makeOrbEvent } from "./events";
import type { OrbEvent } from "./events";
import { OrbHandle, OrbRuntime } from "./runtime";
const validGateway = {
apiKey: "test-key",
baseUrl: "https://gw.example.com/v1",
model: "m1",
provider: "p1",
};
const validContext = {
artifacts: [],
contextFiles: [],
issueBody: "Do the thing",
issueTitle: "Thing",
repositoryUrl: undefined,
};
const validIdentity = {
projectId: "prj-1",
runId: "run-1",
workUnitId: "wrk-1",
};
describe("OrbRuntime.createOrb validation", () => {
it("rejects missing gateway API key before touching Docker", () => {
const runtime = new OrbRuntime();
// This must fail at validation, not at Docker — if Docker is the failure,
// that indicates the validation ordering is wrong.
const error = Effect.runSync(
Effect.flip(
runtime.createOrb({
context: validContext,
docker: {
containerName: "orb-test",
hostWorkspacePath: "/tmp/orb-test",
},
gateway: { ...validGateway, apiKey: " " },
identity: validIdentity,
})
)
);
expect(error).toBeInstanceOf(OrbConfigurationError);
expect(error.reason).toBe("MissingGateway");
});
});
describe("OrbHandle event lifecycle", () => {
it("emits events to listeners", () => {
const handle = new OrbHandle(
"orb-x" as never,
"run-x" as never,
validIdentity
);
const events: OrbEvent[] = [];
handle.onEvent((e) => events.push(e));
handle.emitEvent(makeOrbEvent(1, "vm_booted", { text: "booted" }));
handle.emitEvent(
makeOrbEvent(2, "command_executed", { command: "ls", exitCode: 0 })
);
expect(events.length).toBe(2);
expect(events[0]!.type).toBe("vm_booted");
expect(events[1]!.type).toBe("command_executed");
expect(events[1]!.command).toBe("ls");
});
it("unsubscribes listeners correctly", () => {
const handle = new OrbHandle(
"orb-y" as never,
"run-y" as never,
validIdentity
);
const events: OrbEvent[] = [];
const unsub = handle.onEvent((e) => events.push(e));
handle.emitEvent(makeOrbEvent(1, "session_opened"));
unsub();
handle.emitEvent(makeOrbEvent(2, "session_closed"));
expect(events.length).toBe(1);
});
});
describe("OrbHandle state transitions", () => {
it("starts in creating state", () => {
const handle = new OrbHandle(
"orb-z" as never,
"run-z" as never,
validIdentity
);
expect(handle.state).toBe("creating");
});
it("transitions to prepared then running", () => {
const handle = new OrbHandle(
"orb-a" as never,
"run-a" as never,
validIdentity
);
Effect.runSync(handle.setOrbState("prepared"));
expect(handle.state).toBe("prepared");
Effect.runSync(handle.setOrbState("running"));
expect(handle.state).toBe("running");
});
it("rejects invalid transition", () => {
const handle = new OrbHandle(
"orb-b" as never,
"run-b" as never,
validIdentity
);
const error = Effect.runSync(
Effect.flip(handle.setOrbState("needs-input"))
);
expect(error.reason).toBe("InvalidTransition");
});
});

View File

@@ -1,763 +0,0 @@
/* eslint-disable prefer-destructuring -- field captures before mutation are intentional */
/* eslint-disable max-classes-per-file -- runtime and handle form one service. */
import opencodePkg from "@agentos-software/opencode";
import { AgentOs } from "@rivet-dev/agentos-core";
import type { SessionStreamEntry } from "@rivet-dev/agentos-core";
import { Effect } from "effect";
import type { DockerSandboxOptions } from "./docker-sandbox";
import { DockerSandboxProvider } from "./docker-sandbox";
import {
OrbConfigurationError,
OrbSandboxError,
OrbSessionError,
orbActorKey,
transitionOrbState,
transitionRunState,
} from "./domain";
import type {
OrbIdentity,
OrbId,
OrbModelGatewayConfig,
OrbProjectContext,
OrbRunId,
OrbSessionId,
OrbState,
OrbStateError,
RunState,
} from "./domain";
import type { OrbEvent } from "./events";
import { makeOrbEvent, normalizeSessionEvent, redactSecrets } from "./events";
import { prepareOpenCodeConfig } from "./opencode-config";
import { evaluatePermission } from "./permission-policy";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface OrbEnv {
readonly dockerImage?: string;
readonly dockerWorkspace?: string;
readonly rivetEndpoint?: string;
}
export interface OrbCreateInput {
readonly context: OrbProjectContext;
readonly docker: Omit<DockerSandboxOptions, "image">;
readonly gateway: OrbModelGatewayConfig;
readonly identity: OrbIdentity;
}
// ---------------------------------------------------------------------------
// OrbHandle
// ---------------------------------------------------------------------------
export class OrbHandle {
readonly id: OrbId;
readonly runId: OrbRunId;
readonly identity: OrbIdentity;
readonly actorKey: string;
private vm: AgentOs | null = null;
private dockerProvider: DockerSandboxProvider | null = null;
private sessionId: string | undefined;
private orbState: OrbState = "creating";
private runState: RunState = "queued";
private eventSequence = 0;
private readonly eventListeners = new Set<(event: OrbEvent) => void>();
private unsubscribeSession: (() => void) | null = null;
private context: OrbProjectContext | undefined;
private gateway: OrbModelGatewayConfig | undefined;
constructor(id: OrbId, runId: OrbRunId, identity: OrbIdentity) {
this.id = id;
this.runId = runId;
this.identity = identity;
this.actorKey = orbActorKey(identity);
}
get state(): OrbState {
return this.orbState;
}
get currentSessionId(): string | undefined {
return this.sessionId;
}
get docker(): DockerSandboxProvider | null {
return this.dockerProvider;
}
get vmInstance(): AgentOs | null {
return this.vm;
}
// -----------------------------------------------------------------------
// Event API
// -----------------------------------------------------------------------
onEvent(listener: (event: OrbEvent) => void): () => void {
this.eventListeners.add(listener);
return () => {
this.eventListeners.delete(listener);
};
}
emitEvent(event: OrbEvent): void {
for (const listener of this.eventListeners) {
listener(event);
}
}
private nextSequence(): number {
this.eventSequence += 1;
return this.eventSequence;
}
// -----------------------------------------------------------------------
// State transitions
// -----------------------------------------------------------------------
readonly setOrbState = (to: OrbState): Effect.Effect<void, OrbStateError> =>
transitionOrbState({ from: this.orbState, to }).pipe(
Effect.tap((next) =>
Effect.sync(() => {
this.orbState = next;
})
),
Effect.asVoid
);
readonly setRunState = (to: RunState): Effect.Effect<void, OrbStateError> =>
transitionRunState({ from: this.runState, to }).pipe(
Effect.tap((next) =>
Effect.sync(() => {
this.runState = next;
})
),
Effect.asVoid
);
// -----------------------------------------------------------------------
// Internal attachment
// -----------------------------------------------------------------------
_attachVm(vm: AgentOs): void {
this.vm = vm;
this.unsubscribeSession = vm.onSessionEvent((entry: SessionStreamEntry) => {
const normalized = normalizeSessionEvent(entry);
if (normalized) {
this.emitEvent({ ...normalized, sequence: this.nextSequence() });
}
if (
typeof entry === "object" &&
entry !== null &&
"type" in entry &&
entry.type === "permission_request"
) {
void this.handlePermissionRequest(
entry as unknown as {
requestId: string;
options: {
description?: string;
id: string;
title?: string;
}[];
toolCall?: { kind?: string; name?: string; title?: string };
}
);
}
});
this.emitEvent(
makeOrbEvent(this.nextSequence(), "vm_booted", { text: "VM booted" })
);
}
_attachDocker(provider: DockerSandboxProvider): void {
this.dockerProvider = provider;
}
_configure(input: {
readonly context: OrbProjectContext;
readonly gateway: OrbModelGatewayConfig;
}): void {
this.context = input.context;
this.gateway = input.gateway;
}
// -----------------------------------------------------------------------
// Permission handler
// -----------------------------------------------------------------------
private async handlePermissionRequest(request: {
readonly requestId: string;
readonly options: {
description?: string;
id: string;
title?: string;
}[];
readonly toolCall?: { kind?: string; name?: string; title?: string };
}): Promise<void> {
const vm = this.vm;
const sessionId = this.sessionId;
if (!vm || !sessionId) {
return;
}
const decision = evaluatePermission(request);
if (!decision.allow) {
this.emitEvent(
makeOrbEvent(this.nextSequence(), "permission_denied", {
text: `Permission denied for: ${request.toolCall?.title ?? "unknown"}`,
})
);
}
if (decision.optionId) {
await vm
.respondPermission({
optionId: decision.optionId,
requestId: request.requestId,
sessionId,
})
.catch(
// eslint-disable-next-line no-empty-function -- best-effort permission response
() => {}
);
}
}
// -----------------------------------------------------------------------
// Repository preparation
// -----------------------------------------------------------------------
readonly prepareRepository = Effect.fn("Orb.prepareRepository")(
function* prepareRepository(
this: OrbHandle,
input: { readonly baseBranch?: string; readonly branchName?: string }
) {
if (!this.dockerProvider) {
return yield* Effect.fail(
new OrbSandboxError({
message: "Docker sandbox is not attached",
reason: "ContainerStart",
})
);
}
yield* this.setOrbState("prepared");
yield* this.setRunState("provisioning");
const client = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Failed to start Docker sandbox: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "ContainerStart",
}),
try: () => {
const dp = this.dockerProvider;
if (!dp) {
throw new Error("Docker provider detached");
}
return dp.start();
},
});
const repoUrl = this.context?.repositoryUrl;
if (repoUrl) {
const branch = input.branchName ?? "main";
const base = input.baseBranch ?? "main";
// eslint-disable-next-line no-use-before-define -- module-level helper
const baseRef = `origin/${base}`;
// eslint-disable-next-line no-use-before-define -- module-level helper
const cloneCmd = `git clone --branch ${shellQuote(base)} --single-branch ${shellQuote(repoUrl)} /home/sandbox/repository || git clone ${shellQuote(repoUrl)} /home/sandbox/repository`;
// eslint-disable-next-line no-use-before-define -- module-level helper
const checkoutCmd = `cd /home/sandbox/repository && git checkout -b ${shellQuote(branch)} ${shellQuote(baseRef)} 2>/dev/null || git checkout ${shellQuote(branch)} 2>/dev/null || true`;
const result = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Repository checkout failed: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "CommandFailed",
}),
try: () =>
client.runProcess({
args: ["-c", `${cloneCmd} && ${checkoutCmd}`],
command: "sh",
cwd: "/home/sandbox",
timeoutMs: 300_000,
}),
});
if (result.exitCode !== 0) {
return yield* Effect.fail(
new OrbSandboxError({
message: `Repository clone failed: ${result.stderr}`,
reason: "CommandFailed",
})
);
}
} else {
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Failed to create workspace: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "CommandFailed",
}),
try: () =>
client.runProcess({
args: ["-c", "mkdir -p /home/sandbox/repository"],
command: "sh",
cwd: "/home/sandbox",
}),
});
}
const ctx = this.context;
const vm = this.vm;
if (ctx && vm) {
yield* Effect.tryPromise({
catch: () => null, // eslint-disable-next-line no-empty-function -- best-effort context staging
try: () =>
vm
.mkdir("/mnt/sandbox/control", { recursive: true })
.then(() =>
vm.writeFile(
"/mnt/sandbox/control/issue.md",
`# ${ctx.issueTitle}\n\n${ctx.issueBody}\n`
)
),
});
for (const file of ctx.contextFiles) {
yield* Effect.tryPromise({
catch: () => null,
try: () =>
vm.writeFile(`/mnt/sandbox/control/${file.path}`, file.content),
});
}
}
yield* this.setRunState("preparing");
}
);
// -----------------------------------------------------------------------
// OpenCode session
// -----------------------------------------------------------------------
readonly openSession = Effect.fn("Orb.openSession")(
function* openSession(this: OrbHandle) {
if (!this.vm) {
return yield* Effect.fail(
new OrbSessionError({
message: "AgentOS VM is not attached",
reason: "OpenSession",
})
);
}
if (!this.gateway || !this.context) {
return yield* Effect.fail(
new OrbConfigurationError({
message: "Orb is not configured with gateway and context",
reason: "MissingGateway",
})
);
}
const config = yield* prepareOpenCodeConfig({
context: this.context,
gateway: this.gateway,
});
const vm = this.vm;
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to create config directory: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "OpenSession",
}),
try: () => vm.mkdir("/root/.config/opencode", { recursive: true }),
});
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to write OpenCode config: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "OpenSession",
}),
try: () => vm.writeFile(config.configPath, config.configJson),
});
// Restrict the config file containing the run-scoped gateway key.
yield* Effect.tryPromise({
catch: () => null, // eslint-disable-next-line no-empty-function -- best-effort hardening
try: () => vm.exec(`chmod 600 ${config.configPath}`),
}).pipe(Effect.ignore);
const agents = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to list agents: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "AgentNotInstalled",
}),
try: () => vm.listAgents(),
});
const hasOpencode = agents.some(
(a) => a.id === "opencode" && a.installed
);
if (!hasOpencode) {
return yield* Effect.fail(
new OrbSessionError({
message: "OpenCode agent is not installed in the VM",
reason: "AgentNotInstalled",
})
);
}
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to open OpenCode session: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "OpenSession",
}),
try: () =>
vm.openSession({
agent: "opencode",
cwd: "/mnt/sandbox/repository",
permissionPolicy: "ask",
skipOsInstructions: false,
}),
});
const sessionInfo = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to read session info: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "OpenSession",
}),
try: () => vm.getSession(),
});
this.sessionId = sessionInfo.sessionId;
this.emitEvent(
makeOrbEvent(this.nextSequence(), "session_opened", {
text: `Session ${sessionInfo.sessionId} opened`,
})
);
yield* this.setOrbState("running");
yield* this.setRunState("running");
return sessionInfo.sessionId as OrbSessionId;
}
);
// -----------------------------------------------------------------------
// Send task — raw prompt to model, redacted copy in events only
// -----------------------------------------------------------------------
readonly sendTask = Effect.fn("Orb.sendTask")(function* sendTask(
this: OrbHandle,
prompt: string
) {
if (!this.vm || !this.sessionId) {
return yield* Effect.fail(
new OrbSessionError({
message: "No active OpenCode session",
reason: "SessionNotFound",
})
);
}
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const vm = this.vm;
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const sessionId = this.sessionId;
// Send raw prompt — no redaction of outgoing content.
const result = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Prompt failed: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "PromptFailed",
}),
try: () =>
vm.prompt({
content: [{ text: prompt, type: "text" }],
sessionId,
}),
});
return result;
});
// -----------------------------------------------------------------------
// Execute command via Docker
// -----------------------------------------------------------------------
readonly executeCommand = Effect.fn("Orb.executeCommand")(
function* executeCommand(
this: OrbHandle,
input: {
readonly command: string;
readonly cwd?: string;
readonly env?: Readonly<Record<string, string>>;
readonly timeoutMs?: number;
}
) {
if (!this.dockerProvider) {
return yield* Effect.fail(
new OrbSandboxError({
message: "Docker sandbox is not attached",
reason: "ContainerStart",
})
);
}
const client = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Failed to get sandbox client: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "ContainerStart",
}),
try: () => {
const dp = this.dockerProvider;
if (!dp) {
throw new Error("Docker provider detached");
}
return dp.start();
},
});
const result = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Command failed: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "CommandFailed",
}),
try: () =>
client.runProcess({
args: ["-c", input.command],
command: "sh",
...(input.cwd === undefined ? {} : { cwd: input.cwd }),
...(input.env === undefined ? {} : { env: input.env }),
...(input.timeoutMs === undefined
? {}
: { timeoutMs: input.timeoutMs }),
}),
});
// Emit redacted copy for logs/UI.
this.emitEvent(
makeOrbEvent(this.nextSequence(), "command_executed", {
command: redactSecrets(input.command),
exitCode: result.exitCode ?? undefined,
})
);
return result;
}
);
// -----------------------------------------------------------------------
// Cancel / dispose
// -----------------------------------------------------------------------
readonly cancel = Effect.fn("Orb.cancel")(function* cancel(this: OrbHandle) {
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const vm = this.vm;
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const sessionId = this.sessionId;
if (vm && sessionId) {
yield* Effect.tryPromise({
catch: () => null,
try: () => vm.cancelPrompt({ sessionId }),
}).pipe(Effect.ignore);
}
yield* this.setOrbState("cancelled");
yield* this.setRunState("cancelled");
this.emitEvent(
makeOrbEvent(this.nextSequence(), "session_closed", {
text: "Orb cancelled",
})
);
});
readonly dispose = Effect.fn("Orb.dispose")(
function* dispose(this: OrbHandle) {
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const vm = this.vm;
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const sessionId = this.sessionId;
// eslint-disable-next-line prefer-destructuring -- captured before mutation
const docker = this.dockerProvider;
if (vm && sessionId) {
yield* Effect.tryPromise({
catch: () => null,
try: () => vm.cancelPrompt({ sessionId }),
}).pipe(Effect.ignore);
}
// Dispose the VM before its sandbox so the mount unbinds cleanly.
if (vm) {
if (this.unsubscribeSession) {
this.unsubscribeSession();
this.unsubscribeSession = null;
}
yield* Effect.tryPromise({
catch: () => null,
try: () => vm.dispose(),
}).pipe(Effect.ignore);
}
if (docker) {
yield* Effect.tryPromise({
catch: () => null,
try: () => docker.dispose(),
}).pipe(Effect.ignore);
}
yield* this.setOrbState("disposed");
this.eventListeners.clear();
this.vm = null;
this.dockerProvider = null;
this.sessionId = undefined;
}
);
}
// ---------------------------------------------------------------------------
// OrbRuntime
// ---------------------------------------------------------------------------
export class OrbRuntime {
private readonly orbs = new Map<string, OrbHandle>();
private readonly env: OrbEnv;
constructor(env: OrbEnv = {}) {
this.env = env;
}
readonly createOrb = Effect.fn("OrbRuntime.createOrb")(function* createOrb(
this: OrbRuntime,
input: OrbCreateInput
) {
if (!input.gateway.apiKey.trim()) {
return yield* Effect.fail(
new OrbConfigurationError({
message: "Model gateway API key is required",
reason: "MissingGateway",
})
);
}
const orbId =
`orb-${input.identity.projectId}-${input.identity.runId}` as OrbId;
const runId = `run-${input.identity.runId}` as OrbRunId;
const handle = new OrbHandle(orbId, runId, input.identity);
handle._configure({
context: input.context,
gateway: input.gateway,
});
// 1. Create and start Docker sandbox (the provider owns its container).
const dockerOptions: DockerSandboxOptions = {
...input.docker,
...(this.env.dockerImage === undefined
? {}
: { image: this.env.dockerImage }),
};
const provider = yield* DockerSandboxProvider.create(dockerOptions);
handle._attachDocker(provider);
// 2-3. Start the sandbox, create the AgentOS VM, and link OpenCode. Any
// failure here disposes the VM before its sandbox so neither leaks.
let createdVm: AgentOs | null = null;
const vm = yield* Effect.gen(function* vm() {
const sandboxClient = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSandboxError({
message: `Failed to start Docker sandbox: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "ContainerStart",
}),
try: () => provider.start(),
});
const created = yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to create AgentOS VM: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "OpenSession",
}),
try: () =>
AgentOs.create({
database: {
path: `/tmp/${orbId}.db`,
type: "sqlite_file",
},
sandbox: {
client: sandboxClient,
dispose: false,
mountPath: "/mnt/sandbox",
readOnly: false,
sandboxRoot: "/home/sandbox",
},
software: [opencodePkg],
}),
});
createdVm = created;
yield* Effect.tryPromise({
catch: (cause) =>
new OrbSessionError({
message: `Failed to link OpenCode: ${cause instanceof Error ? cause.message : String(cause)}`,
reason: "AgentNotInstalled",
}),
try: () => created.linkSoftware({ path: opencodePkg.packagePath }),
});
return created;
}).pipe(
Effect.tapError(() =>
Effect.tryPromise({
catch: () => null,
// eslint-disable-next-line no-use-before-define -- module-level cleanup helper
try: () => disposeVmBeforeSandbox(createdVm, provider),
}).pipe(Effect.ignore)
)
);
// 4. Attach VM to handle.
handle._attachVm(vm);
this.orbs.set(orbId, handle);
return handle;
});
getOrb(id: string): OrbHandle | undefined {
return this.orbs.get(id);
}
listOrbs(): readonly OrbHandle[] {
return [...this.orbs.values()];
}
}
// ---------------------------------------------------------------------------
// Partial-failure cleanup — dispose the VM before its sandbox
// ---------------------------------------------------------------------------
const disposeVmBeforeSandbox = async (
vm: AgentOs | null,
docker: DockerSandboxProvider
): Promise<void> => {
if (vm) {
try {
await vm.dispose();
} catch {
// best-effort; container removal below is the hard guarantee
}
}
await docker.dispose();
};
// ---------------------------------------------------------------------------
// Shell quoting
// ---------------------------------------------------------------------------
// eslint-disable-next-line no-use-before-define -- module-level helper
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'"'"'`)}'`;

View File

@@ -1,162 +0,0 @@
import {
decodeProjectIssueRequest,
ProjectIssueDispatchInput,
ProjectIssueRequestError,
ProjectIssueRequestResult,
ProjectIssueValidationError,
} from "@code/primitives/project-issue";
import type { ProjectIssueRequest } from "@code/primitives/project-issue";
import { dispatch } from "@flue/runtime";
import type { ConvexHttpClient } from "convex/browser";
import { makeFunctionReference } from "convex/server";
import { Effect, Schema } from "effect";
import type { Context } from "hono";
import { createAuthenticatedClient, extractBearerToken } from "./auth";
interface ProjectIssueCreateArgs extends Record<string, unknown> {
readonly body: string;
readonly projectId: string;
readonly title: string;
}
const createIssue = makeFunctionReference<
"mutation",
ProjectIssueCreateArgs,
string
>("projectIssues:create");
const createIssueFromSignal = makeFunctionReference<
"mutation",
{ readonly signalId: string },
{ readonly issueId: string; readonly projectId: string }
>("projectIssues:createFromSignal");
const beginIssue = makeFunctionReference<
"mutation",
{ readonly issueId: string },
"queued" | "working"
>("projectIssues:begin");
const markDispatchFailed = makeFunctionReference<
"mutation",
{ readonly error: string; readonly issueId: string },
null
>("projectIssues:markDispatchFailed");
const invalidRequest = (message: string) =>
Response.json({ error: message }, { status: 400 });
const knownAuthorizationFailure = (message: string): boolean =>
/authentication required|membership required|project not found|signal not found|not project-scoped/iu.test(
message
);
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
const decodeRequest = async (input: unknown): Promise<ProjectIssueRequest> => {
try {
return await Effect.runPromise(decodeProjectIssueRequest(input));
} catch (error) {
if (
error instanceof ProjectIssueRequestError ||
error instanceof ProjectIssueValidationError
) {
throw invalidRequest(
error instanceof Error ? error.message : "Invalid project request"
);
}
throw error;
}
};
const createIssueForRequest = async (
client: ConvexHttpClient,
request: Awaited<ReturnType<typeof decodeRequest>>
): Promise<{ readonly issueId: string; readonly projectId: string }> => {
if (request.kind === "signal") {
return client.mutation(createIssueFromSignal, {
signalId: request.signalId,
});
}
const issueId = await client.mutation(createIssue, {
body: request.body,
projectId: request.projectId,
title: request.title,
});
return { issueId, projectId: request.projectId };
};
export const projectRequestRoute = async (c: Context): Promise<Response> => {
const accessToken = extractBearerToken(c.req.raw);
if (!accessToken) {
return c.json({ error: "Unauthorized" }, 401);
}
let input: unknown;
try {
input = await c.req.json();
} catch {
return invalidRequest("Request body must be valid JSON");
}
let request: Awaited<ReturnType<typeof decodeRequest>>;
try {
request = await decodeRequest(input);
} catch (error) {
if (error instanceof Response) {
return error;
}
return c.json({ error: "Invalid project request" }, 400);
}
const client = createAuthenticatedClient(accessToken);
let issue:
| { readonly issueId: string; readonly projectId: string }
| undefined;
try {
issue = await createIssueForRequest(client, request);
const status = await client.mutation(beginIssue, {
issueId: issue.issueId,
});
const dispatchInput = Schema.decodeUnknownSync(ProjectIssueDispatchInput)({
issueId: issue.issueId,
kind: "project.issue.started",
projectId: issue.projectId,
});
const receipt = await dispatch({
agent: "project-manager",
id: issue.issueId,
input: dispatchInput,
});
const result = Schema.decodeUnknownSync(ProjectIssueRequestResult)({
acceptedAt: receipt.acceptedAt,
dispatchId: receipt.dispatchId,
issueId: issue.issueId,
projectId: issue.projectId,
status,
});
return c.json(result, 202);
} catch (error) {
const message = errorMessage(error);
if (issue) {
try {
await client.mutation(markDispatchFailed, {
error: message,
issueId: issue.issueId,
});
} catch {
// Preserve the original request failure; the issue remains inspectable.
}
}
return c.json(
{
error: knownAuthorizationFailure(message)
? "Project request is not authorized"
: "Project request could not be dispatched",
},
knownAuthorizationFailure(message) ? 403 : 502
);
}
};

View File

@@ -1,312 +0,0 @@
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { parseAgentEnv } from "@code/env/agent";
import {
decodeIssueWorkspaceResult,
makeIssueWorkspacePlan,
} from "@code/primitives/project-workspace";
import { createSandboxSessionEnv } from "@flue/runtime";
import type { FileStat, SandboxApi, SandboxFactory } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import { Effect } from "effect";
import * as v from "valibot";
import {
clonePublicRepository,
mirrorHostCheckoutToSandbox,
} from "./host-repository-bridge";
const execResultSchema = v.object({
exitCode: v.number(),
stderr: v.string(),
stdout: v.string(),
});
const statResultSchema = v.object({
isDirectory: v.boolean(),
isSymbolicLink: v.boolean(),
mtimeMs: v.number(),
size: v.number(),
});
interface ExecuteOptions {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
}
export class AgentOsSandboxApi implements SandboxApi {
readonly #actorKey: string[];
readonly #client: ConvexHttpClient;
readonly #daemonId: string;
constructor(
client: ConvexHttpClient,
daemonId: string,
actorKey: readonly string[]
) {
this.#client = client;
this.#daemonId = daemonId;
this.#actorKey = [...actorKey];
}
async #execute(
method: string,
args: unknown[],
options: ExecuteOptions = {}
): Promise<unknown> {
const commandId = await this.#client.mutation(api.daemonCommands.enqueue, {
actorKey: this.#actorKey,
args,
daemonId: this.#daemonId,
method,
});
const timeoutMs = options.timeoutMs ?? 120_000;
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (options.signal?.aborted) {
// oxlint-disable-next-line no-await-in-loop -- cancellation must settle before the poll exits.
await this.#client.mutation(api.daemonCommands.cancel, { commandId });
throw options.signal.reason ?? new Error("AgentOS command aborted");
}
// oxlint-disable-next-line no-await-in-loop -- each query observes the next durable command state.
const command = await this.#client.query(api.daemonCommands.get, {
commandId,
});
if (!command) {
throw new Error(`AgentOS command ${commandId} disappeared`);
}
if (command.status === "succeeded") {
return command.result;
}
if (command.status === "failed" || command.status === "cancelled") {
throw new Error(
command.error ?? `AgentOS command ${method} ${command.status}`
);
}
const { promise, resolve } = Promise.withResolvers<null>();
setTimeout(() => resolve(null), 200);
// oxlint-disable-next-line no-await-in-loop -- polling intentionally waits between sequential reads.
await promise;
}
await this.#client.mutation(api.daemonCommands.cancel, { commandId });
throw new Error(`AgentOS command ${method} timed out after ${timeoutMs}ms`);
}
async readFile(path: string): Promise<string> {
return new TextDecoder().decode(await this.readFileBuffer(path));
}
async readFileBuffer(path: string): Promise<Uint8Array> {
const result = await this.#execute("readFile", [path]);
if (result instanceof ArrayBuffer) {
return new Uint8Array(result);
}
if (ArrayBuffer.isView(result)) {
return new Uint8Array(
result.buffer.slice(
result.byteOffset,
result.byteOffset + result.byteLength
)
);
}
throw new TypeError(
`AgentOS readFile returned non-binary data for ${path}`
);
}
async writeFile(path: string, content: string | Uint8Array): Promise<void> {
const serialized =
typeof content === "string" ? content : Uint8Array.from(content).buffer;
await this.#execute("writeFile", [path, serialized]);
}
async stat(path: string): Promise<FileStat> {
const result = v.parse(
statResultSchema,
await this.#execute("stat", [path])
);
return {
isDirectory: result.isDirectory,
isFile: !result.isDirectory && !result.isSymbolicLink,
isSymbolicLink: result.isSymbolicLink,
mtime: new Date(result.mtimeMs),
size: result.size,
};
}
async readdir(path: string): Promise<string[]> {
return v.parse(v.array(v.string()), await this.#execute("readdir", [path]));
}
async exists(path: string): Promise<boolean> {
return v.parse(v.boolean(), await this.#execute("exists", [path]));
}
async mkdir(
path: string,
options?: { readonly recursive?: boolean }
): Promise<void> {
if (!options?.recursive) {
await this.#execute("mkdir", [path]);
return;
}
const quotedPath = `'${path.replaceAll("'", `'"'"'`)}'`;
const result = v.parse(
execResultSchema,
await this.#execute("exec", [`mkdir -p ${quotedPath}`])
);
if (result.exitCode !== 0) {
throw new Error(result.stderr || `Could not create ${path}`);
}
}
async rm(
path: string,
options?: { readonly force?: boolean; readonly recursive?: boolean }
): Promise<void> {
if (options?.force && !(await this.exists(path))) {
return;
}
await this.#execute("deleteFile", [
path,
{ recursive: options?.recursive },
]);
}
async exec(
command: string,
options?: {
readonly cwd?: string;
readonly env?: Record<string, string>;
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
}
): Promise<{ exitCode: number; stderr: string; stdout: string }> {
return v.parse(
execResultSchema,
await this.#execute(
"exec",
[
command,
{
...(options?.cwd === undefined ? {} : { cwd: options.cwd }),
...(options?.env === undefined ? {} : { env: options.env }),
},
],
{ signal: options?.signal, timeoutMs: options?.timeoutMs }
)
);
}
}
export const agentOs = (
runtimeEnv: Record<string, string | undefined>
): SandboxFactory => {
const env = parseAgentEnv(runtimeEnv);
const client = new ConvexHttpClient(env.CONVEX_URL);
return {
async createSessionEnv({ id }) {
// Flue controls this id from the issue document selected by the web app.
const issueId = id as Id<"projectIssues">;
const run = await client.mutation(api.agentWorkspace.ensureRun, {
daemonId: env.DAEMON_ID,
issueId,
token: env.FLUE_DB_TOKEN,
});
if (!run) {
throw new Error(`Could not initialize AgentOS work run for ${id}`);
}
const sandbox = new AgentOsSandboxApi(
client,
env.DAEMON_ID,
run.actorKey
);
const context = await client.query(api.agentWorkspace.get, {
issueId,
token: env.FLUE_DB_TOKEN,
});
const plan = await Effect.runPromise(
makeIssueWorkspacePlan({
artifacts: context.artifacts.map((artifact) => ({
content: artifact.content,
path: artifact.path,
})),
branchName: context.run?.branchName,
checkoutPath: context.run?.checkoutPath,
contextFiles: context.contextDocuments.map((document) => ({
content: document.content,
kind: document.kind,
path: document.path,
})),
defaultBranch:
context.run?.baseBranch ?? context.source?.defaultBranch,
issueBody: context.issue.body,
issueId: String(context.issue._id),
issueNumber: context.issue.number,
issueTitle: context.issue.title,
sourceUrl: context.run?.sourceUrl ?? context.source?.url,
})
);
const [controlDirectory, checkoutOperation, ...stagingOperations] =
plan.operations;
if (!controlDirectory || controlDirectory._tag !== "Mkdir") {
throw new Error(
"Issue workspace plan must start with a control directory"
);
}
await sandbox.mkdir(controlDirectory.path, { recursive: true });
if (!checkoutOperation || checkoutOperation._tag !== "Exec") {
throw new Error("Issue workspace plan must include a checkout command");
}
const hostCheckout = await clonePublicRepository({
branchName: plan.branchName,
repositoryUrl: plan.sourceUrl,
timeoutMs: checkoutOperation.timeoutMs,
});
try {
if (!(await sandbox.exists(plan.checkoutPath))) {
await mirrorHostCheckoutToSandbox({
checkoutDirectory: hostCheckout.checkoutDirectory,
sandbox,
sandboxDirectory: plan.checkoutPath,
});
}
} finally {
await hostCheckout.cleanup();
}
const checkoutCommandResult = {
exitCode: 0,
stderr: "",
stdout: `${plan.branchName} ${hostCheckout.headSha}\n`,
};
await Promise.all(
stagingOperations
.filter((operation) => operation._tag === "Mkdir")
.map((operation) =>
sandbox.mkdir(operation.path, { recursive: true })
)
);
await Promise.all(
stagingOperations
.filter((operation) => operation._tag === "WriteFile")
.map((operation) =>
sandbox.writeFile(operation.path, operation.content)
)
);
await Effect.runPromise(
decodeIssueWorkspaceResult({
command: checkoutCommandResult,
plan,
})
);
return createSandboxSessionEnv(sandbox, "/workspace");
},
};
};

View File

@@ -1,121 +0,0 @@
import {
createSandboxSessionEnv,
SandboxOperationUnsupportedError,
} from "@flue/runtime";
import type {
FileStat,
SandboxApi,
SandboxFactory,
SessionEnv,
} from "@flue/runtime";
import { AgentOs } from "@rivet-dev/agentos-core";
import type { VirtualStat } from "@rivet-dev/agentos-core";
class AgentOsSandboxApi implements SandboxApi {
private readonly vm: AgentOs;
constructor(vm: AgentOs) {
this.vm = vm;
}
async readFile(path: string): Promise<string> {
const bytes = await this.vm.readFile(path);
return new TextDecoder().decode(bytes);
}
readFileBuffer(path: string): Promise<Uint8Array> {
return this.vm.readFile(path);
}
async writeFile(path: string, content: string | Uint8Array): Promise<void> {
await this.vm.writeFile(path, content);
}
async stat(path: string): Promise<FileStat> {
const s: VirtualStat = await this.vm.stat(path);
return {
isDirectory: s.isDirectory,
isFile: !s.isDirectory && !s.isSymbolicLink,
isSymbolicLink: s.isSymbolicLink,
mtime: new Date(s.mtimeMs),
size: s.size,
};
}
readdir(path: string): Promise<string[]> {
return this.vm.readdir(path);
}
async exists(path: string): Promise<boolean> {
try {
return await this.vm.exists(path);
} catch {
return false;
}
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
await this.vm.mkdir(path, options);
}
async rm(
path: string,
options?: { recursive?: boolean; force?: boolean }
): Promise<void> {
// agentOS remove has no `force` flag. Reject it per the adapter contract:
// never ignore an option or leave its behavior provider-defined.
if (options?.force) {
throw new SandboxOperationUnsupportedError({
operation: "rm",
options: ["force"],
provider: "agentos",
});
}
await this.vm.remove(path, { recursive: options?.recursive });
}
async exec(
command: string,
options?: {
cwd?: string;
env?: Record<string, string>;
timeoutMs?: number;
signal?: AbortSignal;
}
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
// agentOS exec takes timeout in ms, same unit as Flue's timeoutMs.
// Forward directly — no rounding needed.
const result = await this.vm.exec(command, {
cwd: options?.cwd,
env: options?.env,
timeout: options?.timeoutMs,
});
return {
exitCode: result.exitCode,
stderr: result.stderr,
stdout: result.stdout,
};
}
}
/**
* Adapts an agentOS VM into Flue's sandbox contract.
*
* The VM boots lazily on the first operation and sleeps when idle. Files
* persist for the VM's lifetime. Shell commands run in an isolated Wasm+V8
* Linux environment with sh and coreutils.
*/
export const agentos = (): SandboxFactory => {
let vm: AgentOs | null = null;
return {
async createSessionEnv(): Promise<SessionEnv> {
// Boot once per harness. Repeated calls reuse the same VM.
if (!vm) {
vm = await AgentOs.create();
}
const api = new AgentOsSandboxApi(vm);
return createSandboxSessionEnv(api, "/workspace");
},
};
};

View File

@@ -1,297 +0,0 @@
import {
lstat,
mkdir,
mkdtemp,
readFile,
rm,
stat,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import nodePath from "node:path";
import type { FileStat, SandboxApi } from "@flue/runtime";
import { afterEach, describe, expect, it } from "vitest";
import {
mirrorHostCheckoutToSandbox,
mirrorSandboxToHostCheckout,
parseGitCommitSha,
parsePublicGitUrl,
} from "./host-repository-bridge";
class FakeSandbox implements SandboxApi {
readonly files = new Map<string, Uint8Array>();
readonly directories = new Set<string>(["/"]);
async readFile(path: string): Promise<string> {
return new TextDecoder().decode(await this.readFileBuffer(path));
}
readFileBuffer(path: string): Promise<Uint8Array> {
const content = this.files.get(path);
if (!content) {
throw new Error(`Missing fake sandbox file: ${path}`);
}
return Promise.resolve(Uint8Array.from(content));
}
writeFile(path: string, content: string | Uint8Array): Promise<void> {
this.files.set(
path,
typeof content === "string"
? new TextEncoder().encode(content)
: Uint8Array.from(content)
);
return Promise.resolve();
}
stat(path: string): Promise<FileStat> {
const content = this.files.get(path);
if (content) {
return Promise.resolve({
isDirectory: false,
isFile: true,
size: content.byteLength,
});
}
if (this.directories.has(path)) {
return Promise.resolve({ isDirectory: true, isFile: false });
}
throw new Error(`Missing fake sandbox path: ${path}`);
}
readdir(path: string): Promise<string[]> {
const prefix = path === "/" ? "/" : `${path}/`;
const entries = new Set<string>();
for (const directory of this.directories) {
if (directory.startsWith(prefix)) {
const [entry] = directory.slice(prefix.length).split("/");
if (entry) {
entries.add(entry);
}
}
}
for (const file of this.files.keys()) {
if (file.startsWith(prefix)) {
const [entry] = file.slice(prefix.length).split("/");
if (entry) {
entries.add(entry);
}
}
}
return Promise.resolve([...entries]);
}
exists(path: string): Promise<boolean> {
return Promise.resolve(this.files.has(path) || this.directories.has(path));
}
mkdir(
path: string,
options?: { readonly recursive?: boolean }
): Promise<void> {
if (!options?.recursive) {
this.directories.add(path);
return Promise.resolve();
}
const parts = path.split("/").filter(Boolean);
let current = "";
for (const part of parts) {
current += `/${part}`;
this.directories.add(current);
}
return Promise.resolve();
}
rm(
path: string,
options?: { readonly force?: boolean; readonly recursive?: boolean }
): Promise<void> {
const prefix = `${path}/`;
if (options?.recursive) {
for (const file of this.files.keys()) {
if (file === path || file.startsWith(prefix)) {
this.files.delete(file);
}
}
for (const directory of this.directories) {
if (directory === path || directory.startsWith(prefix)) {
this.directories.delete(directory);
}
}
return Promise.resolve();
}
this.files.delete(path);
this.directories.delete(path);
return Promise.resolve();
}
exec(): Promise<{
exitCode: number;
stderr: string;
stdout: string;
}> {
void this.directories;
return Promise.resolve({ exitCode: 0, stderr: "", stdout: "" });
}
}
const temporaryDirectories: string[] = [];
const makeCheckout = async (): Promise<string> => {
const directory = await mkdtemp(nodePath.join(tmpdir(), "host-bridge-test-"));
temporaryDirectories.push(directory);
await mkdir(nodePath.join(directory, ".git"), { recursive: true });
await writeFile(nodePath.join(directory, ".git", "keep"), "git metadata");
return directory;
};
afterEach(async () => {
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { force: true, recursive: true }))
);
});
describe("parsePublicGitUrl", () => {
it("accepts public HTTP(S) repositories", () => {
expect(
parsePublicGitUrl("https://git.openputer.com/team/repository.git")
.hostname
).toBe("git.openputer.com");
});
it.each([
"file:///tmp/repository",
"ssh://git@example.com/team/repository.git",
"https://token@example.com/team/repository.git",
"http://127.0.0.1/repository.git",
"http://192.168.1.10/repository.git",
])("rejects non-public repository URL %s", (repositoryUrl) => {
expect(() => parsePublicGitUrl(repositoryUrl)).toThrow();
});
});
describe("parseGitCommitSha", () => {
it("normalizes a full SHA returned by git", () => {
const sha = "a".repeat(40);
expect(parseGitCommitSha(` ${sha}\n`)).toBe(sha);
});
it.each(["", "abc123", "g".repeat(40), "a".repeat(41)])(
"rejects invalid commit SHA %s",
(sha) => {
expect(() => parseGitCommitSha(sha)).toThrow("invalid HEAD commit SHA");
}
);
});
describe("repository mirroring", () => {
it("copies host files into a sandbox without copying .git", async () => {
const checkoutDirectory = await makeCheckout();
await mkdir(nodePath.join(checkoutDirectory, "src"), {
recursive: true,
});
await writeFile(nodePath.join(checkoutDirectory, "README.md"), "hello");
await writeFile(
nodePath.join(checkoutDirectory, "src", "binary.bin"),
Uint8Array.from([0, 255, 1])
);
const sandbox = new FakeSandbox();
await mirrorHostCheckoutToSandbox({
checkoutDirectory,
sandbox,
sandboxDirectory: "/workspace/repository",
});
expect(
new TextDecoder().decode(
sandbox.files.get("/workspace/repository/README.md")
)
).toBe("hello");
expect(sandbox.files.get("/workspace/repository/src/binary.bin")).toEqual(
Uint8Array.from([0, 255, 1])
);
expect(
[...sandbox.files.keys()].some((filePath) => filePath.includes("/.git/"))
).toBe(false);
});
it("stages sandbox files, removes stale files, and preserves .git", async () => {
const checkoutDirectory = await makeCheckout();
await writeFile(nodePath.join(checkoutDirectory, "stale.txt"), "delete me");
const executablePath = nodePath.join(checkoutDirectory, "run.sh");
await writeFile(executablePath, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const sandbox = new FakeSandbox();
await sandbox.mkdir("/workspace/repository/src", { recursive: true });
await sandbox.writeFile(
"/workspace/repository/run.sh",
"#!/bin/sh\necho changed\n"
);
await sandbox.writeFile(
"/workspace/repository/src/index.ts",
"export const value = 1;\n"
);
await mirrorSandboxToHostCheckout({
checkoutDirectory,
sandbox,
sandboxDirectory: "/workspace/repository",
});
await expect(
readFile(nodePath.join(checkoutDirectory, "stale.txt"))
).rejects.toThrow();
await expect(
readFile(nodePath.join(checkoutDirectory, ".git", "keep"), "utf-8")
).resolves.toBe("git metadata");
await expect(
readFile(nodePath.join(checkoutDirectory, "src", "index.ts"), "utf-8")
).resolves.toBe("export const value = 1;\n");
const executableMetadata = await stat(executablePath);
expect(executableMetadata.mode % 0o1000).toBe(0o755);
});
it("enforces transfer limits before modifying the sandbox", async () => {
const checkoutDirectory = await makeCheckout();
await writeFile(nodePath.join(checkoutDirectory, "one.txt"), "1");
await writeFile(nodePath.join(checkoutDirectory, "two.txt"), "2");
const sandbox = new FakeSandbox();
await expect(
mirrorHostCheckoutToSandbox({
checkoutDirectory,
limits: { maxFiles: 1 },
sandbox,
sandboxDirectory: "/workspace/repository",
})
).rejects.toThrow("limit is 1");
expect(sandbox.files.size).toBe(0);
});
it("rejects host symbolic links", async () => {
const checkoutDirectory = await makeCheckout();
await writeFile(nodePath.join(checkoutDirectory, "outside.txt"), "outside");
await symlink(
"outside.txt",
nodePath.join(checkoutDirectory, "linked.txt")
);
const sandbox = new FakeSandbox();
await expect(
mirrorHostCheckoutToSandbox({
checkoutDirectory,
sandbox,
sandboxDirectory: "/workspace/repository",
})
).rejects.toThrow("Symbolic links are not supported");
const linkedMetadata = await lstat(
nodePath.join(checkoutDirectory, "linked.txt")
);
expect(linkedMetadata.isSymbolicLink()).toBe(true);
});
});

View File

@@ -1,506 +0,0 @@
import { execFile } from "node:child_process";
import {
chmod,
lstat,
mkdir,
mkdtemp,
readdir,
readFile,
rename,
rm,
writeFile,
} from "node:fs/promises";
import { isIP } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import type { SandboxApi } from "@flue/runtime";
const DEFAULT_GIT_TIMEOUT_MS = 60_000;
const GIT_OUTPUT_LIMIT_BYTES = 1_048_576;
export interface RepositoryMirrorLimits {
readonly maxDepth: number;
readonly maxFileBytes: number;
readonly maxFiles: number;
readonly maxTotalBytes: number;
}
export const DEFAULT_REPOSITORY_MIRROR_LIMITS: RepositoryMirrorLimits = {
maxDepth: 64,
maxFileBytes: 10 * 1024 * 1024,
maxFiles: 10_000,
maxTotalBytes: 100 * 1024 * 1024,
};
export interface HostRepositoryCheckout {
readonly branchName: string;
readonly checkoutDirectory: string;
readonly headSha: string;
readonly temporaryDirectory: string;
readonly cleanup: () => Promise<void>;
}
interface MirrorFile {
readonly mode?: number;
readonly path: string;
readonly size: number;
}
interface GitResult {
readonly stderr: string;
readonly stdout: string;
}
const gitError = (
args: readonly string[],
error: Error & { readonly stderr?: string }
): Error => {
const detail = error.stderr?.trim() || error.message;
return new Error(`git ${args.join(" ")} failed: ${detail}`, {
cause: error,
});
};
const execFileAsync = promisify(execFile);
const runGit = async (
args: readonly string[],
options: { readonly cwd?: string; readonly timeoutMs: number }
): Promise<GitResult> => {
try {
const result = await execFileAsync("git", [...args], {
cwd: options.cwd,
maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
timeout: options.timeoutMs,
});
return {
stderr: String(result.stderr),
stdout: String(result.stdout),
};
} catch (error) {
if (!(error instanceof Error)) {
throw error;
}
throw gitError(
args,
error as Error & {
readonly stderr?: string;
}
);
}
};
const isPrivateIpv4 = (hostname: string): boolean => {
const octets = hostname.split(".").map(Number);
const [first = -1, second = -1] = octets;
return (
first === 0 ||
first === 10 ||
first === 127 ||
(first === 169 && second === 254) ||
(first === 172 && second >= 16 && second <= 31) ||
(first === 192 && second === 168)
);
};
const isPrivateIpv6 = (hostname: string): boolean => {
const normalized = hostname
.toLowerCase()
.replaceAll("[", "")
.replaceAll("]", "");
return (
normalized === "::" ||
normalized === "::1" ||
normalized.startsWith("fc") ||
normalized.startsWith("fd") ||
normalized.startsWith("fe8") ||
normalized.startsWith("fe9") ||
normalized.startsWith("fea") ||
normalized.startsWith("feb")
);
};
export const parsePublicGitUrl = (repositoryUrl: string): URL => {
const url = new URL(repositoryUrl);
if (url.protocol !== "https:" && url.protocol !== "http:") {
throw new Error("Public Git repositories must use an HTTP(S) URL");
}
if (url.username || url.password) {
throw new Error("Public Git repository URLs must not contain credentials");
}
const hostname = url.hostname.toLowerCase();
const addressKind = isIP(hostname);
const isPrivateAddress =
(addressKind === 4 && isPrivateIpv4(hostname)) ||
(addressKind === 6 && isPrivateIpv6(hostname));
if (
hostname === "localhost" ||
hostname.endsWith(".localhost") ||
hostname.endsWith(".local") ||
isPrivateAddress
) {
throw new Error("Public Git repository URLs must use a public host");
}
return url;
};
export const parseGitCommitSha = (value: string): string => {
const sha = value.trim();
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(sha)) {
throw new Error("Git returned an invalid HEAD commit SHA");
}
return sha;
};
export const clonePublicRepository = async (options: {
readonly branchName: string;
readonly repositoryUrl: string;
readonly timeoutMs?: number;
}): Promise<HostRepositoryCheckout> => {
const timeoutMs = options.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS;
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
throw new Error("Git timeout must be a positive integer");
}
const repositoryUrl = parsePublicGitUrl(options.repositoryUrl).toString();
await runGit(["check-ref-format", "--branch", options.branchName], {
timeoutMs,
});
const temporaryDirectory = await mkdtemp(
path.join(tmpdir(), "zopu-host-repository-")
);
const checkoutDirectory = path.join(temporaryDirectory, "repository");
let headSha = "";
try {
await runGit(
[
"clone",
"--depth",
"1",
"--single-branch",
"--no-tags",
"--",
repositoryUrl,
checkoutDirectory,
],
{ timeoutMs }
);
await runGit(["switch", "-c", options.branchName], {
cwd: checkoutDirectory,
timeoutMs,
});
const headResult = await runGit(["rev-parse", "HEAD"], {
cwd: checkoutDirectory,
timeoutMs,
});
headSha = parseGitCommitSha(headResult.stdout);
} catch (error) {
await rm(temporaryDirectory, { force: true, recursive: true });
throw error;
}
return {
branchName: options.branchName,
checkoutDirectory,
cleanup: () =>
rm(temporaryDirectory, {
force: true,
recursive: true,
}),
headSha,
temporaryDirectory,
};
};
const resolveLimits = (
limits: Partial<RepositoryMirrorLimits> | undefined
): RepositoryMirrorLimits => {
const resolvedLimits = {
...DEFAULT_REPOSITORY_MIRROR_LIMITS,
...limits,
};
for (const [name, value] of Object.entries(resolvedLimits)) {
if (!Number.isSafeInteger(value) || value <= 0) {
throw new Error(`${name} must be a positive integer`);
}
}
return resolvedLimits;
};
const assertSafeEntryName = (name: string): void => {
if (
!name ||
name === "." ||
name === ".." ||
name.includes("/") ||
name.includes("\\")
) {
throw new Error(`Sandbox returned an unsafe directory entry: ${name}`);
}
};
const assertWithinCheckout = (checkoutDirectory: string): string => {
const absoluteCheckout = path.resolve(checkoutDirectory);
if (absoluteCheckout === path.resolve(path.sep)) {
throw new Error("Repository checkout cannot be the filesystem root");
}
return absoluteCheckout;
};
const assertAbsoluteSandboxDirectory = (sandboxDirectory: string): string => {
if (!path.posix.isAbsolute(sandboxDirectory)) {
throw new Error("Sandbox directory must be absolute");
}
return path.posix.normalize(sandboxDirectory);
};
const enforceFileBounds = (
files: readonly MirrorFile[],
limits: RepositoryMirrorLimits
): void => {
if (files.length > limits.maxFiles) {
throw new Error(
`Repository contains ${files.length} files; limit is ${limits.maxFiles}`
);
}
let totalBytes = 0;
for (const file of files) {
if (file.size > limits.maxFileBytes) {
throw new Error(
`${file.path} is ${file.size} bytes; per-file limit is ${limits.maxFileBytes}`
);
}
totalBytes += file.size;
if (totalBytes > limits.maxTotalBytes) {
throw new Error(
`Repository files exceed the ${limits.maxTotalBytes}-byte total limit`
);
}
}
};
const listHostFiles = async (
checkoutDirectory: string,
limits: RepositoryMirrorLimits
): Promise<MirrorFile[]> => {
const files: MirrorFile[] = [];
const visit = async (
directory: string,
relativeDirectory: string
): Promise<void> => {
const depth = relativeDirectory
? relativeDirectory.split(path.sep).length
: 0;
if (depth > limits.maxDepth) {
throw new Error(`Repository directory depth exceeds ${limits.maxDepth}`);
}
const entries = await readdir(directory, { withFileTypes: true });
entries.sort((left, right) => left.name.localeCompare(right.name));
for (const entry of entries) {
if (!relativeDirectory && entry.name === ".git") {
continue;
}
const relativePath = path.join(relativeDirectory, entry.name);
const absolutePath = path.join(directory, entry.name);
if (entry.isSymbolicLink()) {
throw new Error(`Symbolic links are not supported: ${relativePath}`);
}
if (entry.isDirectory()) {
// oxlint-disable-next-line no-await-in-loop -- deterministic bounded traversal.
await visit(absolutePath, relativePath);
continue;
}
if (!entry.isFile()) {
throw new Error(`Unsupported repository entry: ${relativePath}`);
}
// oxlint-disable-next-line no-await-in-loop -- metadata is bounded before file transfer.
const metadata = await lstat(absolutePath);
files.push({
mode: metadata.mode % 0o1000,
path: relativePath.split(path.sep).join(path.posix.sep),
size: metadata.size,
});
enforceFileBounds(files, limits);
}
};
await visit(checkoutDirectory, "");
return files;
};
const listSandboxFiles = async (
sandbox: SandboxApi,
sandboxDirectory: string,
limits: RepositoryMirrorLimits
): Promise<MirrorFile[]> => {
const files: MirrorFile[] = [];
const visit = async (
directory: string,
relativeDirectory: string
): Promise<void> => {
const depth = relativeDirectory
? relativeDirectory.split(path.posix.sep).length
: 0;
if (depth > limits.maxDepth) {
throw new Error(`Sandbox directory depth exceeds ${limits.maxDepth}`);
}
const entries = [...(await sandbox.readdir(directory))].toSorted(
(left, right) => left.localeCompare(right)
);
for (const entry of entries) {
assertSafeEntryName(entry);
if (!relativeDirectory && entry === ".git") {
continue;
}
const relativePath = path.posix.join(relativeDirectory, entry);
const absolutePath = path.posix.join(directory, entry);
// oxlint-disable-next-line no-await-in-loop -- sandbox metadata is read sequentially and bounded.
const metadata = await sandbox.stat(absolutePath);
if (metadata.isSymbolicLink) {
throw new Error(`Symbolic links are not supported: ${relativePath}`);
}
if (metadata.isDirectory) {
// oxlint-disable-next-line no-await-in-loop -- deterministic bounded traversal.
await visit(absolutePath, relativePath);
continue;
}
if (!metadata.isFile) {
throw new Error(`Unsupported sandbox entry: ${relativePath}`);
}
if (metadata.size === undefined) {
throw new Error(`Sandbox did not report a size for ${relativePath}`);
}
files.push({ path: relativePath, size: metadata.size });
enforceFileBounds(files, limits);
}
};
await visit(sandboxDirectory, "");
return files;
};
export const mirrorHostCheckoutToSandbox = async (options: {
readonly checkoutDirectory: string;
readonly limits?: Partial<RepositoryMirrorLimits>;
readonly sandbox: SandboxApi;
readonly sandboxDirectory: string;
}): Promise<void> => {
const checkoutDirectory = assertWithinCheckout(options.checkoutDirectory);
const sandboxDirectory = assertAbsoluteSandboxDirectory(
options.sandboxDirectory
);
const limits = resolveLimits(options.limits);
const files = await listHostFiles(checkoutDirectory, limits);
await options.sandbox.mkdir(sandboxDirectory, { recursive: true });
for (const file of files) {
const hostPath = path.join(
checkoutDirectory,
...file.path.split(path.posix.sep)
);
const sandboxPath = path.posix.join(sandboxDirectory, file.path);
// oxlint-disable-next-line no-await-in-loop -- bounded sequential writes avoid overwhelming remote sandboxes.
await options.sandbox.mkdir(path.posix.dirname(sandboxPath), {
recursive: true,
});
// oxlint-disable-next-line no-await-in-loop -- bounded sequential transfer limits peak memory.
const content = await readFile(hostPath);
if (content.byteLength !== file.size) {
throw new Error(`${file.path} changed while it was being mirrored`);
}
// oxlint-disable-next-line no-await-in-loop -- bounded sequential writes avoid overwhelming remote sandboxes.
await options.sandbox.writeFile(sandboxPath, content);
}
};
const clearCheckoutFiles = async (checkoutDirectory: string): Promise<void> => {
const entries = await readdir(checkoutDirectory);
for (const entry of entries) {
if (entry === ".git") {
continue;
}
// oxlint-disable-next-line no-await-in-loop -- deletion is deliberately scoped to checkout children.
await rm(path.join(checkoutDirectory, entry), {
force: true,
recursive: true,
});
}
};
export const mirrorSandboxToHostCheckout = async (options: {
readonly checkoutDirectory: string;
readonly limits?: Partial<RepositoryMirrorLimits>;
readonly sandbox: SandboxApi;
readonly sandboxDirectory: string;
}): Promise<void> => {
const checkoutDirectory = assertWithinCheckout(options.checkoutDirectory);
const sandboxDirectory = assertAbsoluteSandboxDirectory(
options.sandboxDirectory
);
const limits = resolveLimits(options.limits);
const files = await listSandboxFiles(
options.sandbox,
sandboxDirectory,
limits
);
const originalFiles = await listHostFiles(checkoutDirectory, limits);
const originalModes = new Map(
originalFiles.map((file) => [file.path, file.mode])
);
const stagingDirectory = await mkdtemp(
path.join(path.dirname(checkoutDirectory), ".zopu-sandbox-mirror-")
);
try {
let transferredBytes = 0;
for (const file of files) {
const sandboxPath = path.posix.join(sandboxDirectory, file.path);
// oxlint-disable-next-line no-await-in-loop -- bounded sequential reads limit peak memory.
const content = await options.sandbox.readFileBuffer(sandboxPath);
if (content.byteLength !== file.size) {
throw new Error(`${file.path} changed while it was being mirrored`);
}
transferredBytes += content.byteLength;
if (transferredBytes > limits.maxTotalBytes) {
throw new Error(
`Sandbox files exceed the ${limits.maxTotalBytes}-byte total limit`
);
}
const stagedPath = path.join(
stagingDirectory,
...file.path.split(path.posix.sep)
);
// oxlint-disable-next-line no-await-in-loop -- staged writes keep the checkout intact until transfer succeeds.
await mkdir(path.dirname(stagedPath), { recursive: true });
// oxlint-disable-next-line no-await-in-loop -- bounded sequential writes limit peak memory.
await writeFile(stagedPath, content);
const originalMode = originalModes.get(file.path);
if (originalMode !== undefined) {
// oxlint-disable-next-line no-await-in-loop -- preserve executable bits for existing files.
await chmod(stagedPath, originalMode);
}
}
await clearCheckoutFiles(checkoutDirectory);
const stagedEntries = await readdir(stagingDirectory);
for (const entry of stagedEntries) {
// oxlint-disable-next-line no-await-in-loop -- each top-level entry is moved exactly once.
await rename(
path.join(stagingDirectory, entry),
path.join(checkoutDirectory, entry)
);
}
} finally {
await rm(stagingDirectory, { force: true, recursive: true });
}
};

View File

@@ -1,143 +0,0 @@
---
name: paseo
description: Paseo reference for managing workspaces, agents, schedules, and heartbeats.
---
Paseo is a daemon that supervises AI coding agents on your machine. Control it through tools or a CLI.
## Workspaces
**`create_workspace`** — create a workspace independently of any agent. Required: `isolation` (`local` or `worktree`). Worktree isolation supports `mode: "branch-off" | "checkout-branch" | "checkout-pr"`: use `branchName`/`baseBranch` for a new branch, `branch` for an existing branch, or `prNumber` plus optional `forge`/`projectPath` for a change request. `worktreeSlug` controls the managed path. Returns the workspace descriptor centered on `workspaceId`.
**`list_workspaces`** — list active workspaces.
**`archive_workspace`** — `{ workspaceId }`. Archives the workspace, its agents, and its terminals. Local directories remain; Paseo removes an owned worktree only after its final active workspace reference is archived.
Worktree creation and reference accounting are implementation details of `isolation: "worktree"`.
## Agents
**`create_agent`** — required: `title`, `provider` (`claude/opus`, `codex/gpt-5.4`, …), `initialPrompt`. Optional: `workspaceId`, `notifyOnFinish`, `settings`, `labels`. Returns `{ agentId, workspaceId, … }`.
Initial runtime settings live under `settings`: `modeId`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }` when creating the agent.
Agent-scoped creation always creates your subagent. Omit `workspaceId` to use your current workspace; pass a workspace returned by `create_workspace` for isolated delegation. Placement never changes parentage.
Detach is an explicit user action in the subagents track, not an agent tool. A cross-workspace child remains your subagent even though it also appears as a normal tab in its workspace.
Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false` only for truly fire-and-forget agents.
**`send_agent_prompt`** — `{ agentId, prompt }`. Use for follow-ups to an existing agent. Agent-scoped prompt calls default to `background: true` and `notifyOnFinish: true`; top-level calls default to blocking with no callback. For a synchronous follow-up, pass `background: false` and use the returned result.
**`update_agent`** — `{ agentId, name?, labels?, settings? }`. Use `settings` for runtime changes on an existing agent: `modeId`, `model`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }`.
**`list_agents`** — filter by `cwd`, `statuses`, `sinceHours`, `includeArchived`.
**`archive_agent`** — `{ agentId }`. Interrupts if running, removes from active list.
## Provider discovery
**`list_providers`** — compact provider availability and modes.
**`list_models`** — full model list for one provider. Use only when you need model IDs or thinking options; the list can be large.
**`inspect_provider`** — compact provider capability and feature inspection. Required: `provider`; pass `cwd` when you are not in an agent-scoped session. Optional: `settings` with draft `model`, `modeId`, `thinkingOptionId`, and `features`.
Only set feature IDs returned by `inspect_provider`. For Codex fast mode, look for `fast_mode` and pass `settings: { features: { "fast_mode": true } }` to `create_agent` or `update_agent`.
## Schedules and heartbeats
**`create_schedule`** — starts a new agent on a cron cadence. Required: `prompt`, `cron`, `provider`. Optional: `timezone`, `name`, `cwd`, `maxRuns`, `expiresIn`. Use when recurring work should live in fresh agents.
**`create_heartbeat`** — sends you a prompt on a cron cadence. Required: `prompt`, `cron`. Optional: `timezone`, `name`, `maxRuns`, `expiresIn`. Use for reminders, PR/build babysitting, and status checks that should return to this conversation.
**`delete_heartbeat`** stops it. MCP intentionally exposes no heartbeat update tool; delete and recreate when its task or cadence changes.
Schedules have the full list/inspect/update/pause/resume/run-once/log/delete surface. Heartbeats deliberately do not.
## Models
`claude/sonnet` (default), `claude/opus` (harder reasoning), `codex/gpt-5.4` (frontier coding), `claude/haiku` (tests only).
## Orchestration preferences
User-specific configuration at `~/.paseo/orchestration-preferences.json`. **Before any Paseo skill chooses a provider or creates an agent, it must read this file.** Reading means an actual file read, not relying on these examples or defaults. Never hardcode a provider string in another skill — resolve through this file.
Two parts:
- `providers` — map of role categories to provider strings. Pass straight to `create_agent`'s `provider` field.
- `preferences` — freeform string array. Read on startup; weave into agent prompts contextually.
Categories: `impl`, `ui`, `research`, `planning`, `audit`. Skills pick the category that matches the role they're launching.
```json
{
"providers": {
"impl": "codex/gpt-5.4",
"ui": "claude/opus",
"research": "codex/gpt-5.4",
"planning": "codex/gpt-5.4",
"audit": "codex/gpt-5.4"
},
"preferences": [
"Claude Opus is the right choice for anything artistic or human-skill-oriented: copywriting, naming, UX copy, visual design, styling. Codex is the workhorse for mechanical work."
]
}
```
If the file is missing, use sensible defaults and tell the user once.
## Waiting
Agents take time — 1030+ minutes is routine. Favor asynchronous workflows.
For agent-scoped `create_agent` and background `send_agent_prompt`, leave `notifyOnFinish` omitted or set it to `true` unless the work is truly fire-and-forget. You will get notified when the target agent finishes, errors, or needs permission. Move on to other work. The notification arrives on its own.
Don't poll `list_agents` or `get_agent_status` to "check on" a running agent. The notification will tell you.
## CLI semantics
The CLI and tools use the same ownership semantics even where their syntax differs:
```bash
paseo workspace create --isolation worktree --mode branch-off --new-branch fix-x --base main
paseo workspace create --isolation worktree --mode checkout-branch --branch existing-work
paseo workspace create --isolation worktree --mode checkout-pr --pr-number 42
paseo run --provider codex/gpt-5.4 --mode full-access --workspace <workspace-id> "<prompt>"
paseo send <agent-id> "<follow-up>"
paseo ls
paseo schedule create --cron "*/15 * * * *" "ping main build"
paseo heartbeat create --cron "*/15 * * * *" "check the build"
```
Discover with `paseo --help` and `paseo <cmd> --help`.
**If `paseo` isn't on PATH but the desktop app is installed**, the bundled CLI is at:
- macOS: `/Applications/Paseo.app/Contents/Resources/bin/paseo`
- Linux: `<install-dir>/resources/bin/paseo`
- Windows: `C:\Program Files\Paseo\resources\bin\paseo.cmd`
The desktop app's first-run hook (`installCli`) symlinks this to `~/.local/bin/paseo` (macOS/Linux) or drops a `.cmd` trampoline (Windows) and adds `~/.local/bin` to PATH via shell rc files. If that didn't take, offer to symlink it — don't do it silently.
## Ops and debugging
Daemon-client architecture: the daemon owns agent lifecycle, state, and the WebSocket API. Tools, CLI, mobile, and desktop apps are all clients.
| | Default |
| --- | --- |
| Listen address | `127.0.0.1:6767` (override `PASEO_LISTEN`) |
| Home | `~/.paseo` (override `PASEO_HOME`) |
| Daemon log | `$PASEO_HOME/daemon.log` |
| Agent state | `$PASEO_HOME/agents/<id>.json` |
| Worktrees | `$PASEO_HOME/worktrees/` (or `worktrees.root` in `config.json`) |
| PID file | `$PASEO_HOME/paseo.pid` |
| Health | `GET http://127.0.0.1:6767/api/health` |
Debug order:
1. `tail -n 200 ~/.paseo/daemon.log`.
2. `paseo daemon status` for liveness.
3. `curl -s localhost:6767/api/health` if the CLI itself is suspect.
**Never restart the daemon without explicit user approval** — it kills every running agent, including, often, the one asking.

View File

@@ -1,119 +0,0 @@
import {
createBranch,
createIssue,
createPullRequest,
fetchTransport,
listIssues,
} from "@code/primitives/git-remote-runtime";
import type {
GitRemoteConfig,
GitRemoteError,
} from "@code/primitives/git-remote-runtime";
import { defineTool } from "@flue/runtime";
import { Effect } from "effect";
import * as v from "valibot";
/**
* Canonical repo for the bootstrap: one self-hosted Gitea repo hosts all work.
* Hard-coded owner/repo keeps the agent off credential-shaped free input.
*/
export const CANONICAL_REPO = { owner: "puter", repo: "zopu-code" } as const;
export const makeGitRemoteConfig = (runtimeEnv: {
readonly GITEA_TOKEN?: string;
readonly GITEA_URL: string;
}): GitRemoteConfig => {
if (!runtimeEnv.GITEA_TOKEN) {
throw new Error(
"GITEA_TOKEN is required to configure the git remote tools"
);
}
return {
baseUrl: runtimeEnv.GITEA_URL,
owner: CANONICAL_REPO.owner,
repo: CANONICAL_REPO.repo,
token: runtimeEnv.GITEA_TOKEN,
};
};
const run = <A, E>(eff: Effect.Effect<A, E>): Promise<A> =>
Effect.runPromise(eff);
const describeError = (error: GitRemoteError) => ({
error: error.message,
reason: error.reason,
});
// Tool returns are serialized to the model; round-trip through JSON so the
// Effect-branded/readonly value objects become plain mutable JsonValue.
// oxlint-disable-next-line unicorn/prefer-structured-clone -- structuredClone keeps readonly modifiers; JSON erases them for JsonValue
const json = (value: unknown) => JSON.parse(JSON.stringify(value));
/**
* Git-remote tools bound to the canonical repo. The agent creates issues,
* branches, and pull requests on puter/zopu-code via the Gitea API using the
* server-side token — it never accepts credentials or repo paths as input.
*/
export const createGitRemoteTools = (config: GitRemoteConfig) => [
defineTool({
description:
"Create an issue on the canonical zopu-code repository. Use this to turn an agreed-upon piece of work into a tracked issue. Returns the issue number and URL. Always call list_issues first to avoid duplicates.",
input: v.object({
body: v.string(),
title: v.string(),
}),
name: "create_issue",
async run({ input }) {
const result = await run(
createIssue(fetchTransport, config, input)
).catch(describeError);
return json(result);
},
}),
defineTool({
description:
"List open issues on the canonical zopu-code repository. Call this before creating an issue to check for duplicates and understand existing work.",
name: "list_issues",
async run() {
const result = await run(listIssues(fetchTransport, config)).catch(
describeError
);
return json(result);
},
}),
defineTool({
description:
"Create a remote branch on the canonical zopu-code repository. Usually you do not need this directly — start_workflow handles branching for a work run. Use only when explicitly setting up a branch by hand.",
input: v.object({
from: v.optional(v.string()),
name: v.string(),
}),
name: "create_branch",
async run({ input }) {
const result = await run(
createBranch(fetchTransport, config, input)
).catch(describeError);
return json(result);
},
}),
defineTool({
description:
"Open a pull request on the canonical zopu-code repository. Provide the work branch, the base branch (usually main), a title, and a body. Returns the PR number and URL.",
input: v.object({
baseBranch: v.string(),
body: v.string(),
branch: v.string(),
title: v.string(),
}),
name: "create_pull_request",
async run({ input }) {
const result = await run(
createPullRequest(fetchTransport, config, input)
).catch(describeError);
return json(result);
},
}),
];

View File

@@ -1,43 +0,0 @@
import { spawn } from "node:child_process";
import { once } from "node:events";
import path from "node:path";
import { defineTool } from "@flue/runtime";
import * as v from "valibot";
const repositoryRoot = path.resolve(process.cwd(), "../..");
export const paseoCli = defineTool({
description:
"Run the locally installed Paseo CLI. Pass every argument exactly as it should appear after the paseo executable.",
input: v.object({
args: v.array(v.string()),
}),
name: "paseo_cli",
output: v.object({
exitCode: v.number(),
stderr: v.string(),
stdout: v.string(),
}),
async run({ input, signal }) {
const process = spawn("paseo", input.args, {
cwd: repositoryRoot,
signal,
stdio: ["ignore", "pipe", "pipe"],
});
const stderrChunks: Buffer[] = [];
const stdoutChunks: Buffer[] = [];
process.stderr.on("data", (chunk: Buffer) => stderrChunks.push(chunk));
process.stdout.on("data", (chunk: Buffer) => stdoutChunks.push(chunk));
const [code] = await once(process, "close");
const exitCode = typeof code === "number" ? code : 1;
return {
exitCode,
stderr: Buffer.concat(stderrChunks).toString(),
stdout: Buffer.concat(stdoutChunks).toString(),
};
},
});

View File

@@ -1,70 +0,0 @@
import { api } from "@code/backend/convex/_generated/api";
import type { Id } from "@code/backend/convex/_generated/dataModel";
import { ARTIFACT_PATHS } from "@code/backend/convex/artifactModel";
import { parseAgentEnv } from "@code/env/agent";
import { defineTool } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import * as v from "valibot";
export const createProjectTools = (
issueAgentId: string,
runtimeEnv: Record<string, string | undefined>
) => {
const env = parseAgentEnv(runtimeEnv);
const client = new ConvexHttpClient(env.CONVEX_URL);
// Flue receives this controlled id from the issue card that starts the run.
const issueId = issueAgentId as Id<"projectIssues">;
return [
defineTool({
description:
"Read the repository, issue, and canonical project artifacts bound to this agent.",
name: "lookup_issue_context",
async run() {
return await client.query(api.agentWorkspace.get, {
issueId,
token: env.FLUE_DB_TOKEN,
});
},
}),
defineTool({
description:
"Publish the complete current content of one canonical project markdown artifact after changing it in AgentOS.",
input: v.object({
content: v.pipe(v.string(), v.maxLength(200_000)),
path: v.picklist(ARTIFACT_PATHS),
}),
name: "publish_project_artifact",
async run({ input }) {
const revision = await client.mutation(
api.agentWorkspace.updateArtifact,
{
content: input.content,
issueId,
path: input.path,
token: env.FLUE_DB_TOKEN,
}
);
return { path: input.path, revision };
},
}),
defineTool({
description:
"Report the durable issue state. Use needs-input before asking a blocking question and completed only after verification.",
input: v.object({
status: v.picklist(["working", "needs-input", "completed", "failed"]),
summary: v.pipe(v.string(), v.maxLength(4000)),
}),
name: "report_work_status",
async run({ input }) {
await client.mutation(api.agentWorkspace.setStatus, {
issueId,
status: input.status,
summary: input.summary,
token: env.FLUE_DB_TOKEN,
});
return { recorded: true, status: input.status };
},
}),
];
};

View File

@@ -1,368 +0,0 @@
import { parseAgentEnv } from "@code/env/agent";
import { ProjectIssueDispatchInput } from "@code/primitives/project-issue";
import { defineTool, dispatch } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import { makeFunctionReference } from "convex/server";
import { Schema } from "effect";
import * as v from "valibot";
// ---------------------------------------------------------------------------
// Agent-gated Convex function references for the routing loop.
// ---------------------------------------------------------------------------
const listEvidenceRef = makeFunctionReference<
"query",
{ readonly organizationId: string; readonly token: string },
{
messageId: string;
rawText: string;
createdAt: number;
submissionId: string | null;
}[]
>("signalRouting:listEvidence");
const createSignalRef = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly projectId?: string;
messageIds: string[];
readonly problemStatement: {
readonly title: string;
readonly summary: string;
readonly desiredOutcome: string;
constraints: string[];
};
readonly processedByAgentInstanceId: string;
readonly token: string;
},
{ signalId: string }
>("signalRouting:createSignal");
const listSignalsRef = makeFunctionReference<
"query",
{
readonly organizationId: string;
readonly projectId?: string;
readonly token: string;
},
{
_id: string;
createdAt: number;
problemStatement: {
title: string;
summary: string;
desiredOutcome: string;
constraints: string[];
};
projectId: string | null;
}[]
>("signalRouting:listSignals");
const listActiveIssuesRef = makeFunctionReference<
"query",
{
readonly organizationId: string;
readonly projectId: string;
readonly token: string;
},
{
_id: string;
number: number;
title: string;
body: string;
status: string;
projectId: string;
updatedAt: number;
}[]
>("signalRouting:listActiveIssues");
const attachSignalToIssueRef = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly signalId: string;
readonly issueId: string;
readonly token: string;
},
{ attachmentId: string; alreadyAttached: boolean }
>("signalRouting:attachSignalToIssue");
const createIssueFromSignalRef = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly signalId: string;
readonly token: string;
},
{ issueId: string; projectId: string }
>("signalRouting:createIssueFromSignal");
const beginIssueRef = makeFunctionReference<
"mutation",
{
readonly organizationId: string;
readonly issueId: string;
readonly token: string;
},
{
readonly dispatchRequired: boolean;
readonly projectId: string;
readonly status: "queued" | "working";
}
>("signalRouting:beginIssue");
const markDispatchFailedRef = makeFunctionReference<
"mutation",
{
readonly error: string;
readonly issueId: string;
readonly organizationId: string;
readonly token: string;
},
null
>("signalRouting:markDispatchFailed");
const getProjectContextRef = makeFunctionReference<
"query",
{
readonly organizationId: string;
readonly projectId: string;
readonly token: string;
},
{
project: {
_id: string;
name: string;
description: string | null;
organizationId: string;
};
contextDocuments: {
kind: string;
path: string;
content: string;
revision: number;
}[];
}
>("signalRouting:getProjectContext");
const listProjectsRef = makeFunctionReference<
"query",
{
readonly organizationId: string;
readonly token: string;
},
{
_id: string;
name: string;
description: string | null;
organizationId: string;
}[]
>("signalRouting:listProjects");
// ---------------------------------------------------------------------------
// Tool factory: creates all routing tools bound to one agent instance.
//
// The `instanceId` is the organization ID (established by the authenticated
// route middleware). The tool never accepts organization ID as free input;
// it always comes from the bound instance. This is the hard tenancy boundary.
// ---------------------------------------------------------------------------
export const createSignalRoutingTools = (
instanceId: string,
runtimeEnv: Record<string, string | undefined>
) => {
const env = parseAgentEnv(runtimeEnv);
const client = new ConvexHttpClient(env.CONVEX_URL);
const token = env.FLUE_DB_TOKEN;
// The instance id is the organization id; tools are scoped to it.
const organizationId = instanceId;
return [
defineTool({
description:
"List projects in the current organization. Call this first to identify the project context the user is working in.",
name: "list_projects",
async run() {
return await client.query(listProjectsRef, {
organizationId,
token,
});
},
}),
defineTool({
description:
"Read the project name, description, and canonical context documents (README, product, design, tech, agents). Use this to understand the project before routing work.",
input: v.object({
projectId: v.string(),
}),
name: "get_project_context",
async run({ input }) {
return await client.query(getProjectContextRef, {
organizationId,
projectId: input.projectId,
token,
});
},
}),
defineTool({
description:
"List admitted user messages in the current conversation that have not yet been consumed by a Signal. These are the candidate evidence messages. Raw text is exact — never modify it.",
name: "list_signal_evidence",
async run() {
return await client.query(listEvidenceRef, {
organizationId,
token,
});
},
}),
defineTool({
description:
"Create a Signal from one or more admitted user messages plus a structured problem statement. Use ONLY when the conversation contains an actionable problem, request, blocker, or decision. Do NOT create Signals for casual chat, greetings, or exploration without a concrete problem. The problemStatement must faithfully represent the user's own words — do not invent or rewrite their intent.",
input: v.object({
messageIds: v.array(v.string()),
problemStatement: v.object({
constraints: v.array(v.string()),
desiredOutcome: v.string(),
summary: v.string(),
title: v.string(),
}),
projectId: v.optional(v.string()),
}),
name: "create_signal",
async run({ input }) {
return await client.mutation(createSignalRef, {
messageIds: input.messageIds,
organizationId,
problemStatement: input.problemStatement,
...(input.projectId === undefined
? {}
: { projectId: input.projectId }),
processedByAgentInstanceId: organizationId,
token,
});
},
}),
defineTool({
description:
"List recent Signals for a project (or organization-wide if no projectId). Use this to see what has already been captured.",
input: v.object({
projectId: v.optional(v.string()),
}),
name: "list_recent_signals",
async run({ input }) {
return await client.query(listSignalsRef, {
organizationId,
...(input.projectId === undefined
? {}
: { projectId: input.projectId }),
token,
});
},
}),
defineTool({
description:
"List active (open, queued, working, needs-input) ProjectIssues for a project. Use this to find existing issues that a new Signal might relate to before deciding whether to attach or create a new one.",
input: v.object({
projectId: v.string(),
}),
name: "list_active_issues",
async run({ input }) {
return await client.query(listActiveIssuesRef, {
organizationId,
projectId: input.projectId,
token,
});
},
}),
defineTool({
description:
"Attach a Signal to an existing ProjectIssue. This links the signal's evidence to an open issue. Idempotent: repeating the same attachment is safe and returns the existing relation. Use when the signal's problem clearly relates to an existing active issue.",
input: v.object({
issueId: v.string(),
signalId: v.string(),
}),
name: "attach_signal_to_issue",
async run({ input }) {
return await client.mutation(attachSignalToIssueRef, {
issueId: input.issueId,
organizationId,
signalId: input.signalId,
token,
});
},
}),
defineTool({
description:
"Create a new ProjectIssue from a Signal. The signal must be project-scoped. This also auto-attaches the signal to the new issue. Use when the signal's problem does not match any existing active issue.",
input: v.object({
signalId: v.string(),
}),
name: "create_issue_from_signal",
async run({ input }) {
return await client.mutation(createIssueFromSignalRef, {
organizationId,
signalId: input.signalId,
token,
});
},
}),
defineTool({
description:
"Begin working on a ProjectIssue by transitioning it to queued. Use only after the user explicitly confirms they want to start the issue. Returns the new status.",
input: v.object({
issueId: v.string(),
}),
name: "begin_issue",
async run({ input }) {
const outcome = await client.mutation(beginIssueRef, {
issueId: input.issueId,
organizationId,
token,
});
const dispatchInput = Schema.decodeUnknownSync(
ProjectIssueDispatchInput
)({
issueId: input.issueId,
kind: "project.issue.started",
projectId: outcome.projectId,
});
if (!outcome.dispatchRequired) {
return {
acceptedAt: "",
dispatchId: "",
status: outcome.status,
};
}
try {
const receipt = await dispatch({
agent: "project-manager",
id: input.issueId,
input: dispatchInput,
});
return {
acceptedAt: receipt.acceptedAt,
dispatchId: receipt.dispatchId,
status: outcome.status,
};
} catch (error) {
await client.mutation(markDispatchFailedRef, {
error: error instanceof Error ? error.message : String(error),
issueId: input.issueId,
organizationId,
token,
});
throw error;
}
},
}),
];
};

View File

@@ -1,37 +0,0 @@
import { defineTool } from "@flue/runtime";
import { ConvexHttpClient } from "convex/browser";
import { makeFunctionReference } from "convex/server";
import * as v from "valibot";
// The control-plane mutation that enqueues a work run for an issue. Implemented
// in the backend Convex workflow module; referenced by name so the agent never
// imports generated bindings.
const startIssueWorkRef = makeFunctionReference<
"mutation",
{ readonly issueNumber: number; readonly token: string },
{ readonly runId: string; readonly status: string }
>("workflows:startIssueWork");
export const createWorkflowTools = (clientOptions: {
readonly convexUrl: string;
readonly token: string;
}) => {
const client = new ConvexHttpClient(clientOptions.convexUrl);
return [
defineTool({
description:
"Start the autonomous work workflow for an existing zopu-code issue. This spawns a Codex agent in an isolated worktree of the canonical repo, gives it the issue, lets it implement and verify the change, then commits and opens a pull request. Use it after create_issue (or for an existing issue number) once the user confirms they want work to begin. Returns the run id and initial status.",
input: v.object({
issueNumber: v.number(),
}),
name: "start_workflow",
async run({ input }) {
return await client.mutation(startIssueWorkRef, {
issueNumber: input.issueNumber,
token: clientOptions.token,
});
},
}),
];
};

View File

@@ -22,7 +22,7 @@
"expo-constants": "~57.0.2",
"expo-secure-store": "~57.0.0",
"heroui-native": "catalog:",
"react": "^19.2.3",
"react": "catalog:",
"react-native": "0.86.0",
"sonner": "catalog:",
"zod": "catalog:"
@@ -30,8 +30,8 @@
"devDependencies": {
"@code/config": "workspace:*",
"@types/react": "~19.2.17",
"vite": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "catalog:"
}
}

View File

@@ -1,8 +1,8 @@
import { env } from "@code/env/web";
import { convexClient, crossDomainClient } from "@convex-dev/better-auth/client/plugins";
import { convexClient } from "@convex-dev/better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: env.VITE_CONVEX_SITE_URL,
plugins: [convexClient(), crossDomainClient()],
baseURL: env.VITE_AUTH_URL,
plugins: [convexClient()],
});

Some files were not shown because too many files have changed in this diff Show More