Compare commits
23 Commits
t3code/sli
...
a907539810
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a907539810 | ||
|
|
601aca73c2 | ||
|
|
ffecff3857 | ||
|
|
0d7162544b | ||
|
|
092a9793ea | ||
|
|
5ee0a8d50e | ||
|
|
420676f2d7 | ||
|
|
24d82e2a06 | ||
|
|
d47fa0e96a | ||
|
|
1e7c893985 | ||
|
|
f9ebcb4a01 | ||
|
|
dceaa2b417 | ||
|
|
a4f121e190 | ||
|
|
4edd456b5b | ||
|
|
4d9f6da41b | ||
|
|
a53029cf7a | ||
|
|
eede4c10ba | ||
|
|
35169672e1 | ||
|
|
359d9e2285 | ||
|
|
05a3baaac3 | ||
|
|
4cc40cb2e4 | ||
|
|
814df02be9 | ||
|
|
d7f6cbdcdc |
@@ -17,7 +17,9 @@ DAEMON_NAME=Local MacBook
|
||||
DAEMON_VERSION=0.0.0
|
||||
DAEMON_HEARTBEAT_MS=15000
|
||||
DAEMON_COMMAND_LEASE_MS=60000
|
||||
# RIVET_ENDPOINT=http://localhost:6420
|
||||
RIVET_ENDPOINT=http://localhost:6420
|
||||
RIVET_PUBLIC_ENDPOINT=http://localhost:6420
|
||||
RIVET_WORKSPACE_TOKEN=replace-with-a-long-random-workspace-token
|
||||
|
||||
# Flue persistence adapter
|
||||
FLUE_DB_TOKEN=replace-with-a-long-random-token
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
} from "@code/ui/components/ai-elements/conversation";
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import {
|
||||
AlertTriangle,
|
||||
ChevronRight,
|
||||
Check,
|
||||
FileCode2,
|
||||
FolderGit2,
|
||||
Hammer,
|
||||
LoaderCircle,
|
||||
@@ -15,8 +17,10 @@ import {
|
||||
ImagePlus,
|
||||
Play,
|
||||
RotateCcw,
|
||||
ScrollText,
|
||||
Send,
|
||||
Sparkles,
|
||||
Settings,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
@@ -35,6 +39,28 @@ import {
|
||||
type SliceWork = NonNullable<ReturnType<typeof useSliceOne>["works"]>[number];
|
||||
const EMPTY_WORKS: readonly SliceWork[] = [];
|
||||
|
||||
type SliceArtifact = NonNullable<
|
||||
NonNullable<SliceWork["runs"][number]["artifacts"]>[number]
|
||||
>;
|
||||
|
||||
interface ArtifactMetadata {
|
||||
readonly changedFiles?: readonly string[];
|
||||
}
|
||||
|
||||
const parseArtifactMetadata = (artifact: SliceArtifact): ArtifactMetadata => {
|
||||
if (!artifact.metadataJson) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
return JSON.parse(artifact.metadataJson) as ArtifactMetadata;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const changedFilesFor = (artifact: SliceArtifact): readonly string[] =>
|
||||
parseArtifactMetadata(artifact).changedFiles ?? [];
|
||||
|
||||
interface WorkCardProps {
|
||||
readonly onSourceSelect: (rawText: string) => void;
|
||||
readonly work: SliceWork;
|
||||
@@ -95,6 +121,7 @@ const starterDesign = (work: SliceWork) => ({
|
||||
const WorkCard = ({ onSourceSelect, work, slice }: WorkCardProps) => {
|
||||
const [sourcesOpen, setSourcesOpen] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [logsOpen, setLogsOpen] = useState(false);
|
||||
const sources = work.signals.flatMap((signal) => signal.sources);
|
||||
const { definition } = work;
|
||||
const { design } = work;
|
||||
@@ -257,26 +284,122 @@ const WorkCard = ({ onSourceSelect, work, slice }: WorkCardProps) => {
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Build
|
||||
</p>
|
||||
{latestRun ? (
|
||||
<p className="mt-1 leading-5 text-[#626057]">
|
||||
Run {latestRun.status}:{" "}
|
||||
{latestRun.terminalSummary ??
|
||||
latestRun.terminalClassification ??
|
||||
"activity is still arriving"}
|
||||
{slice.operationError ? (
|
||||
<p className="mt-2 flex items-start gap-1.5 border border-red-300 bg-red-50 px-2 py-1.5 text-red-800">
|
||||
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 leading-5">
|
||||
{slice.operationError.message}
|
||||
</span>
|
||||
<button
|
||||
aria-label="Dismiss error"
|
||||
className="shrink-0"
|
||||
onClick={() => slice.clearOperationError()}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</p>
|
||||
) : null}
|
||||
{latestRun ? (
|
||||
<div className="mt-1 space-y-2 text-[#626057]">
|
||||
<p className="leading-5">
|
||||
{latestRun.executionKind === "real"
|
||||
? "AgentOS"
|
||||
: "Simulation"}{" "}
|
||||
run {latestRun.status}:{" "}
|
||||
{latestRun.terminalSummary ??
|
||||
latestRun.terminalClassification ??
|
||||
"activity is still arriving"}
|
||||
</p>
|
||||
{latestRun.baseRevision ? (
|
||||
<p className="font-mono text-[10px] text-[#747168]">
|
||||
{latestRun.baseRevision.slice(0, 8)} →{" "}
|
||||
{latestRun.candidateRevision?.slice(0, 8) ?? "working"}
|
||||
</p>
|
||||
) : null}
|
||||
{latestRun.artifacts?.map((artifact) => {
|
||||
const changedFiles = changedFilesFor(artifact);
|
||||
return (
|
||||
<div key={artifact._id} className="space-y-1">
|
||||
{artifact.uri ? (
|
||||
<a
|
||||
className="block font-medium underline"
|
||||
href={artifact.uri}
|
||||
rel="noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{artifact.title}
|
||||
</a>
|
||||
) : (
|
||||
<p className="font-medium">{artifact.title}</p>
|
||||
)}
|
||||
{changedFiles.length > 0 ? (
|
||||
<ul className="space-y-0.5">
|
||||
{changedFiles.map((file) => (
|
||||
<li
|
||||
className="flex items-start gap-1.5 font-mono text-[11px] leading-5 text-[#747168]"
|
||||
key={file}
|
||||
>
|
||||
<FileCode2 className="mt-0.5 size-3 shrink-0 text-[#9a985f]" />
|
||||
<span className="min-w-0 break-all">{file}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{latestRun.attemptEvents &&
|
||||
latestRun.attemptEvents.length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
{(logsOpen
|
||||
? latestRun.attemptEvents
|
||||
: latestRun.attemptEvents.slice(-3)
|
||||
).map((item) => (
|
||||
<p
|
||||
className="border-l-2 border-[#b8c760] pl-2 leading-5"
|
||||
key={item._id}
|
||||
>
|
||||
{item.message}
|
||||
</p>
|
||||
))}
|
||||
{latestRun.attemptEvents.length > 3 ? (
|
||||
<button
|
||||
className="flex items-center gap-1 font-medium text-[#65713a] hover:underline"
|
||||
onClick={() => setLogsOpen((open) => !open)}
|
||||
type="button"
|
||||
>
|
||||
<ScrollText className="size-3.5" />
|
||||
{logsOpen
|
||||
? "Show recent activity"
|
||||
: `Show full activity log (${latestRun.attemptEvents.length})`}
|
||||
<ChevronRight
|
||||
className={`size-3.5 transition-transform ${logsOpen ? "rotate-90" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-1 text-[#747168]">No simulation Run yet.</p>
|
||||
<p className="mt-1 text-[#747168]">No implementation Run yet.</p>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "ready" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!slice.projectGitConnection}
|
||||
onClick={() => void slice.startExecution(work._id)}
|
||||
>
|
||||
<Play className="size-3.5" /> Run
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "ready" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void slice.startSimulation(
|
||||
work._id,
|
||||
"success",
|
||||
design?.slices?.[0]?.id
|
||||
)
|
||||
void slice.startSimulation(work._id, "success")
|
||||
}
|
||||
>
|
||||
<Play className="size-3.5" /> Simulate
|
||||
@@ -286,12 +409,17 @@ const WorkCard = ({ onSourceSelect, work, slice }: WorkCardProps) => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void slice.cancelSimulation(latestRun._id)}
|
||||
onClick={() =>
|
||||
void (latestRun.executionKind === "real"
|
||||
? slice.cancelExecution(latestRun._id)
|
||||
: slice.cancelSimulation(latestRun._id))
|
||||
}
|
||||
>
|
||||
<X className="size-3.5" /> Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
{latestRun?.status === "terminal" &&
|
||||
{latestRun?.executionKind !== "real" &&
|
||||
latestRun?.status === "terminal" &&
|
||||
latestRun.terminalClassification === "RetryableFailure" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -381,6 +509,7 @@ const ConnectProject = ({ slice }: { slice: SliceOneState }) => (
|
||||
</main>
|
||||
);
|
||||
|
||||
// oxlint-disable-next-line complexity -- this page coordinates the existing mobile shell without owning domain logic.
|
||||
export const SliceOnePage = () => {
|
||||
const slice = useSliceOne();
|
||||
const viewportStyle = useVisualViewportStyle();
|
||||
@@ -388,6 +517,10 @@ export const SliceOnePage = () => {
|
||||
const attachments = useChatImages();
|
||||
const imageInput = useRef<HTMLInputElement>(null);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [giteaUrl, setGiteaUrl] = useState("https://git.openputer.com");
|
||||
const [giteaUsername, setGiteaUsername] = useState("");
|
||||
const [giteaToken, setGiteaToken] = useState("");
|
||||
const [highlightedMessageId, setHighlightedMessageId] = useState<string>();
|
||||
const highlightTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const works = slice.works ?? EMPTY_WORKS;
|
||||
@@ -450,7 +583,7 @@ export const SliceOnePage = () => {
|
||||
style={viewportStyle}
|
||||
>
|
||||
<section className="flex min-w-0 flex-1 flex-col">
|
||||
<header className="flex h-14 shrink-0 items-center border-b border-[#d7d3c7] bg-[#faf9f4] px-4">
|
||||
<header className="relative flex h-14 shrink-0 items-center border-b border-[#d7d3c7] bg-[#faf9f4] px-4">
|
||||
<div className="min-w-0 flex-1 pr-2">
|
||||
<select
|
||||
aria-label="Current project"
|
||||
@@ -468,6 +601,15 @@ export const SliceOnePage = () => {
|
||||
Conversation to proposed Work
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
aria-label="Project settings"
|
||||
className="mr-2 size-9"
|
||||
onClick={() => setSettingsOpen((open) => !open)}
|
||||
size="icon"
|
||||
variant="outline"
|
||||
>
|
||||
<Settings className="size-4" />
|
||||
</Button>
|
||||
<button
|
||||
className="flex h-9 items-center gap-2 border border-[#c9c5b9] bg-white px-3 text-xs lg:hidden"
|
||||
onClick={() => setDrawerOpen(true)}
|
||||
@@ -476,6 +618,94 @@ export const SliceOnePage = () => {
|
||||
<Menu className="size-4" /> Work{" "}
|
||||
{slice.works === undefined ? "…" : works.length}
|
||||
</button>
|
||||
{settingsOpen ? (
|
||||
<section className="absolute right-4 top-12 z-40 w-[min(92vw,360px)] border border-[#c9c5b9] bg-[#fffefa] p-4 shadow-xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-sm font-semibold">Project Git</h2>
|
||||
<button
|
||||
aria-label="Close settings"
|
||||
onClick={() => setSettingsOpen(false)}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-[#747168]">
|
||||
{slice.projectGitConnection
|
||||
? `${slice.projectGitConnection.provider} · ${slice.projectGitConnection.serverUrl}`
|
||||
: "No Git credentials attached"}
|
||||
</p>
|
||||
{slice.operationError ? (
|
||||
<p className="mt-2 flex items-start gap-1.5 border border-red-300 bg-red-50 px-2 py-1.5 text-xs text-red-800">
|
||||
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 leading-5">
|
||||
{slice.operationError.message}
|
||||
</span>
|
||||
<button
|
||||
aria-label="Dismiss error"
|
||||
className="shrink-0"
|
||||
onClick={() => slice.clearOperationError()}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void slice.authorizeGithub()}
|
||||
>
|
||||
Authorize GitHub
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => void slice.connectLinkedGithub()}
|
||||
>
|
||||
Use GitHub
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2 border-t border-[#e7e3d9] pt-4">
|
||||
<input
|
||||
aria-label="Gitea server URL"
|
||||
className="h-9 w-full border px-2 text-xs"
|
||||
onChange={(event) => setGiteaUrl(event.target.value)}
|
||||
value={giteaUrl}
|
||||
/>
|
||||
<input
|
||||
aria-label="Gitea username"
|
||||
className="h-9 w-full border px-2 text-xs"
|
||||
onChange={(event) => setGiteaUsername(event.target.value)}
|
||||
placeholder="Username (optional)"
|
||||
value={giteaUsername}
|
||||
/>
|
||||
<input
|
||||
aria-label="Gitea access token"
|
||||
className="h-9 w-full border px-2 text-xs"
|
||||
onChange={(event) => setGiteaToken(event.target.value)}
|
||||
placeholder="Personal access token"
|
||||
type="password"
|
||||
value={giteaToken}
|
||||
/>
|
||||
<Button
|
||||
className="w-full"
|
||||
disabled={!giteaToken.trim()}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void slice.connectGitea({
|
||||
serverUrl: giteaUrl,
|
||||
token: giteaToken,
|
||||
username: giteaUsername || undefined,
|
||||
});
|
||||
setGiteaToken("");
|
||||
}}
|
||||
>
|
||||
Connect Gitea
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</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">
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { authClient } from "@code/auth/web";
|
||||
import { api } from "@code/backend/convex/_generated/api";
|
||||
import type { Id } from "@code/backend/convex/_generated/dataModel";
|
||||
import { useAction, useMutation, useQuery } from "convex/react";
|
||||
@@ -27,6 +28,25 @@ interface WorkRecord {
|
||||
readonly designs: readonly unknown[];
|
||||
readonly slices: readonly unknown[];
|
||||
readonly runs: readonly {
|
||||
readonly artifacts?: readonly {
|
||||
_id: string;
|
||||
kind: string;
|
||||
metadataJson: string;
|
||||
sourceRevision?: string;
|
||||
title: string;
|
||||
uri?: string;
|
||||
}[];
|
||||
readonly attemptEvents?: readonly {
|
||||
_id: string;
|
||||
kind: string;
|
||||
message: string;
|
||||
metadataJson: string;
|
||||
occurredAt: number;
|
||||
sequence: number;
|
||||
}[];
|
||||
readonly baseRevision?: string;
|
||||
readonly candidateRevision?: string;
|
||||
readonly executionKind?: string;
|
||||
_id: Id<"workRuns">;
|
||||
status: string;
|
||||
terminalClassification?: string;
|
||||
@@ -96,6 +116,57 @@ const retrySimulationRef = makeFunctionReference<
|
||||
{ runId: Id<"workRuns"> },
|
||||
unknown
|
||||
>("workExecution:retrySimulatedExecution");
|
||||
const startExecutionRef = makeFunctionReference<
|
||||
"mutation",
|
||||
{ workId: Id<"works">; sliceId?: string },
|
||||
unknown
|
||||
>("workExecutionWorkflow:startExecution");
|
||||
const cancelExecutionRef = makeFunctionReference<
|
||||
"mutation",
|
||||
{ runId: Id<"workRuns"> },
|
||||
unknown
|
||||
>("workExecutionWorkflow:cancelExecution");
|
||||
const listGitConnectionsRef = makeFunctionReference<
|
||||
"query",
|
||||
Record<string, never>,
|
||||
readonly {
|
||||
id: string;
|
||||
provider: "github" | "gitea";
|
||||
serverUrl: string;
|
||||
username?: string;
|
||||
}[]
|
||||
>("gitConnectionData:list");
|
||||
const projectGitConnectionRef = makeFunctionReference<
|
||||
"query",
|
||||
{ projectId: Id<"projects"> },
|
||||
{
|
||||
id: string;
|
||||
provider: "github" | "gitea";
|
||||
serverUrl: string;
|
||||
username?: string;
|
||||
} | null
|
||||
>("gitConnectionData:getForProject");
|
||||
const connectGiteaRef = makeFunctionReference<
|
||||
"action",
|
||||
{ serverUrl: string; token: string; username?: string },
|
||||
{ connectionId: Id<"gitConnections"> }
|
||||
>("gitConnections:connectGitea");
|
||||
const connectGithubRef = makeFunctionReference<
|
||||
"action",
|
||||
Record<string, never>,
|
||||
{ connectionId: Id<"gitConnections"> }
|
||||
>("gitConnections:connectGithub");
|
||||
const attachGitConnectionRef = makeFunctionReference<
|
||||
"mutation",
|
||||
{ connectionId: Id<"gitConnections">; projectId: Id<"projects"> },
|
||||
unknown
|
||||
>("gitConnectionData:attachToProject");
|
||||
|
||||
const authorizeGithub = () =>
|
||||
authClient.signIn.social({
|
||||
callbackURL: window.location.href,
|
||||
provider: "github",
|
||||
});
|
||||
|
||||
export const useSliceOne = () => {
|
||||
const organization = usePersonalOrganization();
|
||||
@@ -110,6 +181,20 @@ export const useSliceOne = () => {
|
||||
const [repository, setRepository] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<Error>();
|
||||
const [operationError, setOperationError] = useState<Error>();
|
||||
const captureOperationError =
|
||||
<TArgs extends unknown[], TResult>(
|
||||
operation: (...args: TArgs) => Promise<TResult>
|
||||
) =>
|
||||
async (...args: TArgs): Promise<TResult> => {
|
||||
setOperationError(undefined);
|
||||
try {
|
||||
return await operation(...args);
|
||||
} catch (caughtError) {
|
||||
setOperationError(toError(caughtError));
|
||||
throw caughtError;
|
||||
}
|
||||
};
|
||||
const selectedProjectStillExists = projects?.some(
|
||||
(project) => project.id === (selectedProjectId as unknown as string)
|
||||
);
|
||||
@@ -120,6 +205,14 @@ export const useSliceOne = () => {
|
||||
workListRef,
|
||||
activeProjectId ? { projectId: activeProjectId } : "skip"
|
||||
);
|
||||
const gitConnections = useQuery(
|
||||
listGitConnectionsRef,
|
||||
organization.organizationId ? {} : "skip"
|
||||
);
|
||||
const projectGitConnection = useQuery(
|
||||
projectGitConnectionRef,
|
||||
activeProjectId ? { projectId: activeProjectId } : "skip"
|
||||
);
|
||||
const requestDefinitionMutation = useMutation(requestDefinitionRef);
|
||||
const saveDefinitionMutation = useMutation(saveDefinitionRef);
|
||||
const approveDefinitionMutation = useMutation(approveDefinitionRef);
|
||||
@@ -128,6 +221,11 @@ export const useSliceOne = () => {
|
||||
const startSimulationMutation = useMutation(startSimulationRef);
|
||||
const cancelSimulationMutation = useMutation(cancelSimulationRef);
|
||||
const retrySimulationMutation = useMutation(retrySimulationRef);
|
||||
const startExecutionMutation = useMutation(startExecutionRef);
|
||||
const cancelExecutionMutation = useMutation(cancelExecutionRef);
|
||||
const attachGitConnectionMutation = useMutation(attachGitConnectionRef);
|
||||
const connectGiteaAction = useAction(connectGiteaRef);
|
||||
const connectGithubAction = useAction(connectGithubRef);
|
||||
const selectedProject = useMemo(
|
||||
() =>
|
||||
projects?.find(
|
||||
@@ -180,20 +278,54 @@ export const useSliceOne = () => {
|
||||
| "permanent-failure"
|
||||
| "cancelled",
|
||||
sliceId?: string
|
||||
) => startSimulationMutation({ scenario, sliceId, workId });
|
||||
) =>
|
||||
captureOperationError(() =>
|
||||
startSimulationMutation({ scenario, sliceId, workId })
|
||||
)();
|
||||
const cancelSimulation = (runId: Id<"workRuns">) =>
|
||||
cancelSimulationMutation({ runId });
|
||||
captureOperationError(() => cancelSimulationMutation({ runId }))();
|
||||
const retrySimulation = (runId: Id<"workRuns">) =>
|
||||
retrySimulationMutation({ runId });
|
||||
captureOperationError(() => retrySimulationMutation({ runId }))();
|
||||
const startExecution = (workId: Id<"works">, sliceId?: string) =>
|
||||
captureOperationError(() => startExecutionMutation({ sliceId, workId }))();
|
||||
const cancelExecution = (runId: Id<"workRuns">) =>
|
||||
captureOperationError(() => cancelExecutionMutation({ runId }))();
|
||||
const attachConnection = async (connectionId: Id<"gitConnections">) => {
|
||||
if (!activeProjectId) {
|
||||
throw new Error("Select a project first");
|
||||
}
|
||||
await attachGitConnectionMutation({
|
||||
connectionId,
|
||||
projectId: activeProjectId,
|
||||
});
|
||||
};
|
||||
const connectGitea = captureOperationError(
|
||||
async (input: { serverUrl: string; token: string; username?: string }) => {
|
||||
const result = await connectGiteaAction(input);
|
||||
await attachConnection(result.connectionId);
|
||||
}
|
||||
);
|
||||
const connectLinkedGithub = captureOperationError(async () => {
|
||||
const result = await connectGithubAction({});
|
||||
await attachConnection(result.connectionId);
|
||||
});
|
||||
|
||||
return {
|
||||
agent,
|
||||
approveDefinition,
|
||||
approveDesign,
|
||||
authorizeGithub,
|
||||
cancelExecution,
|
||||
cancelSimulation,
|
||||
clearOperationError: () => setOperationError(undefined),
|
||||
connectGitea,
|
||||
connectLinkedGithub,
|
||||
connectRepository,
|
||||
error,
|
||||
gitConnections,
|
||||
operationError,
|
||||
pending,
|
||||
projectGitConnection,
|
||||
projects,
|
||||
repository,
|
||||
requestDefinition,
|
||||
@@ -203,6 +335,7 @@ export const useSliceOne = () => {
|
||||
selectProject,
|
||||
selectedProject,
|
||||
setRepository,
|
||||
startExecution,
|
||||
startSimulation,
|
||||
works,
|
||||
} as const;
|
||||
|
||||
@@ -7,6 +7,9 @@ import { defineConfig } from "vite-plus";
|
||||
export default defineConfig({
|
||||
envDir: path.resolve(import.meta.dirname, "../.."),
|
||||
plugins: [tailwindcss(), reactRouter()],
|
||||
ssr: {
|
||||
noExternal: true,
|
||||
},
|
||||
resolve: {
|
||||
dedupe: ["convex", "react", "react-dom"],
|
||||
tsconfigPaths: true,
|
||||
|
||||
@@ -25,14 +25,7 @@ CONVEX_INSTANCE_NAME=zopu-production
|
||||
CONVEX_INSTANCE_SECRET=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Self-hosted Git / Gitea — REQUIRED for issue lifecycle
|
||||
# The agent daemon clones repos and creates PRs through Gitea.
|
||||
# ---------------------------------------------------------------------------
|
||||
GITEA_URL=https://git.openputer.com
|
||||
GITEA_TOKEN=replace-with-gitea-api-token
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Model gateway — REQUIRED
|
||||
# 2. Model gateway — REQUIRED
|
||||
# All model calls route through this OpenAI-compatible endpoint.
|
||||
# ---------------------------------------------------------------------------
|
||||
AGENT_MODEL_PROVIDER=cheaptricks
|
||||
@@ -44,24 +37,25 @@ AGENT_MODEL_CONTEXT_WINDOW=262000
|
||||
AGENT_MODEL_MAX_TOKENS=131072
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. AgentOS / RivetKit — OPTIONAL (defaults shown)
|
||||
# registry.start() in the daemon boots an in-process RivetKit engine
|
||||
# (envoy mode) backed by a native Rust sidecar. createClient() connects
|
||||
# back to RIVET_ENDPOINT. No separate Rivet Engine process is required
|
||||
# for single-node operation. Leave RIVET_ENDPOINT unset to use the
|
||||
# library default (http://localhost:6420).
|
||||
# 3. AgentOS / Rivet Engine — REQUIRED for the execution runner
|
||||
# The runner creates isolated worktrees from ZOPU_SOURCE_REPOSITORY and
|
||||
# connects to AgentOS through the public engine endpoint.
|
||||
# ---------------------------------------------------------------------------
|
||||
#RIVET_ENDPOINT=http://localhost:6420
|
||||
|
||||
RIVET_ENDPOINT=https://default:@rivet.example.com
|
||||
RIVET_PUBLIC_ENDPOINT=https://default@rivet.example.com
|
||||
RIVET_ENVOY_VERSION=1
|
||||
RIVET_WORKSPACE_TOKEN=replace-with-a-long-random-workspace-token
|
||||
ZOPU_SOURCE_REPOSITORY=/opt/zopu-source
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Zopu agent service (Flue)
|
||||
# 4. Zopu agent service (Flue)
|
||||
# FLUE_DB_TOKEN authenticates the Flue persistence adapter.
|
||||
# zopu-agent.service pins the Flue Node server to port 3583.
|
||||
# ---------------------------------------------------------------------------
|
||||
FLUE_DB_TOKEN=replace-with-long-random-token
|
||||
AGENT_BACKEND_URL=https://zopu-agent.example.com
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Daemon identity
|
||||
# 5. Daemon identity
|
||||
# ---------------------------------------------------------------------------
|
||||
DAEMON_ID=zopu-dedicated
|
||||
DAEMON_NAME=Zopu-Dedicated-Server
|
||||
|
||||
16
deploy/zopu-runtime/runner/Dockerfile
Normal file
16
deploy/zopu-runtime/runner/Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
||||
FROM oven/bun:1.3.14 AS bun
|
||||
|
||||
FROM node:24-bookworm-slim
|
||||
|
||||
COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates g++ git make python3 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
CMD ["bun", "packages/agents/src/runner.ts"]
|
||||
29
deploy/zopu-runtime/runner/docker-compose.yml
Normal file
29
deploy/zopu-runtime/runner/docker-compose.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
services:
|
||||
zopu-agentos-runner:
|
||||
build:
|
||||
context: ../../..
|
||||
dockerfile: deploy/zopu-runtime/runner/Dockerfile
|
||||
environment:
|
||||
AGENT_MODEL_API: ${AGENT_MODEL_API}
|
||||
AGENT_MODEL_API_KEY: ${AGENT_MODEL_API_KEY}
|
||||
AGENT_MODEL_BASE_URL: ${AGENT_MODEL_BASE_URL}
|
||||
AGENT_MODEL_CONTEXT_WINDOW: ${AGENT_MODEL_CONTEXT_WINDOW}
|
||||
AGENT_MODEL_MAX_TOKENS: ${AGENT_MODEL_MAX_TOKENS}
|
||||
AGENT_MODEL_NAME: ${AGENT_MODEL_NAME}
|
||||
AGENT_MODEL_PROVIDER: ${AGENT_MODEL_PROVIDER}
|
||||
CONVEX_URL: ${CONVEX_URL}
|
||||
DAEMON_ID: zopu-agentos-runner
|
||||
FLUE_DB_TOKEN: ${FLUE_DB_TOKEN}
|
||||
RIVET_ENDPOINT: ${RIVET_ENDPOINT}
|
||||
RIVET_PUBLIC_ENDPOINT: ${RIVET_PUBLIC_ENDPOINT}
|
||||
RIVET_ENVOY_VERSION: ${RIVET_ENVOY_VERSION}
|
||||
RIVET_WORKSPACE_TOKEN: ${RIVET_WORKSPACE_TOKEN}
|
||||
RIVET_POOL: default
|
||||
ZOPU_SOURCE_REPOSITORY: /opt/zopu-source
|
||||
volumes:
|
||||
- ../..:/opt/zopu-source
|
||||
- zopu-agentos-workspaces:/var/lib/zopu/workspaces
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
zopu-agentos-workspaces:
|
||||
221
docs/TECH.md
221
docs/TECH.md
@@ -18,29 +18,28 @@ Convex application backend
|
||||
├── normalized product data
|
||||
├── conversation turn queue
|
||||
└── reactive client projections
|
||||
│ service-authenticated dispatch
|
||||
│ durable Workflow steps + service-authenticated dispatch
|
||||
▼
|
||||
FLUE orchestration service
|
||||
├── model calls
|
||||
├── typed tools
|
||||
└── canonical Flue persistence in Convex
|
||||
│ later execution commands
|
||||
Private agent backend
|
||||
├── FLUE product agents and typed tools
|
||||
├── AgentOS execution environments
|
||||
├── Codex implementation harness
|
||||
└── canonical events/results returned to Convex
|
||||
│ optional attached full sandbox
|
||||
▼
|
||||
Rivet Engine + AgentOS (post-Slice 1)
|
||||
└── sandboxes, harnesses, and durable execution
|
||||
Cube/E2B-compatible runtime (later)
|
||||
```
|
||||
|
||||
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.
|
||||
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 |
|
||||
|---|---|
|
||||
| --- | --- |
|
||||
| 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 |
|
||||
| Convex Workflow | durable sequencing, retries, cancellation, scheduling, and completion callbacks |
|
||||
| Agent backend | private programmable agents and execution adapters |
|
||||
| Rivet Engine + runners | placement, routing, sleep/wake, and execution ownership for AgentOS workspaces |
|
||||
| Harness | bounded coding/tool loop |
|
||||
| Sandbox/runtime | filesystem, processes, network, isolation |
|
||||
| Git | source revision history |
|
||||
@@ -63,11 +62,7 @@ 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.
|
||||
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
|
||||
|
||||
@@ -106,93 +101,93 @@ Avoid package proliferation in v0; logical boundaries may begin as folders.
|
||||
Minimal durable model:
|
||||
|
||||
```ts
|
||||
type Id = string
|
||||
type Id = string;
|
||||
|
||||
interface Message {
|
||||
id: Id
|
||||
projectId: Id
|
||||
content: string
|
||||
createdAt: number
|
||||
id: Id;
|
||||
projectId: Id;
|
||||
content: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
interface Signal {
|
||||
id: Id
|
||||
projectId: Id
|
||||
sourceType: string
|
||||
sourceId: string
|
||||
sourcePayloadRef?: string
|
||||
summary: string
|
||||
fingerprint: string
|
||||
status: "candidate" | "accepted" | "dismissed"
|
||||
id: Id;
|
||||
projectId: Id;
|
||||
sourceType: string;
|
||||
sourceId: string;
|
||||
sourcePayloadRef?: string;
|
||||
summary: string;
|
||||
fingerprint: string;
|
||||
status: "candidate" | "accepted" | "dismissed";
|
||||
}
|
||||
|
||||
interface Work {
|
||||
id: Id
|
||||
projectId: Id
|
||||
title: string
|
||||
objective: string
|
||||
risk: "low" | "medium" | "high"
|
||||
status: WorkStatus
|
||||
definitionVersion?: number
|
||||
designVersion?: number
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
id: Id;
|
||||
projectId: Id;
|
||||
title: string;
|
||||
objective: string;
|
||||
risk: "low" | "medium" | "high";
|
||||
status: WorkStatus;
|
||||
definitionVersion?: number;
|
||||
designVersion?: number;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
interface Step {
|
||||
id: Id
|
||||
workId: Id
|
||||
sliceId?: Id
|
||||
kind: "design" | "implement" | "verify" | "integrate" | "publish" | "observe"
|
||||
objective: string
|
||||
dependsOn: readonly Id[]
|
||||
status: StepStatus
|
||||
id: Id;
|
||||
workId: Id;
|
||||
sliceId?: Id;
|
||||
kind: "design" | "implement" | "verify" | "integrate" | "publish" | "observe";
|
||||
objective: string;
|
||||
dependsOn: readonly Id[];
|
||||
status: StepStatus;
|
||||
}
|
||||
|
||||
interface Run {
|
||||
id: Id
|
||||
workId: Id
|
||||
stepId: Id
|
||||
kitVersion: string
|
||||
status: RunStatus
|
||||
id: Id;
|
||||
workId: Id;
|
||||
stepId: Id;
|
||||
kitVersion: string;
|
||||
status: RunStatus;
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
id: Id
|
||||
runId: Id
|
||||
number: number
|
||||
harness: string
|
||||
runtime: string
|
||||
sourceRevision: string
|
||||
status: AttemptStatus
|
||||
startedAt?: number
|
||||
endedAt?: number
|
||||
id: Id;
|
||||
runId: Id;
|
||||
number: number;
|
||||
harness: string;
|
||||
runtime: string;
|
||||
sourceRevision: string;
|
||||
status: AttemptStatus;
|
||||
startedAt?: number;
|
||||
endedAt?: number;
|
||||
}
|
||||
|
||||
interface Artifact {
|
||||
id: Id
|
||||
workId: Id
|
||||
stepId?: Id
|
||||
runId?: Id
|
||||
attemptId?: Id
|
||||
type: string
|
||||
uri?: string
|
||||
contentHash?: string
|
||||
sourceRevision?: string
|
||||
environmentId?: string
|
||||
metadata: unknown
|
||||
id: Id;
|
||||
workId: Id;
|
||||
stepId?: Id;
|
||||
runId?: Id;
|
||||
attemptId?: Id;
|
||||
type: string;
|
||||
uri?: string;
|
||||
contentHash?: string;
|
||||
sourceRevision?: string;
|
||||
environmentId?: string;
|
||||
metadata: unknown;
|
||||
}
|
||||
|
||||
interface Question {
|
||||
id: Id
|
||||
workId: Id
|
||||
stepId?: Id
|
||||
attemptId?: Id
|
||||
prompt: string
|
||||
recommendation?: string
|
||||
alternatives: readonly string[]
|
||||
status: "open" | "answered" | "withdrawn"
|
||||
answer?: string
|
||||
id: Id;
|
||||
workId: Id;
|
||||
stepId?: Id;
|
||||
attemptId?: Id;
|
||||
prompt: string;
|
||||
recommendation?: string;
|
||||
alternatives: readonly string[];
|
||||
status: "open" | "answered" | "withdrawn";
|
||||
answer?: string;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -337,35 +332,49 @@ Keep domain/application code provider-neutral.
|
||||
|
||||
```ts
|
||||
interface HarnessRuntime {
|
||||
open(input: OpenHarnessInput): Effect.Effect<HarnessSession, HarnessError>
|
||||
prompt(id: string, content: string): Effect.Effect<void, HarnessError>
|
||||
events(id: string): Stream.Stream<HarnessEvent, HarnessError>
|
||||
approve(input: PermissionDecision): Effect.Effect<void, HarnessError>
|
||||
abort(id: string): Effect.Effect<void, HarnessError>
|
||||
close(id: string): Effect.Effect<void, HarnessError>
|
||||
open(input: OpenHarnessInput): Effect.Effect<HarnessSession, HarnessError>;
|
||||
prompt(id: string, content: string): Effect.Effect<void, HarnessError>;
|
||||
events(id: string): Stream.Stream<HarnessEvent, HarnessError>;
|
||||
approve(input: PermissionDecision): Effect.Effect<void, HarnessError>;
|
||||
abort(id: string): Effect.Effect<void, HarnessError>;
|
||||
close(id: string): Effect.Effect<void, HarnessError>;
|
||||
}
|
||||
|
||||
interface SandboxRuntime {
|
||||
create(spec: SandboxSpec): Effect.Effect<SandboxLease, SandboxError>
|
||||
exec(lease: SandboxLease, cmd: Command): Effect.Effect<CommandResult, SandboxError>
|
||||
readFile(lease: SandboxLease, path: string): Effect.Effect<Uint8Array, SandboxError>
|
||||
writeFile(lease: SandboxLease, path: string, body: Uint8Array): Effect.Effect<void, SandboxError>
|
||||
pause(lease: SandboxLease): Effect.Effect<void, SandboxError>
|
||||
resume(id: string): Effect.Effect<SandboxLease, SandboxError>
|
||||
terminate(lease: SandboxLease): Effect.Effect<void, SandboxError>
|
||||
create(spec: SandboxSpec): Effect.Effect<SandboxLease, SandboxError>;
|
||||
exec(
|
||||
lease: SandboxLease,
|
||||
cmd: Command
|
||||
): Effect.Effect<CommandResult, SandboxError>;
|
||||
readFile(
|
||||
lease: SandboxLease,
|
||||
path: string
|
||||
): Effect.Effect<Uint8Array, SandboxError>;
|
||||
writeFile(
|
||||
lease: SandboxLease,
|
||||
path: string,
|
||||
body: Uint8Array
|
||||
): Effect.Effect<void, SandboxError>;
|
||||
pause(lease: SandboxLease): Effect.Effect<void, SandboxError>;
|
||||
resume(id: string): Effect.Effect<SandboxLease, SandboxError>;
|
||||
terminate(lease: SandboxLease): Effect.Effect<void, SandboxError>;
|
||||
}
|
||||
|
||||
interface SourceControl {
|
||||
prepareWorktree(input: WorktreeInput): Effect.Effect<Worktree, GitError>
|
||||
diff(worktree: Worktree): Effect.Effect<DiffArtifact, GitError>
|
||||
commit(input: CommitInput): Effect.Effect<CommitArtifact, GitError>
|
||||
push(input: PushInput): Effect.Effect<BranchArtifact, GitError>
|
||||
createPullRequest(input: PullRequestInput): Effect.Effect<PullRequestArtifact, GitError>
|
||||
prepareWorktree(input: WorktreeInput): Effect.Effect<Worktree, GitError>;
|
||||
diff(worktree: Worktree): Effect.Effect<DiffArtifact, GitError>;
|
||||
commit(input: CommitInput): Effect.Effect<CommitArtifact, GitError>;
|
||||
push(input: PushInput): Effect.Effect<BranchArtifact, GitError>;
|
||||
createPullRequest(
|
||||
input: PullRequestInput
|
||||
): Effect.Effect<PullRequestArtifact, GitError>;
|
||||
}
|
||||
|
||||
interface VerificationRuntime {
|
||||
execute(plan: VerificationPlan, env: EnvironmentRef):
|
||||
Effect.Effect<VerificationResult, VerificationError>
|
||||
execute(
|
||||
plan: VerificationPlan,
|
||||
env: EnvironmentRef
|
||||
): Effect.Effect<VerificationResult, VerificationError>;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -420,6 +429,10 @@ Zopu owns Work, branches, worktrees, budgets, approvals, artifacts, and completi
|
||||
|
||||
## 10. Runtime strategy
|
||||
|
||||
### Convex orchestration
|
||||
|
||||
Slice 5 uses the Convex Workflow component as the durable product orchestration layer. Workflow steps call private agent-backend actions, while all user-visible state, events, artifacts, idempotency keys, and cancellation remain canonical in Convex.
|
||||
|
||||
### CubeSandbox
|
||||
|
||||
Best for full Linux execution:
|
||||
@@ -443,7 +456,7 @@ Best for:
|
||||
- actor-adjacent orchestration;
|
||||
- context/files/networking that fit runtime limits.
|
||||
|
||||
Use an attached full sandbox when native/heavy tooling is needed.
|
||||
Slice 5 starts here with one Codex-backed AgentOS actor and one authenticated repository checkout per project. Convex Workflow owns product orchestration; Rivet Engine coordinates placement while a normal runner executes the actor. Use an attached full sandbox through the E2B-compatible boundary when native/heavy tooling is needed.
|
||||
|
||||
### Persistent project machine
|
||||
|
||||
|
||||
@@ -211,16 +211,18 @@ Zopu implements one approved slice in an isolated repository environment and str
|
||||
Initial adapter choice:
|
||||
|
||||
```text
|
||||
SandboxRuntime = CubeSandboxLive
|
||||
HarnessRuntime = OmpHarnessLive (or one chosen harness)
|
||||
SandboxRuntime = AgentOsSandboxLive
|
||||
HarnessRuntime = CodexHarnessLive
|
||||
Durable orchestration = Convex Workflow
|
||||
```
|
||||
|
||||
Flow:
|
||||
|
||||
```text
|
||||
prepare worktree
|
||||
→ create sandbox
|
||||
→ clone/mount repo
|
||||
load the project's authenticated Git connection
|
||||
→ start durable Convex workflow
|
||||
→ create AgentOS execution environment
|
||||
→ clone the single configured repo
|
||||
→ inject context
|
||||
→ run one slice
|
||||
→ normalize events
|
||||
@@ -230,14 +232,15 @@ prepare worktree
|
||||
|
||||
Security:
|
||||
|
||||
- scoped Git/model tokens;
|
||||
- GitHub OAuth or self-hosted Gitea PAT, scoped to one project;
|
||||
- scoped Git/model tokens passed only to private execution;
|
||||
- isolated HOME/worktree;
|
||||
- one mutating attempt per worktree;
|
||||
- timeout/cancel cleanup.
|
||||
|
||||
### Frontend
|
||||
|
||||
Current activity, changed files, artifact links, expandable raw logs.
|
||||
Project selector/settings, Git connection status, current activity, changed files, artifact links, expandable raw logs, cancel/retry, and manual Git delivery controls.
|
||||
|
||||
### Acceptance
|
||||
|
||||
@@ -247,6 +250,8 @@ Current activity, changed files, artifact links, expandable raw logs.
|
||||
- provider failure becomes classified attempt outcome;
|
||||
- exact base/candidate revision recorded.
|
||||
|
||||
Rivet Engine coordinates AgentOS actor placement through a normal runner, but does not own product orchestration; Convex Workflow remains canonical for the Run lifecycle. Cube/Kubernetes sandbox support remains behind `SandboxRuntime` and can be mounted through AgentOS incrementally.
|
||||
|
||||
---
|
||||
|
||||
## Slice 6 — Independent verification and repair
|
||||
@@ -490,4 +495,4 @@ browser-tester integration-coordinator
|
||||
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11 → 12
|
||||
```
|
||||
|
||||
Parallel engineering is allowed *within* a slice after contracts land, but product release order remains sequential.
|
||||
Parallel engineering is allowed _within_ a slice after contracts land, but product release order remains sequential.
|
||||
|
||||
56
package.json
56
package.json
@@ -1,53 +1,6 @@
|
||||
{
|
||||
"name": "code",
|
||||
"private": true,
|
||||
"workspaces": {
|
||||
"packages": [
|
||||
"apps/web",
|
||||
"packages/agents",
|
||||
"packages/auth",
|
||||
"packages/backend",
|
||||
"packages/config",
|
||||
"packages/env",
|
||||
"packages/primitives",
|
||||
"packages/ui"
|
||||
],
|
||||
"catalog": {
|
||||
"@rivet-dev/agentos": "^0.2.7",
|
||||
"@rivet-dev/agentos-core": "^0.2.10",
|
||||
"@effect/platform-bun": "4.0.0-beta.99",
|
||||
"dotenv": "^17.4.2",
|
||||
"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",
|
||||
"@convex-dev/better-auth": "^0.12.5",
|
||||
"@tanstack/react-form": "^1.33.0",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"@better-auth/expo": "1.6.15",
|
||||
"effect": "4.0.0-beta.99",
|
||||
"typescript": "^6",
|
||||
"@types/bun": "latest",
|
||||
"heroui-native": "^1.0.5",
|
||||
"vite": "^7.3.6",
|
||||
"vitest": "^4.1.10",
|
||||
"convex-test": "^0.0.54",
|
||||
"react-native": "0.86.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/node": "^22.13.14",
|
||||
"hono": "^4.8.3",
|
||||
"valibot": "^1.4.2",
|
||||
"streamdown": "2.5.0",
|
||||
"@tailwindcss/postcss": "^4.3.2",
|
||||
"@tailwindcss/vite": "^4.3.2"
|
||||
}
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vp run -r dev",
|
||||
@@ -65,8 +18,8 @@
|
||||
"dev:server": "vp run --filter @code/backend dev",
|
||||
"dev:setup": "vp run --filter @code/backend dev:setup",
|
||||
"build:agents": "vp run --filter @code/agents build",
|
||||
"docs:update": "bun run scripts/update-docs.ts",
|
||||
"subtree": "bun run scripts/subtree.ts",
|
||||
"docs:update": "node scripts/update-docs.ts",
|
||||
"subtree": "node scripts/subtree.ts",
|
||||
"fix": "ultracite fix",
|
||||
"slice1": "vp run -r dev",
|
||||
"dev:zopu": "vp run --filter @code/agents dev",
|
||||
@@ -92,8 +45,5 @@
|
||||
"vite-plus": "0.2.2",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"overrides": {
|
||||
"vite": "npm:@voidzero-dev/vite-plus-core@0.2.2"
|
||||
},
|
||||
"packageManager": "bun@1.3.14"
|
||||
"packageManager": "pnpm@11.17.0"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineConfig } from '@flue/cli/config';
|
||||
import { defineConfig } from "@flue/cli/config";
|
||||
|
||||
export default defineConfig({
|
||||
target: 'node',
|
||||
target: "node",
|
||||
});
|
||||
|
||||
@@ -4,26 +4,37 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "bun --env-file=../../.env flue build",
|
||||
"build": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs build",
|
||||
"start": "node --env-file=../../.env dist/server.mjs",
|
||||
"check-types": "tsc --noEmit",
|
||||
"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:work-planner": "bun --env-file=../../.env flue run work-planner"
|
||||
"dev": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs dev",
|
||||
"dev:tailscale": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs dev",
|
||||
"run": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run",
|
||||
"runner": "node --env-file=../../.env src/runner.ts",
|
||||
"run:zopu": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run zopu",
|
||||
"run:work-planner": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run work-planner"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentos-software/git": "0.3.3",
|
||||
"@code/backend": "workspace:*",
|
||||
"@code/env": "workspace:*",
|
||||
"@code/primitives": "workspace:*",
|
||||
"@flue/runtime": "latest",
|
||||
"@rivet-dev/agentos": "0.2.14",
|
||||
"@rivet-dev/agentos-core": "0.2.14",
|
||||
"convex": "catalog:",
|
||||
"hono": "catalog:",
|
||||
"rivetkit": "2.3.9",
|
||||
"valibot": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@code/config": "workspace:*",
|
||||
"@flue/cli": "latest",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18 <23 || >=23.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +1,9 @@
|
||||
import { parseAgentEnv } from "@code/env/agent";
|
||||
import { defineAgent } from "@flue/runtime";
|
||||
|
||||
import INSTRUCTIONS from "../prompts/zopu-instructions.md" with { type: "markdown" };
|
||||
import { createSliceOneTools } from "../tools/slice-one";
|
||||
|
||||
const INSTRUCTIONS = `You are Zopu for product Slice 1 and the Work planning handoff.
|
||||
|
||||
## Your role
|
||||
|
||||
The application stores each user message as exact evidence before you process it. You may interpret that evidence, but never supply, rewrite, or invent source text.
|
||||
|
||||
## Work routing loop
|
||||
|
||||
When a user sends a message, follow this decision flow:
|
||||
|
||||
1. **Assess actionability.** Does the message contain a concrete problem, request, blocker, opportunity, or decision that warrants a work unit? Greetings, questions about the system, casual conversation, and exploration do NOT create work. If the message is casual conversation, respond naturally and do nothing else.
|
||||
|
||||
Direct questions, casual conversation, and image-reading requests must be answered immediately without calling any tools.
|
||||
|
||||
2. **Identify project context.** Call list_projects. If there is one project, use it. If there are several and the request is ambiguous, ask one focused question.
|
||||
|
||||
3. **Create a Signal (only when actionable).** When the message is actionable:
|
||||
a. Call list_signal_evidence to see the exact admitted user messages.
|
||||
b. Select the message IDs that compose the problem statement.
|
||||
c. Call create_signal with a structured problem statement (title, summary, desiredOutcome, constraints). The problem statement must faithfully represent the user's own intent. Do not invent scope they did not mention.
|
||||
d. Include the projectId when the project is known.
|
||||
|
||||
4. **Route the Signal.** After creating the Signal:
|
||||
a. Call list_proposed_work for the project.
|
||||
b. If the Signal clearly describes the same desired outcome as existing Work, call attach_signal_to_work.
|
||||
c. Otherwise call create_work_from_signal.
|
||||
e. If genuinely uncertain whether to attach or create, ask one focused question.
|
||||
|
||||
5. **Explain the outcome.** Tell the user clearly what happened:
|
||||
- "Captured [Signal title] and linked it to [Work title]."
|
||||
- "Captured [Signal title] and proposed [Work title]."
|
||||
- Keep the response brief; the product renders the durable Work card separately.
|
||||
|
||||
## Rules
|
||||
|
||||
- Never supply or rewrite the raw source message text. The control plane copies it server-side.
|
||||
- You receive and can see images attached to the current user message. This model supports image input. Never claim images are unavailable, omitted, or unsupported. If a message has attached images, inspect them before responding.
|
||||
- Never create Work from casual chat.
|
||||
- Ask at most one focused clarification when genuinely ambiguous.
|
||||
- Preserve project and organization scope at all times.
|
||||
- Repeated delivery of the same message must not create duplicate Signals or attachments. The backend is idempotent.
|
||||
- Never claim you created a Signal until the tool call returns successfully.
|
||||
- Do not start implementation, planning, sandboxes, Git, verification, or delivery. Those are explicitly outside Slice 1.
|
||||
- After creating proposed Work, the system may invoke the private work-planner. Never claim that a Definition, Design, approval, or implementation exists unless Convex reports it.
|
||||
- Proposed Work is the only Work status you directly create.`;
|
||||
|
||||
export {
|
||||
convexAgentRoute as attachments,
|
||||
convexAgentRoute as route,
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { parseAgentEnv } from "@code/env/agent";
|
||||
import { WorkAttemptExecutionError } from "@code/primitives/execution-runtime";
|
||||
import { registerProvider } from "@flue/runtime";
|
||||
import type { Fetchable } from "@flue/runtime/routing";
|
||||
import { flue } from "@flue/runtime/routing";
|
||||
import { Hono } from "hono";
|
||||
|
||||
import {
|
||||
cancelAgentOsAttempt,
|
||||
executeAgentOsAttempt,
|
||||
runtimeRegistry,
|
||||
} from "./runtime/agent-os";
|
||||
|
||||
const agentEnv = parseAgentEnv(process.env);
|
||||
|
||||
@@ -24,5 +32,54 @@ registerProvider(agentEnv.AGENT_MODEL_PROVIDER, {
|
||||
},
|
||||
});
|
||||
|
||||
// flue() returns a complete Hono app; the Fetchable contract accepts it.
|
||||
export default flue() satisfies Fetchable;
|
||||
const app = new Hono();
|
||||
|
||||
app.post("/internal/work-attempts/execute", async (context) => {
|
||||
if (
|
||||
context.req.header("authorization") !== `Bearer ${agentEnv.FLUE_DB_TOKEN}`
|
||||
) {
|
||||
return context.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
try {
|
||||
return context.json(await executeAgentOsAttempt(await context.req.json()));
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof WorkAttemptExecutionError
|
||||
? error
|
||||
: new WorkAttemptExecutionError({
|
||||
message:
|
||||
error instanceof Error ? error.message : "Execution failed",
|
||||
reason: "HarnessFailed",
|
||||
retryable: false,
|
||||
});
|
||||
return context.json(
|
||||
{
|
||||
error: {
|
||||
message: failure.message,
|
||||
reason: failure.reason,
|
||||
retryable: failure.retryable,
|
||||
},
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/internal/work-attempts/:workspaceKey/cancel", async (context) => {
|
||||
if (
|
||||
context.req.header("authorization") !== `Bearer ${agentEnv.FLUE_DB_TOKEN}`
|
||||
) {
|
||||
return context.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
const body = (await context.req.json()) as { attemptId?: unknown };
|
||||
if (typeof body.attemptId !== "string" || body.attemptId.length === 0) {
|
||||
return context.json({ error: "attemptId is required" }, 400);
|
||||
}
|
||||
await cancelAgentOsAttempt(context.req.param("workspaceKey"), body.attemptId);
|
||||
return context.json({ cancelled: true });
|
||||
});
|
||||
|
||||
app.all("/api/rivet/*", (context) => runtimeRegistry.handler(context.req.raw));
|
||||
app.route("/", flue());
|
||||
|
||||
export default app satisfies Fetchable;
|
||||
|
||||
45
packages/agents/src/prompts/zopu-instructions.md
Normal file
45
packages/agents/src/prompts/zopu-instructions.md
Normal file
@@ -0,0 +1,45 @@
|
||||
You are Zopu for product Slice 1 and the Work planning handoff.
|
||||
|
||||
## Your role
|
||||
|
||||
The application stores each user message as exact evidence before you process it. You may interpret that evidence, but never supply, rewrite, or invent source text.
|
||||
|
||||
## Work routing loop
|
||||
|
||||
When a user sends a message, follow this decision flow:
|
||||
|
||||
1. **Assess actionability.** Does the message contain a concrete problem, request, blocker, opportunity, or decision that warrants a work unit? Greetings, questions about the system, casual conversation, and exploration do NOT create work. If the message is casual conversation, respond naturally and do nothing else.
|
||||
|
||||
Direct questions, casual conversation, and image-reading requests must be answered immediately without calling any tools.
|
||||
|
||||
2. **Identify project context.** Call list_projects. If there is one project, use it. If there are several and the request is ambiguous, ask one focused question.
|
||||
|
||||
3. **Create a Signal (only when actionable).** When the message is actionable:
|
||||
a. Call list_signal_evidence to see the exact admitted user messages.
|
||||
b. Select the message IDs that compose the problem statement.
|
||||
c. Call create_signal with a structured problem statement (title, summary, desiredOutcome, constraints). The problem statement must faithfully represent the user's own intent. Do not invent scope they did not mention.
|
||||
d. Include the projectId when the project is known.
|
||||
|
||||
4. **Route the Signal.** After creating the Signal:
|
||||
a. Call list_proposed_work for the project.
|
||||
b. If the Signal clearly describes the same desired outcome as existing Work, call attach_signal_to_work.
|
||||
c. Otherwise call create_work_from_signal.
|
||||
e. If genuinely uncertain whether to attach or create, ask one focused question.
|
||||
|
||||
5. **Explain the outcome.** Tell the user clearly what happened:
|
||||
- "Captured [Signal title] and linked it to [Work title]."
|
||||
- "Captured [Signal title] and proposed [Work title]."
|
||||
- Keep the response brief; the product renders the durable Work card separately.
|
||||
|
||||
## Rules
|
||||
|
||||
- Never supply or rewrite the raw source message text. The control plane copies it server-side.
|
||||
- You receive and can see images attached to the current user message. This model supports image input. Never claim images are unavailable, omitted, or unsupported. If a message has attached images, inspect them before responding.
|
||||
- Never create Work from casual chat.
|
||||
- Ask at most one focused clarification when genuinely ambiguous.
|
||||
- Preserve project and organization scope at all times.
|
||||
- Repeated delivery of the same message must not create duplicate Signals or attachments. The backend is idempotent.
|
||||
- Never claim you created a Signal until the tool call returns successfully.
|
||||
- Do not start implementation, planning, sandboxes, Git, verification, or delivery. Those are explicitly outside Slice 1.
|
||||
- After creating proposed Work, the system may invoke the private work-planner. Never claim that a Definition, Design, approval, or implementation exists unless Convex reports it.
|
||||
- Proposed Work is the only Work status you directly create.
|
||||
3
packages/agents/src/runner.ts
Normal file
3
packages/agents/src/runner.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { runtimeRegistry } from "./runtime/agent-os";
|
||||
|
||||
await runtimeRegistry.startAndWait();
|
||||
255
packages/agents/src/runtime/agent-os.ts
Normal file
255
packages/agents/src/runtime/agent-os.ts
Normal file
@@ -0,0 +1,255 @@
|
||||
import { parseAgentEnv } from "@code/env/agent";
|
||||
import {
|
||||
makePiAgentOsConfig,
|
||||
makePiHomeFiles,
|
||||
decodeWorkAttemptExecutionInput,
|
||||
WorkAttemptExecutionError,
|
||||
piSessionEnv,
|
||||
} from "@code/primitives";
|
||||
import type {
|
||||
ExecutionEvent,
|
||||
WorkAttemptExecutionResult,
|
||||
} from "@code/primitives";
|
||||
import { agentOS, setup } from "@rivet-dev/agentos";
|
||||
import { createHostDirBackend } from "@rivet-dev/agentos-core";
|
||||
import { createClient } from "@rivet-dev/agentos/client";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { HostRepositoryWorkspace } from "./host-repository";
|
||||
|
||||
const piConfig = makePiAgentOsConfig();
|
||||
const workspace = agentOS<undefined, { token: string }>({
|
||||
onBeforeConnect: (_context, params) => {
|
||||
if (params.token !== process.env.RIVET_WORKSPACE_TOKEN) {
|
||||
throw new Error("Unauthorized workspace connection");
|
||||
}
|
||||
},
|
||||
options: {
|
||||
actionTimeout: 10 * 60 * 1000,
|
||||
},
|
||||
permissions: piConfig.permissions,
|
||||
software: piConfig.software,
|
||||
});
|
||||
|
||||
export const runtimeRegistry = setup({ use: { workspace } });
|
||||
|
||||
const event = (
|
||||
sequence: number,
|
||||
kind: ExecutionEvent["kind"],
|
||||
message: string,
|
||||
metadata: Record<string, string> = {}
|
||||
): ExecutionEvent => ({
|
||||
kind,
|
||||
message,
|
||||
metadata,
|
||||
occurredAt: Date.now(),
|
||||
sequence,
|
||||
});
|
||||
|
||||
const executionError = (
|
||||
message: string,
|
||||
reason: WorkAttemptExecutionError["reason"],
|
||||
retryable: boolean
|
||||
) => new WorkAttemptExecutionError({ message, reason, retryable });
|
||||
|
||||
const classifyRuntimeFailure = (cause: unknown): WorkAttemptExecutionError => {
|
||||
if (cause instanceof WorkAttemptExecutionError) {
|
||||
return cause;
|
||||
}
|
||||
const message = cause instanceof Error ? cause.message : "Execution failed";
|
||||
if (/auth|credential|401|403/iu.test(message)) {
|
||||
return executionError(message, "Authentication", false);
|
||||
}
|
||||
if (/clone|checkout|repository|git /iu.test(message)) {
|
||||
return executionError(message, "RepositoryFailed", false);
|
||||
}
|
||||
if (/timeout|timed out/iu.test(message)) {
|
||||
return executionError(message, "Timeout", true);
|
||||
}
|
||||
if (/connect|network|unavailable|502|503|504/iu.test(message)) {
|
||||
return executionError(message, "ProviderUnavailable", true);
|
||||
}
|
||||
return executionError(message, "HarnessFailed", false);
|
||||
};
|
||||
|
||||
export const executeAgentOsAttempt = async (
|
||||
rawInput: unknown
|
||||
): Promise<WorkAttemptExecutionResult> => {
|
||||
try {
|
||||
const input = await Effect.runPromise(
|
||||
decodeWorkAttemptExecutionInput(rawInput)
|
||||
);
|
||||
const env = parseAgentEnv(process.env);
|
||||
const client = createClient<typeof runtimeRegistry>({
|
||||
disableMetadataLookup: true,
|
||||
endpoint: env.RIVET_PUBLIC_ENDPOINT ?? env.RIVET_ENDPOINT,
|
||||
});
|
||||
const vm = client.workspace.getOrCreate([input.workspaceKey], {
|
||||
params: { token: env.RIVET_WORKSPACE_TOKEN },
|
||||
});
|
||||
const events: ExecutionEvent[] = [
|
||||
event(0, "runtime.preparing", "AgentOS workspace selected", {
|
||||
workspaceKey: input.workspaceKey,
|
||||
}),
|
||||
];
|
||||
const hostRepository = new HostRepositoryWorkspace();
|
||||
const prepared = await hostRepository.prepare({
|
||||
attemptId: input.attemptId,
|
||||
piHomeFiles: makePiHomeFiles({
|
||||
api: env.AGENT_MODEL_API,
|
||||
apiKeyEnvironmentVariable: "AGENT_MODEL_API_KEY",
|
||||
baseUrl: env.AGENT_MODEL_BASE_URL,
|
||||
contextWindow: env.AGENT_MODEL_CONTEXT_WINDOW,
|
||||
maxTokens: env.AGENT_MODEL_MAX_TOKENS,
|
||||
model: env.AGENT_MODEL_NAME,
|
||||
provider: env.AGENT_MODEL_PROVIDER,
|
||||
}),
|
||||
});
|
||||
events.push(
|
||||
event(
|
||||
1,
|
||||
"runtime.preparing",
|
||||
prepared.created
|
||||
? "Isolated Zopu worktree created on the execution host"
|
||||
: "Isolated Zopu worktree recreated"
|
||||
)
|
||||
);
|
||||
const mounts = [
|
||||
{
|
||||
hostPath: prepared.checkoutPath,
|
||||
path: "/workspace/repository",
|
||||
readOnly: false,
|
||||
},
|
||||
{
|
||||
hostPath: prepared.sourceRepositoryPath,
|
||||
path: prepared.sourceRepositoryPath,
|
||||
readOnly: false,
|
||||
},
|
||||
{
|
||||
hostPath: prepared.piHomePath,
|
||||
path: "/home/zopu",
|
||||
readOnly: false,
|
||||
},
|
||||
{
|
||||
hostPath: prepared.toolsPath,
|
||||
path: "/opt/zopu-tools",
|
||||
readOnly: true,
|
||||
},
|
||||
] as const;
|
||||
const mountNext = async (index: number): Promise<void> => {
|
||||
const mount = mounts[index];
|
||||
if (!mount) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await vm.mountFs({
|
||||
path: mount.path,
|
||||
plugin: createHostDirBackend({
|
||||
hostPath: mount.hostPath,
|
||||
readOnly: mount.readOnly,
|
||||
}),
|
||||
readOnly: mount.readOnly,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw executionError(
|
||||
`Failed to mount ${mount.hostPath} at ${mount.path}: ${message}`,
|
||||
"HarnessFailed",
|
||||
false
|
||||
);
|
||||
}
|
||||
await mountNext(index + 1);
|
||||
};
|
||||
await mountNext(0);
|
||||
const { baseRevision } = prepared;
|
||||
events.push(
|
||||
event(2, "repository.ready", "Repository checkout is ready", {
|
||||
baseRevision,
|
||||
})
|
||||
);
|
||||
|
||||
const sessionId = `pi-${input.attemptId}`;
|
||||
await vm.openSession({
|
||||
additionalDirectories: [`${prepared.sourceRepositoryPath}/.git`],
|
||||
additionalInstructions:
|
||||
"Work only inside /workspace/repository. This is an isolated worktree of the Zopu product repository. Read AGENTS.md and the relevant product specifications before changing code. Never reveal credentials, modify the read-only base checkout, push, or open a pull request. Implement the requested change and run focused verification.",
|
||||
agent: "pi",
|
||||
cwd: "/workspace/repository",
|
||||
env: piSessionEnv(env.AGENT_MODEL_API_KEY),
|
||||
permissionPolicy: "allow_all",
|
||||
sessionId,
|
||||
});
|
||||
events.push(
|
||||
event(3, "harness.started", "Pi implementation session started")
|
||||
);
|
||||
const promptResult = await vm.prompt({
|
||||
content: [{ text: input.prompt, type: "text" }],
|
||||
idempotencyKey: input.attemptId,
|
||||
sessionId,
|
||||
});
|
||||
if (promptResult.stopReason !== "end_turn") {
|
||||
const reason =
|
||||
promptResult.stopReason === "cancelled" ? "Cancelled" : "HarnessFailed";
|
||||
throw executionError(
|
||||
`Pi stopped with ${promptResult.stopReason}`,
|
||||
reason,
|
||||
promptResult.stopReason === "max_tokens" ||
|
||||
promptResult.stopReason === "max_turn_requests"
|
||||
);
|
||||
}
|
||||
events.push(
|
||||
event(4, "harness.progress", "Pi implementation turn completed", {
|
||||
stopReason: promptResult.stopReason,
|
||||
})
|
||||
);
|
||||
|
||||
const collected = await HostRepositoryWorkspace.collect({
|
||||
attemptId: input.attemptId,
|
||||
baseRevision,
|
||||
checkoutPath: prepared.checkoutPath,
|
||||
});
|
||||
const { candidateRevision, changedFiles, diff } = collected;
|
||||
events.push(
|
||||
event(
|
||||
5,
|
||||
"repository.changed",
|
||||
`${changedFiles.length} changed file(s) collected`,
|
||||
{
|
||||
candidateRevision,
|
||||
}
|
||||
),
|
||||
event(6, "runtime.completed", "AgentOS execution completed")
|
||||
);
|
||||
|
||||
return {
|
||||
baseRevision,
|
||||
candidateRevision,
|
||||
changedFiles,
|
||||
diff,
|
||||
environmentId: input.workspaceKey,
|
||||
events,
|
||||
summary:
|
||||
changedFiles.length > 0
|
||||
? `Pi changed ${changedFiles.length} file(s)`
|
||||
: "Pi completed without repository changes",
|
||||
};
|
||||
} catch (error) {
|
||||
throw classifyRuntimeFailure(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const cancelAgentOsAttempt = async (
|
||||
workspaceKey: string,
|
||||
attemptId: string
|
||||
) => {
|
||||
const env = parseAgentEnv(process.env);
|
||||
const client = createClient<typeof runtimeRegistry>({
|
||||
disableMetadataLookup: true,
|
||||
endpoint: env.RIVET_PUBLIC_ENDPOINT ?? env.RIVET_ENDPOINT,
|
||||
});
|
||||
await client.workspace
|
||||
.getOrCreate([workspaceKey], {
|
||||
params: { token: env.RIVET_WORKSPACE_TOKEN },
|
||||
})
|
||||
.cancelPrompt({ sessionId: `pi-${attemptId}` });
|
||||
};
|
||||
274
packages/agents/src/runtime/host-repository.ts
Normal file
274
packages/agents/src/runtime/host-repository.ts
Normal file
@@ -0,0 +1,274 @@
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
copyFile,
|
||||
mkdir,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import type { PiHomeFiles } from "@code/primitives";
|
||||
|
||||
interface PrepareRepositoryInput {
|
||||
attemptId: string;
|
||||
piHomeFiles: PiHomeFiles;
|
||||
}
|
||||
|
||||
interface PreparedRepository {
|
||||
baseRevision: string;
|
||||
checkoutPath: string;
|
||||
created: boolean;
|
||||
piHomePath: string;
|
||||
sourceRepositoryPath: string;
|
||||
toolsPath: string;
|
||||
}
|
||||
|
||||
interface CollectRepositoryInput {
|
||||
attemptId: string;
|
||||
baseRevision: string;
|
||||
checkoutPath: string;
|
||||
}
|
||||
|
||||
interface CollectedRepository {
|
||||
candidateRevision: string;
|
||||
changedFiles: string[];
|
||||
diff: string;
|
||||
}
|
||||
|
||||
interface ProcessResult {
|
||||
exitCode: number;
|
||||
stderr: string;
|
||||
stdout: string;
|
||||
}
|
||||
|
||||
const requireSuccess = (result: ProcessResult, operation: string): string => {
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`${operation} failed: ${result.stderr || result.stdout}`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
};
|
||||
|
||||
const changedFilePath = (line: string): string => {
|
||||
const filePath = line.slice(3).trim();
|
||||
const renameSeparator = " -> ";
|
||||
const renameIndex = filePath.lastIndexOf(renameSeparator);
|
||||
return renameIndex === -1
|
||||
? filePath
|
||||
: filePath.slice(renameIndex + renameSeparator.length);
|
||||
};
|
||||
|
||||
const runProcess = async (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
cwd: string,
|
||||
env: Record<string, string> = {}
|
||||
): Promise<ProcessResult> => {
|
||||
const environment = Object.fromEntries(
|
||||
Object.entries(process.env).filter(
|
||||
(entry): entry is [string, string] => entry[1] !== undefined
|
||||
)
|
||||
);
|
||||
const child = spawn(command, args, {
|
||||
cwd,
|
||||
env: { ...environment, ...env },
|
||||
});
|
||||
const stderr: Uint8Array[] = [];
|
||||
const stdout: Uint8Array[] = [];
|
||||
child.stderr.on("data", (chunk: Uint8Array) => stderr.push(chunk));
|
||||
child.stdout.on("data", (chunk: Uint8Array) => stdout.push(chunk));
|
||||
const [exitCode] = await once(child, "close");
|
||||
return {
|
||||
exitCode: typeof exitCode === "number" ? exitCode : 1,
|
||||
stderr: Buffer.concat(stderr).toString(),
|
||||
stdout: Buffer.concat(stdout).toString(),
|
||||
};
|
||||
};
|
||||
|
||||
const runGit = (cwd: string, args: readonly string[]) =>
|
||||
runProcess("git", args, cwd);
|
||||
|
||||
const pathExists = async (target: string): Promise<boolean> => {
|
||||
try {
|
||||
await access(target);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export class HostRepositoryWorkspace {
|
||||
readonly #root: string;
|
||||
readonly #sourceRepositoryPath: string;
|
||||
readonly #installDependencies: boolean;
|
||||
|
||||
constructor(
|
||||
root = process.env.AGENT_WORKSPACE_ROOT ?? "/var/lib/zopu/workspaces",
|
||||
sourceRepositoryPath = process.env.ZOPU_SOURCE_REPOSITORY ??
|
||||
"/opt/zopu-source",
|
||||
installDependencies = true
|
||||
) {
|
||||
this.#root = root;
|
||||
this.#sourceRepositoryPath = sourceRepositoryPath;
|
||||
this.#installDependencies = installDependencies;
|
||||
}
|
||||
|
||||
async prepare(input: PrepareRepositoryInput): Promise<PreparedRepository> {
|
||||
if (!(await pathExists(path.join(this.#sourceRepositoryPath, ".git")))) {
|
||||
throw new Error(
|
||||
`Fixed Zopu source repository is unavailable at ${this.#sourceRepositoryPath}`
|
||||
);
|
||||
}
|
||||
|
||||
const identity = createHash("sha256")
|
||||
.update(input.attemptId)
|
||||
.digest("hex")
|
||||
.slice(0, 24);
|
||||
const workspacePath = path.join(this.#root, identity);
|
||||
const checkoutPath = path.join(workspacePath, "repository");
|
||||
const toolsPath = path.join(workspacePath, "tools");
|
||||
const piHomePath = path.join(workspacePath, "home");
|
||||
const branch = `zopu/attempt-${identity}`;
|
||||
const created = !(await pathExists(path.join(checkoutPath, ".git")));
|
||||
|
||||
await mkdir(workspacePath, { recursive: true });
|
||||
if (!created) {
|
||||
requireSuccess(
|
||||
await runGit(this.#sourceRepositoryPath, [
|
||||
"worktree",
|
||||
"remove",
|
||||
"--force",
|
||||
checkoutPath,
|
||||
]),
|
||||
"Existing worktree removal"
|
||||
);
|
||||
}
|
||||
await rm(checkoutPath, { force: true, recursive: true });
|
||||
requireSuccess(
|
||||
await runGit(this.#sourceRepositoryPath, [
|
||||
"worktree",
|
||||
"add",
|
||||
"-B",
|
||||
branch,
|
||||
checkoutPath,
|
||||
"HEAD",
|
||||
]),
|
||||
"Zopu worktree creation"
|
||||
);
|
||||
|
||||
const bunExecutable =
|
||||
process.env.BUN_EXECUTABLE ??
|
||||
execFileSync("which", ["bun"], { encoding: "utf-8" }).trim();
|
||||
|
||||
const sourceEnvPath = path.join(this.#sourceRepositoryPath, ".env");
|
||||
if (await pathExists(sourceEnvPath)) {
|
||||
await copyFile(sourceEnvPath, path.join(checkoutPath, ".env"));
|
||||
}
|
||||
if (this.#installDependencies) {
|
||||
requireSuccess(
|
||||
await runProcess(
|
||||
bunExecutable,
|
||||
["install", "--frozen-lockfile"],
|
||||
checkoutPath,
|
||||
{ CI: "1" }
|
||||
),
|
||||
"Workspace dependency installation"
|
||||
);
|
||||
}
|
||||
|
||||
const toolsBinPath = path.join(toolsPath, "bin");
|
||||
await mkdir(toolsBinPath, { recursive: true });
|
||||
const bunPath = path.join(toolsBinPath, "bun");
|
||||
await copyFile(bunExecutable, bunPath);
|
||||
await chmod(bunPath, 0o755);
|
||||
|
||||
const piAgentPath = path.join(piHomePath, ".pi", "agent");
|
||||
await mkdir(piAgentPath, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(piAgentPath, "models.json"),
|
||||
input.piHomeFiles.models
|
||||
);
|
||||
await writeFile(
|
||||
path.join(piAgentPath, "settings.json"),
|
||||
input.piHomeFiles.settings
|
||||
);
|
||||
|
||||
return {
|
||||
baseRevision: requireSuccess(
|
||||
await runGit(checkoutPath, ["rev-parse", "HEAD"]),
|
||||
"Base revision lookup"
|
||||
),
|
||||
checkoutPath,
|
||||
created,
|
||||
piHomePath,
|
||||
sourceRepositoryPath: this.#sourceRepositoryPath,
|
||||
toolsPath,
|
||||
};
|
||||
}
|
||||
|
||||
static async collect(
|
||||
input: CollectRepositoryInput
|
||||
): Promise<CollectedRepository> {
|
||||
const status = requireSuccess(
|
||||
await runGit(input.checkoutPath, ["status", "--porcelain"]),
|
||||
"Changed file lookup"
|
||||
);
|
||||
let diff = "";
|
||||
const changedFiles = status
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map(changedFilePath);
|
||||
let candidateRevision = input.baseRevision;
|
||||
|
||||
if (changedFiles.length > 0) {
|
||||
requireSuccess(
|
||||
await runGit(input.checkoutPath, ["add", "-A"]),
|
||||
"Candidate staging"
|
||||
);
|
||||
diff = requireSuccess(
|
||||
await runGit(input.checkoutPath, [
|
||||
"diff",
|
||||
"--binary",
|
||||
"--cached",
|
||||
"--no-ext-diff",
|
||||
input.baseRevision,
|
||||
]),
|
||||
"Diff collection"
|
||||
);
|
||||
const tree = requireSuccess(
|
||||
await runGit(input.checkoutPath, ["write-tree"]),
|
||||
"Candidate tree creation"
|
||||
);
|
||||
candidateRevision = requireSuccess(
|
||||
await runProcess(
|
||||
"git",
|
||||
[
|
||||
"commit-tree",
|
||||
tree,
|
||||
"-p",
|
||||
input.baseRevision,
|
||||
"-m",
|
||||
`Zopu candidate for ${input.attemptId}`,
|
||||
],
|
||||
input.checkoutPath,
|
||||
{
|
||||
GIT_AUTHOR_EMAIL: "agent@zopu.dev",
|
||||
GIT_AUTHOR_NAME: "Zopu Agent",
|
||||
GIT_COMMITTER_EMAIL: "agent@zopu.dev",
|
||||
GIT_COMMITTER_NAME: "Zopu Agent",
|
||||
}
|
||||
),
|
||||
"Candidate revision creation"
|
||||
);
|
||||
requireSuccess(
|
||||
await runGit(input.checkoutPath, ["reset"]),
|
||||
"Candidate index reset"
|
||||
);
|
||||
}
|
||||
|
||||
return { candidateRevision, changedFiles, diff };
|
||||
}
|
||||
}
|
||||
17
packages/backend/convex/_generated/api.d.ts
vendored
17
packages/backend/convex/_generated/api.d.ts
vendored
@@ -11,7 +11,10 @@
|
||||
import type * as auth from "../auth.js";
|
||||
import type * as authz from "../authz.js";
|
||||
import type * as conversationMessages from "../conversationMessages.js";
|
||||
import type * as crons from "../crons.js";
|
||||
import type * as fluePersistence from "../fluePersistence.js";
|
||||
import type * as gitConnectionData from "../gitConnectionData.js";
|
||||
import type * as gitConnections from "../gitConnections.js";
|
||||
import type * as healthCheck from "../healthCheck.js";
|
||||
import type * as http from "../http.js";
|
||||
import type * as organizations from "../organizations.js";
|
||||
@@ -19,6 +22,11 @@ import type * as privateData from "../privateData.js";
|
||||
import type * as projects from "../projects.js";
|
||||
import type * as publicGit from "../publicGit.js";
|
||||
import type * as signalRouting from "../signalRouting.js";
|
||||
import type * as workArtifacts from "../workArtifacts.js";
|
||||
import type * as workExecution from "../workExecution.js";
|
||||
import type * as workExecutionAgent from "../workExecutionAgent.js";
|
||||
import type * as workExecutionWorkflow from "../workExecutionWorkflow.js";
|
||||
import type * as workPlanning from "../workPlanning.js";
|
||||
import type * as works from "../works.js";
|
||||
|
||||
import type {
|
||||
@@ -31,7 +39,10 @@ declare const fullApi: ApiFromModules<{
|
||||
auth: typeof auth;
|
||||
authz: typeof authz;
|
||||
conversationMessages: typeof conversationMessages;
|
||||
crons: typeof crons;
|
||||
fluePersistence: typeof fluePersistence;
|
||||
gitConnectionData: typeof gitConnectionData;
|
||||
gitConnections: typeof gitConnections;
|
||||
healthCheck: typeof healthCheck;
|
||||
http: typeof http;
|
||||
organizations: typeof organizations;
|
||||
@@ -39,6 +50,11 @@ declare const fullApi: ApiFromModules<{
|
||||
projects: typeof projects;
|
||||
publicGit: typeof publicGit;
|
||||
signalRouting: typeof signalRouting;
|
||||
workArtifacts: typeof workArtifacts;
|
||||
workExecution: typeof workExecution;
|
||||
workExecutionAgent: typeof workExecutionAgent;
|
||||
workExecutionWorkflow: typeof workExecutionWorkflow;
|
||||
workPlanning: typeof workPlanning;
|
||||
works: typeof works;
|
||||
}>;
|
||||
|
||||
@@ -70,4 +86,5 @@ export declare const internal: FilterApi<
|
||||
|
||||
export declare const components: {
|
||||
betterAuth: import("@convex-dev/better-auth/_generated/component.js").ComponentApi<"betterAuth">;
|
||||
workflow: import("@convex-dev/workflow/_generated/component.js").ComponentApi<"workflow">;
|
||||
};
|
||||
|
||||
@@ -25,10 +25,14 @@ import type { DataModel } from "./dataModel.js";
|
||||
* Typesafe environment variables declared in `convex.config.ts`.
|
||||
*/
|
||||
type Env = {
|
||||
readonly AGENT_BACKEND_URL: string | undefined;
|
||||
readonly FLUE_DB_TOKEN: string;
|
||||
readonly FLUE_URL: string | undefined;
|
||||
readonly GITEA_TOKEN: string | undefined;
|
||||
readonly GITEA_URL: string | undefined;
|
||||
readonly GITHUB_CLIENT_ID: string | undefined;
|
||||
readonly GITHUB_CLIENT_SECRET: string | undefined;
|
||||
readonly GIT_CREDENTIAL_ENCRYPTION_KEY: string | undefined;
|
||||
readonly NATIVE_APP_URL: string | undefined;
|
||||
readonly SITE_URL: string;
|
||||
};
|
||||
|
||||
@@ -30,6 +30,15 @@ const createAuth = (ctx: GenericCtx<DataModel>) =>
|
||||
jwksRotateOnTokenGenerationError: true,
|
||||
}),
|
||||
],
|
||||
socialProviders:
|
||||
env.GITHUB_CLIENT_ID && env.GITHUB_CLIENT_SECRET
|
||||
? {
|
||||
github: {
|
||||
clientId: env.GITHUB_CLIENT_ID,
|
||||
clientSecret: env.GITHUB_CLIENT_SECRET,
|
||||
},
|
||||
}
|
||||
: {},
|
||||
trustedOrigins: [siteUrl, nativeAppUrl, "exp://"],
|
||||
});
|
||||
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import betterAuth from "@convex-dev/better-auth/convex.config";
|
||||
import workflow from "@convex-dev/workflow/convex.config.js";
|
||||
import { defineApp } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
const app = defineApp({
|
||||
env: {
|
||||
AGENT_BACKEND_URL: v.optional(v.string()),
|
||||
FLUE_DB_TOKEN: v.string(),
|
||||
FLUE_URL: v.optional(v.string()),
|
||||
GITEA_TOKEN: v.optional(v.string()),
|
||||
GITEA_URL: v.optional(v.string()),
|
||||
GITHUB_CLIENT_ID: v.optional(v.string()),
|
||||
GITHUB_CLIENT_SECRET: v.optional(v.string()),
|
||||
GIT_CREDENTIAL_ENCRYPTION_KEY: v.optional(v.string()),
|
||||
NATIVE_APP_URL: v.optional(v.string()),
|
||||
SITE_URL: v.string(),
|
||||
},
|
||||
});
|
||||
app.use(betterAuth);
|
||||
app.use(workflow);
|
||||
|
||||
export default app;
|
||||
|
||||
143
packages/backend/convex/gitConnectionData.ts
Normal file
143
packages/backend/convex/gitConnectionData.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
import { ConvexError, v } from "convex/values";
|
||||
|
||||
import { internalMutation, mutation, query } from "./_generated/server";
|
||||
import { requireCurrentOrganization, requireProjectMember } from "./authz";
|
||||
|
||||
// Provider ("forge") that owns a repository host. A project's source must be
|
||||
// served by the same forge whose credentials are attached, so a Gitea token is
|
||||
// never offered to GitHub and vice versa. Unknown hosts return null, leaving
|
||||
// the caller free to attach without a forge constraint.
|
||||
export const forgeForHost = (host: string): "github" | "gitea" | null => {
|
||||
const normalized = host.toLowerCase();
|
||||
if (normalized === "github.com" || normalized.endsWith(".githost.com")) {
|
||||
return "github";
|
||||
}
|
||||
if (normalized === "git.openputer.com") {
|
||||
return "gitea";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const persist = internalMutation({
|
||||
args: {
|
||||
credentialCiphertext: v.string(),
|
||||
credentialIv: v.string(),
|
||||
credentialKind: v.union(v.literal("oauth"), v.literal("token")),
|
||||
provider: v.union(v.literal("github"), v.literal("gitea")),
|
||||
serverUrl: v.string(),
|
||||
userId: v.string(),
|
||||
username: v.optional(v.string()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const organization = await ctx.db
|
||||
.query("organizations")
|
||||
.withIndex("by_createdBy_and_kind", (q) =>
|
||||
q.eq("createdBy", args.userId).eq("kind", "personal")
|
||||
)
|
||||
.unique();
|
||||
if (!organization) {
|
||||
throw new ConvexError("Organization not found");
|
||||
}
|
||||
const existing = await ctx.db
|
||||
.query("gitConnections")
|
||||
.withIndex("by_organizationId_and_provider_and_serverUrl", (q) =>
|
||||
q
|
||||
.eq("organizationId", organization._id)
|
||||
.eq("provider", args.provider)
|
||||
.eq("serverUrl", args.serverUrl)
|
||||
)
|
||||
.unique();
|
||||
const timestamp = Date.now();
|
||||
if (existing) {
|
||||
await ctx.db.patch(existing._id, {
|
||||
credentialCiphertext: args.credentialCiphertext,
|
||||
credentialIv: args.credentialIv,
|
||||
credentialKind: args.credentialKind,
|
||||
updatedAt: timestamp,
|
||||
username: args.username,
|
||||
});
|
||||
return existing._id;
|
||||
}
|
||||
return await ctx.db.insert("gitConnections", {
|
||||
connectedAt: timestamp,
|
||||
credentialCiphertext: args.credentialCiphertext,
|
||||
credentialIv: args.credentialIv,
|
||||
credentialKind: args.credentialKind,
|
||||
organizationId: organization._id,
|
||||
provider: args.provider,
|
||||
serverUrl: args.serverUrl,
|
||||
updatedAt: timestamp,
|
||||
username: args.username,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const list = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const { organizationId } = await requireCurrentOrganization(ctx);
|
||||
const connections = await ctx.db
|
||||
.query("gitConnections")
|
||||
.withIndex("by_organizationId", (q) =>
|
||||
q.eq("organizationId", organizationId)
|
||||
)
|
||||
.collect();
|
||||
return connections.map((connection) => ({
|
||||
connectedAt: connection.connectedAt,
|
||||
credentialKind: connection.credentialKind,
|
||||
id: String(connection._id),
|
||||
provider: connection.provider,
|
||||
serverUrl: connection.serverUrl,
|
||||
username: connection.username,
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
export const getForProject = query({
|
||||
args: { projectId: v.id("projects") },
|
||||
handler: async (ctx, args) => {
|
||||
await requireProjectMember(ctx, args.projectId);
|
||||
const project = await ctx.db.get(args.projectId);
|
||||
const connection = project?.gitConnectionId
|
||||
? await ctx.db.get(project.gitConnectionId)
|
||||
: null;
|
||||
return connection
|
||||
? {
|
||||
connectedAt: connection.connectedAt,
|
||||
credentialKind: connection.credentialKind,
|
||||
id: String(connection._id),
|
||||
provider: connection.provider,
|
||||
serverUrl: connection.serverUrl,
|
||||
username: connection.username,
|
||||
}
|
||||
: null;
|
||||
},
|
||||
});
|
||||
|
||||
export const attachToProject = mutation({
|
||||
args: {
|
||||
connectionId: v.id("gitConnections"),
|
||||
projectId: v.id("projects"),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { organizationId } = await requireProjectMember(ctx, args.projectId);
|
||||
const connection = await ctx.db.get(args.connectionId);
|
||||
if (!connection || connection.organizationId !== organizationId) {
|
||||
throw new ConvexError("Git connection not found");
|
||||
}
|
||||
const project = await ctx.db.get(args.projectId);
|
||||
if (project) {
|
||||
const expected = forgeForHost(project.sourceHost);
|
||||
if (expected && connection.provider !== expected) {
|
||||
throw new ConvexError(
|
||||
`Git credential provider (${connection.provider}) does not match this project's forge (${expected})`
|
||||
);
|
||||
}
|
||||
}
|
||||
await ctx.db.patch(args.projectId, {
|
||||
gitConnectionId: connection._id,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
return { attached: true };
|
||||
},
|
||||
});
|
||||
124
packages/backend/convex/gitConnections.ts
Normal file
124
packages/backend/convex/gitConnections.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
"use node";
|
||||
|
||||
import { env } from "@code/env/convex";
|
||||
import { decodeGitConnectionInput } from "@code/primitives/execution-runtime";
|
||||
import { ConvexError, v } from "convex/values";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { internal } from "./_generated/api";
|
||||
import type { Id } from "./_generated/dataModel";
|
||||
import { action } from "./_generated/server";
|
||||
import { authComponent, createAuth } from "./auth";
|
||||
|
||||
const encryptionKey = async (): Promise<CryptoKey> => {
|
||||
if (!env.GIT_CREDENTIAL_ENCRYPTION_KEY) {
|
||||
throw new ConvexError("Git credential encryption is not configured");
|
||||
}
|
||||
const bytes = Buffer.from(env.GIT_CREDENTIAL_ENCRYPTION_KEY, "base64url");
|
||||
if (bytes.byteLength !== 32) {
|
||||
throw new ConvexError("Git credential encryption key must be 32 bytes");
|
||||
}
|
||||
return await crypto.subtle.importKey("raw", bytes, "AES-GCM", false, [
|
||||
"encrypt",
|
||||
"decrypt",
|
||||
]);
|
||||
};
|
||||
|
||||
const encryptCredential = async (credential: string) => {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{ iv, name: "AES-GCM" },
|
||||
await encryptionKey(),
|
||||
new TextEncoder().encode(credential)
|
||||
);
|
||||
return {
|
||||
credentialCiphertext: Buffer.from(encrypted).toString("base64url"),
|
||||
credentialIv: Buffer.from(iv).toString("base64url"),
|
||||
};
|
||||
};
|
||||
|
||||
export const decryptCredential = async (
|
||||
credentialCiphertext: string,
|
||||
credentialIv: string
|
||||
): Promise<string> => {
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{
|
||||
iv: Buffer.from(credentialIv, "base64url"),
|
||||
name: "AES-GCM",
|
||||
},
|
||||
await encryptionKey(),
|
||||
Buffer.from(credentialCiphertext, "base64url")
|
||||
);
|
||||
return new TextDecoder().decode(decrypted);
|
||||
};
|
||||
|
||||
export const connectGitea = action({
|
||||
args: {
|
||||
serverUrl: v.string(),
|
||||
token: v.string(),
|
||||
username: v.optional(v.string()),
|
||||
},
|
||||
handler: async (
|
||||
ctx,
|
||||
args
|
||||
): Promise<{ connectionId: Id<"gitConnections"> }> => {
|
||||
const userId = await ctx.auth.getUserIdentity().then((identity) => {
|
||||
if (!identity) {
|
||||
throw new ConvexError("Authentication required");
|
||||
}
|
||||
return identity.tokenIdentifier;
|
||||
});
|
||||
const connection = await Effect.runPromise(
|
||||
decodeGitConnectionInput({
|
||||
credential: args.token,
|
||||
credentialKind: "token",
|
||||
provider: "gitea",
|
||||
serverUrl: args.serverUrl,
|
||||
username: args.username,
|
||||
})
|
||||
);
|
||||
const encrypted = await encryptCredential(connection.credential);
|
||||
const connectionId = await ctx.runMutation(
|
||||
internal.gitConnectionData.persist,
|
||||
{
|
||||
...encrypted,
|
||||
credentialKind: connection.credentialKind,
|
||||
provider: connection.provider,
|
||||
serverUrl: connection.serverUrl,
|
||||
userId,
|
||||
username: connection.username,
|
||||
}
|
||||
);
|
||||
return { connectionId };
|
||||
},
|
||||
});
|
||||
|
||||
export const connectGithub = action({
|
||||
args: {},
|
||||
handler: async (ctx): Promise<{ connectionId: Id<"gitConnections"> }> => {
|
||||
const identity = await ctx.auth.getUserIdentity();
|
||||
if (!identity) {
|
||||
throw new ConvexError("Authentication required");
|
||||
}
|
||||
const { auth, headers } = await authComponent.getAuth(createAuth, ctx);
|
||||
const token = await auth.api.getAccessToken({
|
||||
body: { providerId: "github" },
|
||||
headers,
|
||||
});
|
||||
if (!token.accessToken) {
|
||||
throw new ConvexError("GitHub account is not connected");
|
||||
}
|
||||
const encrypted = await encryptCredential(token.accessToken);
|
||||
const connectionId = await ctx.runMutation(
|
||||
internal.gitConnectionData.persist,
|
||||
{
|
||||
...encrypted,
|
||||
credentialKind: "oauth",
|
||||
provider: "github",
|
||||
serverUrl: "https://github.com",
|
||||
userId: identity.tokenIdentifier,
|
||||
}
|
||||
);
|
||||
return { connectionId };
|
||||
},
|
||||
});
|
||||
@@ -44,10 +44,28 @@ export default defineSchema({
|
||||
.index("by_userId", ["userId"])
|
||||
.index("by_organizationId", ["organizationId"])
|
||||
.index("by_organizationId_and_userId", ["organizationId", "userId"]),
|
||||
gitConnections: defineTable({
|
||||
connectedAt: v.number(),
|
||||
credentialCiphertext: v.string(),
|
||||
credentialIv: v.string(),
|
||||
credentialKind: v.union(v.literal("oauth"), v.literal("token")),
|
||||
organizationId: v.id("organizations"),
|
||||
provider: v.union(v.literal("github"), v.literal("gitea")),
|
||||
serverUrl: v.string(),
|
||||
updatedAt: v.number(),
|
||||
username: v.optional(v.string()),
|
||||
})
|
||||
.index("by_organizationId", ["organizationId"])
|
||||
.index("by_organizationId_and_provider_and_serverUrl", [
|
||||
"organizationId",
|
||||
"provider",
|
||||
"serverUrl",
|
||||
]),
|
||||
projects: defineTable({
|
||||
createdAt: v.number(),
|
||||
defaultBranch: v.optional(v.string()),
|
||||
description: v.optional(v.string()),
|
||||
gitConnectionId: v.optional(v.id("gitConnections")),
|
||||
name: v.string(),
|
||||
normalizedSourceUrl: v.string(),
|
||||
organizationId: v.id("organizations"),
|
||||
@@ -314,11 +332,17 @@ export default defineSchema({
|
||||
]),
|
||||
|
||||
workRuns: defineTable({
|
||||
baseRevision: v.optional(v.string()),
|
||||
candidateRevision: v.optional(v.string()),
|
||||
createdAt: v.number(),
|
||||
designVersion: v.optional(v.number()),
|
||||
endedAt: v.optional(v.number()),
|
||||
kitId: v.string(),
|
||||
kitVersion: v.string(),
|
||||
environmentId: v.optional(v.string()),
|
||||
executionKind: v.optional(
|
||||
v.union(v.literal("simulated"), v.literal("real"))
|
||||
),
|
||||
scenario: v.union(
|
||||
v.literal("success"),
|
||||
v.literal("transient-failure-then-success"),
|
||||
@@ -337,11 +361,23 @@ export default defineSchema({
|
||||
),
|
||||
terminalClassification: v.optional(attemptClassification),
|
||||
terminalSummary: v.optional(v.string()),
|
||||
workflowId: v.optional(v.string()),
|
||||
workId: v.id("works"),
|
||||
}).index("by_work_and_createdAt", ["workId", "createdAt"]),
|
||||
|
||||
workAttempts: defineTable({
|
||||
classification: v.optional(attemptClassification),
|
||||
failureReason: v.optional(
|
||||
v.union(
|
||||
v.literal("Authentication"),
|
||||
v.literal("Cancelled"),
|
||||
v.literal("HarnessFailed"),
|
||||
v.literal("InvalidInput"),
|
||||
v.literal("ProviderUnavailable"),
|
||||
v.literal("RepositoryFailed"),
|
||||
v.literal("Timeout")
|
||||
)
|
||||
),
|
||||
endedAt: v.optional(v.number()),
|
||||
leaseExpiresAt: v.optional(v.number()),
|
||||
leaseOwner: v.optional(v.string()),
|
||||
@@ -356,6 +392,7 @@ export default defineSchema({
|
||||
),
|
||||
summary: v.optional(v.string()),
|
||||
workId: v.id("works"),
|
||||
workspaceKey: v.optional(v.string()),
|
||||
})
|
||||
.index("by_runId_and_number", ["runId", "number"])
|
||||
.index("by_status_and_leaseExpiresAt", ["status", "leaseExpiresAt"]),
|
||||
|
||||
97
packages/backend/convex/workExecutionAgent.ts
Normal file
97
packages/backend/convex/workExecutionAgent.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
"use node";
|
||||
|
||||
import { env } from "@code/env/convex";
|
||||
import {
|
||||
WorkAttemptExecutionError,
|
||||
decodeWorkAttemptExecutionFailure,
|
||||
decodeWorkAttemptExecutionResult,
|
||||
} from "@code/primitives/execution-runtime";
|
||||
import { ConvexError, v } from "convex/values";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { internal } from "./_generated/api";
|
||||
import { internalAction } from "./_generated/server";
|
||||
import { decryptCredential } from "./gitConnections";
|
||||
|
||||
const backendUrl = () => env.AGENT_BACKEND_URL ?? env.FLUE_URL;
|
||||
|
||||
export const executeAttempt = internalAction({
|
||||
args: { attemptId: v.id("workAttempts") },
|
||||
handler: async (ctx, args) => {
|
||||
const running = await ctx.runMutation(
|
||||
internal.workExecutionWorkflow.markAttemptRunning,
|
||||
args
|
||||
);
|
||||
if (!running) {
|
||||
throw new ConvexError("Attempt is no longer runnable");
|
||||
}
|
||||
const context = await ctx.runQuery(
|
||||
internal.workExecutionWorkflow.executionContext,
|
||||
args
|
||||
);
|
||||
const credential = await decryptCredential(
|
||||
context.connection.credentialCiphertext,
|
||||
context.connection.credentialIv
|
||||
);
|
||||
const response = await fetch(
|
||||
`${backendUrl()}/internal/work-attempts/execute`,
|
||||
{
|
||||
body: JSON.stringify({
|
||||
attemptId: String(context.attempt._id),
|
||||
auth: {
|
||||
credential,
|
||||
provider: context.connection.provider,
|
||||
serverUrl: context.connection.serverUrl,
|
||||
username: context.connection.username,
|
||||
},
|
||||
baseBranch: context.project.defaultBranch ?? "main",
|
||||
prompt: context.prompt,
|
||||
repositoryUrl: context.project.sourceUrl,
|
||||
runId: String(context.run._id),
|
||||
workId: String(context.work._id),
|
||||
workspaceKey: context.attempt.workspaceKey,
|
||||
}),
|
||||
headers: {
|
||||
authorization: `Bearer ${env.FLUE_DB_TOKEN}`,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
const payload = (await response.json()) as unknown;
|
||||
if (!response.ok) {
|
||||
// Decode the agent's classified failure envelope and re-throw as the
|
||||
// typed runtime error so the workflow handler maps reason/retryable to
|
||||
// a durable attempt classification. A malformed envelope falls back to
|
||||
// an InvalidInput failure (non-retryable).
|
||||
const failure = await Effect.runPromise(
|
||||
decodeWorkAttemptExecutionFailure(payload)
|
||||
);
|
||||
throw new WorkAttemptExecutionError(failure.error);
|
||||
}
|
||||
return await Effect.runPromise(decodeWorkAttemptExecutionResult(payload));
|
||||
},
|
||||
});
|
||||
|
||||
export const cancelAttempt = internalAction({
|
||||
args: {
|
||||
attemptId: v.string(),
|
||||
workspaceKey: v.string(),
|
||||
},
|
||||
handler: async (_ctx, args) => {
|
||||
// The workspace key remains the URL path segment (workspace identity),
|
||||
// while the body carries the attemptId so the runtime can target the
|
||||
// matching Pi ACP session for cancellation.
|
||||
await fetch(
|
||||
`${backendUrl()}/internal/work-attempts/${encodeURIComponent(args.workspaceKey)}/cancel`,
|
||||
{
|
||||
body: JSON.stringify({ attemptId: args.attemptId }),
|
||||
headers: {
|
||||
authorization: `Bearer ${env.FLUE_DB_TOKEN}`,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
},
|
||||
});
|
||||
381
packages/backend/convex/workExecutionWorkflow.test.ts
Normal file
381
packages/backend/convex/workExecutionWorkflow.test.ts
Normal file
@@ -0,0 +1,381 @@
|
||||
import { convexTest } from "convex-test";
|
||||
import { anyApi } from "convex/server";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import schema from "./schema";
|
||||
|
||||
const modules = import.meta.glob("./**/*.ts");
|
||||
const api = anyApi;
|
||||
|
||||
type TestContext = ReturnType<typeof convexTest>;
|
||||
|
||||
interface Seeded {
|
||||
attemptId: string;
|
||||
runId: string;
|
||||
t: TestContext;
|
||||
workId: string;
|
||||
}
|
||||
|
||||
// Seed an in-flight real attempt so each mutation under test starts from a
|
||||
// realistic running state: Work "executing", Run "running", Attempt "running".
|
||||
const seedRunningAttempt = async (
|
||||
overrides: {
|
||||
attemptStatus?: "queued" | "claimed" | "running" | "terminal";
|
||||
runStatus?: "ready" | "running" | "terminal" | "cancelled";
|
||||
} = {}
|
||||
): Promise<Seeded> => {
|
||||
const t = convexTest({ modules, schema });
|
||||
const seeded = await t.run(async (ctx) => {
|
||||
const organizationId = await ctx.db.insert("organizations", {
|
||||
createdAt: 1,
|
||||
createdBy: "user",
|
||||
kind: "personal",
|
||||
name: "Personal",
|
||||
});
|
||||
const projectId = await ctx.db.insert("projects", {
|
||||
createdAt: 1,
|
||||
name: "Zopu",
|
||||
normalizedSourceUrl: "https://github.com/puter/zopu",
|
||||
organizationId,
|
||||
repositoryPath: "puter/zopu",
|
||||
sourceHost: "github.com",
|
||||
sourceUrl: "https://github.com/puter/zopu",
|
||||
updatedAt: 1,
|
||||
});
|
||||
const workId = await ctx.db.insert("works", {
|
||||
createdAt: 1,
|
||||
objective: "Implement a real slice",
|
||||
organizationId,
|
||||
projectId,
|
||||
status: "executing",
|
||||
title: "Real execution",
|
||||
updatedAt: 1,
|
||||
});
|
||||
const sliceRowId = await ctx.db.insert("workSlices", {
|
||||
designVersion: 1,
|
||||
objective: "Change the repo",
|
||||
observableBehavior: "A diff exists",
|
||||
ordinal: 0,
|
||||
payloadJson: "{}",
|
||||
sliceId: "slice-1",
|
||||
status: "running",
|
||||
title: "Implementation",
|
||||
workId,
|
||||
});
|
||||
const runId = await ctx.db.insert("workRuns", {
|
||||
createdAt: 1,
|
||||
designVersion: 1,
|
||||
executionKind: "real",
|
||||
kitId: "coding-v0",
|
||||
kitVersion: "1",
|
||||
scenario: "success",
|
||||
sliceId: "slice-1",
|
||||
sliceRowId,
|
||||
status: overrides.runStatus ?? "running",
|
||||
workId,
|
||||
});
|
||||
const attemptId = await ctx.db.insert("workAttempts", {
|
||||
number: 1,
|
||||
runId,
|
||||
status: overrides.attemptStatus ?? "running",
|
||||
workId,
|
||||
workspaceKey: "workspace-1",
|
||||
});
|
||||
return { attemptId, runId, workId };
|
||||
});
|
||||
return { ...seeded, t };
|
||||
};
|
||||
|
||||
const successResult = {
|
||||
baseRevision: "base123",
|
||||
candidateRevision: "candidate456",
|
||||
changedFiles: ["src/index.ts"],
|
||||
diff: "+export const ready = true;",
|
||||
environmentId: "workspace-1",
|
||||
events: [
|
||||
{
|
||||
kind: "runtime.completed",
|
||||
message: "completed",
|
||||
metadata: {},
|
||||
occurredAt: 2,
|
||||
sequence: 0,
|
||||
},
|
||||
],
|
||||
summary: "Changed one file",
|
||||
};
|
||||
|
||||
describe("real work execution persistence", () => {
|
||||
test("records revisions, activity, diff, and terminal state atomically", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
result: successResult,
|
||||
});
|
||||
|
||||
const state = await t.run(async (ctx) => ({
|
||||
artifacts: await ctx.db.query("workArtifacts").collect(),
|
||||
attempt: await ctx.db.get(seeded.attemptId as any),
|
||||
run: await ctx.db.get(seeded.runId as any),
|
||||
work: await ctx.db.get(seeded.workId as any),
|
||||
}));
|
||||
expect(state.attempt?.classification).toBe("Succeeded");
|
||||
expect(state.run).toMatchObject({
|
||||
baseRevision: "base123",
|
||||
candidateRevision: "candidate456",
|
||||
terminalClassification: "Succeeded",
|
||||
});
|
||||
expect(state.work?.status).toBe("completed");
|
||||
expect(state.artifacts[0]).toMatchObject({
|
||||
kind: "diff",
|
||||
sourceRevision: "candidate456",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("classified failure mapping", () => {
|
||||
test("maps a transient runtime reason to a retryable classification", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
reason: "ProviderUnavailable",
|
||||
retryable: true,
|
||||
summary: "model provider timed out",
|
||||
});
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.classification).toBe("RetryableFailure");
|
||||
expect(attempt?.failureReason).toBe("ProviderUnavailable");
|
||||
});
|
||||
|
||||
test("queues a new attempt without terminalizing a retryable run", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
reason: "ProviderUnavailable",
|
||||
retryable: true,
|
||||
summary: "provider unavailable",
|
||||
});
|
||||
const state = await t.run(async (ctx) => ({
|
||||
attempts: await ctx.db.query("workAttempts").collect(),
|
||||
run: await ctx.db.get(seeded.runId as any),
|
||||
work: await ctx.db.get(seeded.workId as any),
|
||||
}));
|
||||
expect(state.attempts).toHaveLength(2);
|
||||
expect(state.attempts[1]).toMatchObject({
|
||||
number: 2,
|
||||
status: "queued",
|
||||
workspaceKey: "workspace-1",
|
||||
});
|
||||
expect(state.run?.status).toBe("running");
|
||||
expect(state.work?.status).toBe("executing");
|
||||
});
|
||||
test("maps an authentication reason to a permanent failure", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
reason: "Authentication",
|
||||
retryable: false,
|
||||
summary: "token rejected",
|
||||
});
|
||||
const state = await t.run(async (ctx) => ({
|
||||
attempt: await ctx.db.get(seeded.attemptId as any),
|
||||
run: await ctx.db.get(seeded.runId as any),
|
||||
work: await ctx.db.get(seeded.workId as any),
|
||||
}));
|
||||
expect(state.attempt?.classification).toBe("PermanentFailure");
|
||||
expect(state.attempt?.failureReason).toBe("Authentication");
|
||||
expect(state.run?.terminalClassification).toBe("PermanentFailure");
|
||||
expect(state.work?.status).toBe("failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancellation fencing", () => {
|
||||
test("a cancelled attempt cannot later settle success", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
// Simulate cancellation marking the attempt/run terminal as Cancelled.
|
||||
await t.run(async (ctx) => {
|
||||
await ctx.db.patch(seeded.attemptId as any, {
|
||||
classification: "Cancelled",
|
||||
endedAt: 5,
|
||||
status: "terminal",
|
||||
summary: "Execution cancelled",
|
||||
});
|
||||
await ctx.db.patch(seeded.runId as any, {
|
||||
endedAt: 5,
|
||||
status: "cancelled",
|
||||
terminalClassification: "Cancelled",
|
||||
terminalSummary: "Execution cancelled",
|
||||
});
|
||||
});
|
||||
// A late-arriving completion must be ignored.
|
||||
await t.mutation(api.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
result: successResult,
|
||||
});
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.classification).toBe("Cancelled");
|
||||
expect(attempt?.status).toBe("terminal");
|
||||
});
|
||||
|
||||
test("a late failure does not overwrite a cancelled run", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.run(async (ctx) => {
|
||||
await ctx.db.patch(seeded.attemptId as any, {
|
||||
classification: "Cancelled",
|
||||
endedAt: 5,
|
||||
status: "terminal",
|
||||
});
|
||||
await ctx.db.patch(seeded.runId as any, { status: "cancelled" });
|
||||
});
|
||||
await t.mutation(api.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
reason: "HarnessFailed",
|
||||
retryable: true,
|
||||
summary: "late failure",
|
||||
});
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.classification).toBe("Cancelled");
|
||||
});
|
||||
});
|
||||
|
||||
describe("empty-change rejection", () => {
|
||||
test("a no-op result with no changed files fails as permanent", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
result: {
|
||||
...successResult,
|
||||
changedFiles: [],
|
||||
candidateRevision: "base123",
|
||||
},
|
||||
});
|
||||
const state = await t.run(async (ctx) => ({
|
||||
attempt: await ctx.db.get(seeded.attemptId as any),
|
||||
work: await ctx.db.get(seeded.workId as any),
|
||||
}));
|
||||
expect(state.attempt?.classification).toBe("PermanentFailure");
|
||||
expect(state.attempt?.failureReason).toBe("InvalidInput");
|
||||
expect(state.work?.status).toBe("failed");
|
||||
});
|
||||
|
||||
test("identical base and candidate revisions are rejected", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
result: {
|
||||
...successResult,
|
||||
baseRevision: "same",
|
||||
candidateRevision: "same",
|
||||
},
|
||||
});
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.classification).toBe("PermanentFailure");
|
||||
});
|
||||
});
|
||||
|
||||
describe("attempt re-entry", () => {
|
||||
test("markAttemptRunning re-claims an already-running attempt", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
// First claim (already "running" from seed) must still succeed so a
|
||||
// workflow replay can re-enter the same live attempt.
|
||||
const first = await t.mutation(
|
||||
api.workExecutionWorkflow.markAttemptRunning,
|
||||
{ attemptId: seeded.attemptId }
|
||||
);
|
||||
expect(first).toBe(true);
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.status).toBe("running");
|
||||
expect(attempt?.leaseExpiresAt).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("a terminal attempt is not re-runnable", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt({
|
||||
attemptStatus: "terminal",
|
||||
});
|
||||
const result = await t.mutation(
|
||||
api.workExecutionWorkflow.markAttemptRunning,
|
||||
{ attemptId: seeded.attemptId }
|
||||
);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
test("a cancelled run cannot re-enter a queued attempt", async () => {
|
||||
const { t, ...seeded } = await seedRunningAttempt({
|
||||
attemptStatus: "queued",
|
||||
runStatus: "cancelled",
|
||||
});
|
||||
const result = await t.mutation(
|
||||
api.workExecutionWorkflow.markAttemptRunning,
|
||||
{ attemptId: seeded.attemptId }
|
||||
);
|
||||
expect(result).toBe(false);
|
||||
const attempt = await t.run((ctx) => ctx.db.get(seeded.attemptId as any));
|
||||
expect(attempt?.status).toBe("queued");
|
||||
});
|
||||
});
|
||||
|
||||
describe("forge credential validation", () => {
|
||||
const identity = { tokenIdentifier: "https://convex.test|forge-user" };
|
||||
|
||||
const seedForgableProject = async (
|
||||
provider: "github" | "gitea",
|
||||
sourceHost: string
|
||||
) => {
|
||||
const t = convexTest({ modules, schema }).withIdentity(identity);
|
||||
const ids = await t.run(async (ctx) => {
|
||||
const organizationId = await ctx.db.insert("organizations", {
|
||||
createdAt: 1,
|
||||
createdBy: identity.tokenIdentifier,
|
||||
kind: "personal",
|
||||
name: "Personal",
|
||||
});
|
||||
await ctx.db.insert("organizationMembers", {
|
||||
createdAt: 1,
|
||||
organizationId,
|
||||
role: "owner",
|
||||
userId: identity.tokenIdentifier,
|
||||
});
|
||||
const projectId = await ctx.db.insert("projects", {
|
||||
createdAt: 1,
|
||||
name: "Zopu",
|
||||
normalizedSourceUrl: `https://${sourceHost}/puter/zopu`,
|
||||
organizationId,
|
||||
repositoryPath: "puter/zopu",
|
||||
sourceHost,
|
||||
sourceUrl: `https://${sourceHost}/puter/zopu`,
|
||||
updatedAt: 1,
|
||||
});
|
||||
const connectionId = await ctx.db.insert("gitConnections", {
|
||||
connectedAt: 1,
|
||||
credentialCiphertext: "x",
|
||||
credentialIv: "y",
|
||||
credentialKind: provider === "github" ? "oauth" : "token",
|
||||
organizationId,
|
||||
provider,
|
||||
serverUrl: `https://${sourceHost}`,
|
||||
updatedAt: 1,
|
||||
username: "zopu",
|
||||
});
|
||||
return { connectionId, projectId };
|
||||
});
|
||||
return { t, ids };
|
||||
};
|
||||
|
||||
test("rejects a git connection whose provider mismatches the project forge", async () => {
|
||||
// Gitea token attached to a GitHub-hosted project.
|
||||
const { t, ids } = await seedForgableProject("gitea", "github.com");
|
||||
await expect(
|
||||
t.mutation(api.gitConnectionData.attachToProject, {
|
||||
connectionId: ids.connectionId,
|
||||
projectId: ids.projectId,
|
||||
})
|
||||
).rejects.toThrow(/does not match this project's forge/u);
|
||||
});
|
||||
|
||||
test("accepts a matching provider for the project forge", async () => {
|
||||
const { t, ids } = await seedForgableProject("github", "github.com");
|
||||
const result = await t.mutation(api.gitConnectionData.attachToProject, {
|
||||
connectionId: ids.connectionId,
|
||||
projectId: ids.projectId,
|
||||
});
|
||||
expect(result).toMatchObject({ attached: true });
|
||||
});
|
||||
});
|
||||
632
packages/backend/convex/workExecutionWorkflow.ts
Normal file
632
packages/backend/convex/workExecutionWorkflow.ts
Normal file
@@ -0,0 +1,632 @@
|
||||
import { WorkAttemptExecutionError } from "@code/primitives/execution-runtime";
|
||||
import type { WorkAttemptExecutionErrorReason } from "@code/primitives/execution-runtime";
|
||||
import { defaultCodingKitV0, resolveOutcome } from "@code/primitives/resolver";
|
||||
import type { AttemptClassification } from "@code/primitives/resolver";
|
||||
import { WorkflowManager } from "@convex-dev/workflow";
|
||||
import type { WorkflowId } from "@convex-dev/workflow";
|
||||
import { ConvexError, v } from "convex/values";
|
||||
|
||||
import { components, internal } from "./_generated/api";
|
||||
import type { Doc, Id } from "./_generated/dataModel";
|
||||
import { internalMutation, internalQuery, mutation } from "./_generated/server";
|
||||
import type { MutationCtx } from "./_generated/server";
|
||||
import { requireProjectMember } from "./authz";
|
||||
import { forgeForHost } from "./gitConnectionData";
|
||||
|
||||
export const workflow = new WorkflowManager(components.workflow);
|
||||
|
||||
// Lease window for a running real attempt. Long enough to outlast a single
|
||||
// agent turn; the workflow's own retry/lease reconciliation covers crashes.
|
||||
const LEASE_MS = 5 * 60_000;
|
||||
|
||||
// Runtime failure reason -> durable attempt classification. The Convex
|
||||
// workflow stores classifications, not provider-specific reasons, so the
|
||||
// resolver and Work lifecycle stay forge-agnostic. `retryable` from the
|
||||
// runtime is carried alongside and consulted by the kit retry policy.
|
||||
const FAILURE_REASON_CLASSIFICATION = {
|
||||
Authentication: "PermanentFailure",
|
||||
Cancelled: "Cancelled",
|
||||
HarnessFailed: "RetryableFailure",
|
||||
InvalidInput: "PermanentFailure",
|
||||
ProviderUnavailable: "RetryableFailure",
|
||||
RepositoryFailed: "PermanentFailure",
|
||||
Timeout: "RetryableFailure",
|
||||
} as const satisfies Record<
|
||||
WorkAttemptExecutionErrorReason,
|
||||
AttemptClassification
|
||||
>;
|
||||
|
||||
export const classifyFailure = (
|
||||
reason: WorkAttemptExecutionErrorReason
|
||||
): AttemptClassification => FAILURE_REASON_CLASSIFICATION[reason];
|
||||
|
||||
// Normalize an error thrown from the agent action into the durable failure
|
||||
// triple (reason/retryable/summary). WorkAttemptExecutionError is the
|
||||
// classified runtime failure; anything else is a Convex/infrastructure error
|
||||
// treated as a transient HarnessFailed so the workflow retry policy decides.
|
||||
const toExecutionFailure = (
|
||||
error: unknown
|
||||
): {
|
||||
message: string;
|
||||
reason: WorkAttemptExecutionErrorReason;
|
||||
retryable: boolean;
|
||||
} =>
|
||||
error instanceof WorkAttemptExecutionError
|
||||
? {
|
||||
message: error.message,
|
||||
reason: error.reason,
|
||||
retryable: error.retryable,
|
||||
}
|
||||
: {
|
||||
message: error instanceof Error ? error.message : "Execution failed",
|
||||
reason: "HarnessFailed",
|
||||
retryable: true,
|
||||
};
|
||||
|
||||
const failureReasonValues = v.union(
|
||||
v.literal("Authentication"),
|
||||
v.literal("Cancelled"),
|
||||
v.literal("HarnessFailed"),
|
||||
v.literal("InvalidInput"),
|
||||
v.literal("ProviderUnavailable"),
|
||||
v.literal("RepositoryFailed"),
|
||||
v.literal("Timeout")
|
||||
);
|
||||
|
||||
const resolveReadySlice = async (
|
||||
ctx: MutationCtx,
|
||||
work: Doc<"works">,
|
||||
sliceId?: string
|
||||
) => {
|
||||
if (work.designVersion === undefined) {
|
||||
throw new ConvexError("Work has no approved Design to execute");
|
||||
}
|
||||
const slices = await ctx.db
|
||||
.query("workSlices")
|
||||
.withIndex("by_workId_and_designVersion", (q) =>
|
||||
q.eq("workId", work._id).eq("designVersion", work.designVersion!)
|
||||
)
|
||||
.collect();
|
||||
const slice = sliceId
|
||||
? slices.find((candidate) => candidate.sliceId === sliceId)
|
||||
: slices
|
||||
.sort((left, right) => left.ordinal - right.ordinal)
|
||||
.find((candidate) => candidate.status === "ready");
|
||||
if (!slice || slice.status !== "ready") {
|
||||
throw new ConvexError("Only the next ready slice can be executed");
|
||||
}
|
||||
return slice;
|
||||
};
|
||||
|
||||
// Deployment prerequisite gate for real execution. Rejects before any
|
||||
// workflow/sandbox starts when the project lacks an attached, forge-matched
|
||||
// Git connection with a cloneable source URL and default branch. Returns the
|
||||
// validated connection so the caller can pass it to the agent unchanged.
|
||||
const validateProjectDeployment = async (
|
||||
ctx: MutationCtx,
|
||||
work: Doc<"works">
|
||||
): Promise<Doc<"gitConnections">> => {
|
||||
const project = await ctx.db.get(work.projectId);
|
||||
if (!project) {
|
||||
throw new ConvexError("Project not found");
|
||||
}
|
||||
if (!project.gitConnectionId) {
|
||||
throw new ConvexError("Connect Git credentials to this project first");
|
||||
}
|
||||
const connection = await ctx.db.get(project.gitConnectionId);
|
||||
if (!connection) {
|
||||
throw new ConvexError("Git connection not found");
|
||||
}
|
||||
const expected = forgeForHost(project.sourceHost);
|
||||
if (expected && connection.provider !== expected) {
|
||||
throw new ConvexError(
|
||||
`Git credential provider (${connection.provider}) does not match this project's forge (${expected})`
|
||||
);
|
||||
}
|
||||
return connection;
|
||||
};
|
||||
|
||||
export const execute = workflow
|
||||
.define({ args: { attemptId: v.id("workAttempts") } })
|
||||
.handler(async (step, args): Promise<void> => {
|
||||
try {
|
||||
const result = await step.runAction(
|
||||
internal.workExecutionAgent.executeAttempt,
|
||||
args,
|
||||
{ retry: true }
|
||||
);
|
||||
await step.runMutation(internal.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: args.attemptId,
|
||||
result: {
|
||||
...result,
|
||||
changedFiles: [...result.changedFiles],
|
||||
events: result.events.map((item) => ({
|
||||
...item,
|
||||
metadata: { ...item.metadata },
|
||||
})),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const failure = toExecutionFailure(error);
|
||||
await step.runMutation(internal.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: args.attemptId,
|
||||
reason: failure.reason,
|
||||
retryable: failure.retryable,
|
||||
summary: failure.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const startExecution = mutation({
|
||||
args: {
|
||||
sliceId: v.optional(v.string()),
|
||||
workId: v.id("works"),
|
||||
},
|
||||
handler: async (
|
||||
ctx,
|
||||
args
|
||||
): Promise<{
|
||||
attemptId: Id<"workAttempts">;
|
||||
runId: Id<"workRuns">;
|
||||
workflowId: WorkflowId;
|
||||
}> => {
|
||||
const work = await ctx.db.get(args.workId);
|
||||
if (!work) {
|
||||
throw new ConvexError("Work not found");
|
||||
}
|
||||
await requireProjectMember(ctx, work.projectId);
|
||||
if (work.status !== "ready") {
|
||||
throw new ConvexError("Work must be Ready before execution");
|
||||
}
|
||||
if (
|
||||
work.definitionApprovalVersion !== work.definitionVersion ||
|
||||
work.designApprovalVersion !== work.designVersion
|
||||
) {
|
||||
throw new ConvexError("Execution requires exact approved versions");
|
||||
}
|
||||
await validateProjectDeployment(ctx, work);
|
||||
const slice = await resolveReadySlice(ctx, work, args.sliceId);
|
||||
const createdAt = Date.now();
|
||||
const runId = await ctx.db.insert("workRuns", {
|
||||
createdAt,
|
||||
designVersion: slice.designVersion,
|
||||
executionKind: "real",
|
||||
kitId: defaultCodingKitV0.id,
|
||||
kitVersion: defaultCodingKitV0.version,
|
||||
scenario: "success",
|
||||
sliceId: slice.sliceId,
|
||||
sliceRowId: slice._id,
|
||||
status: "running",
|
||||
workId: work._id,
|
||||
});
|
||||
const workspaceKey = `work-${work._id}-run-${runId}`;
|
||||
const attemptId = await ctx.db.insert("workAttempts", {
|
||||
number: 1,
|
||||
runId,
|
||||
status: "queued",
|
||||
workId: work._id,
|
||||
workspaceKey,
|
||||
});
|
||||
const workflowId: WorkflowId = await workflow.start(
|
||||
ctx,
|
||||
internal.workExecutionWorkflow.execute,
|
||||
{ attemptId }
|
||||
);
|
||||
await ctx.db.patch(runId, { startedAt: createdAt, workflowId });
|
||||
await ctx.db.patch(slice._id, { status: "running" });
|
||||
await ctx.db.patch(work._id, { status: "executing", updatedAt: createdAt });
|
||||
await ctx.db.insert("workEvents", {
|
||||
createdAt,
|
||||
idempotencyKey: `real-run-started:${runId}`,
|
||||
kind: "run.started",
|
||||
referenceId: String(runId),
|
||||
workId: work._id,
|
||||
});
|
||||
return { attemptId, runId, workflowId };
|
||||
},
|
||||
});
|
||||
|
||||
export const executionContext = internalQuery({
|
||||
args: { attemptId: v.id("workAttempts") },
|
||||
handler: async (ctx, args) => {
|
||||
const attempt = await ctx.db.get(args.attemptId);
|
||||
if (!attempt) {
|
||||
throw new ConvexError("Attempt not found");
|
||||
}
|
||||
const run = await ctx.db.get(attempt.runId);
|
||||
const work = await ctx.db.get(attempt.workId);
|
||||
if (!run || !work || !run.sliceRowId) {
|
||||
throw new ConvexError("Execution records are incomplete");
|
||||
}
|
||||
const [slice, project] = await Promise.all([
|
||||
ctx.db.get(run.sliceRowId),
|
||||
ctx.db.get(work.projectId),
|
||||
]);
|
||||
if (!slice || !project?.gitConnectionId) {
|
||||
throw new ConvexError("Project execution configuration is incomplete");
|
||||
}
|
||||
const connection = await ctx.db.get(project.gitConnectionId);
|
||||
if (!connection) {
|
||||
throw new ConvexError("Git connection not found");
|
||||
}
|
||||
const expectedForge = forgeForHost(project.sourceHost);
|
||||
if (expectedForge && connection.provider !== expectedForge) {
|
||||
throw new ConvexError(
|
||||
`Git credential provider (${connection.provider}) does not match this project's forge (${expectedForge})`
|
||||
);
|
||||
}
|
||||
return {
|
||||
attempt,
|
||||
connection,
|
||||
project,
|
||||
prompt: [
|
||||
`Implement this approved Zopu slice: ${slice.title}`,
|
||||
`Objective: ${slice.objective}`,
|
||||
`Observable behavior: ${slice.observableBehavior}`,
|
||||
"Inspect the repository instructions first. Make focused changes and run relevant checks.",
|
||||
].join("\n\n"),
|
||||
run,
|
||||
work,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const markAttemptRunning = internalMutation({
|
||||
args: { attemptId: v.id("workAttempts") },
|
||||
handler: async (ctx, args) => {
|
||||
const attempt = await ctx.db.get(args.attemptId);
|
||||
if (!attempt || attempt.status === "terminal") {
|
||||
return false;
|
||||
}
|
||||
const run = await ctx.db.get(attempt.runId);
|
||||
if (!run || run.status !== "running") {
|
||||
return false;
|
||||
}
|
||||
await ctx.db.patch(attempt._id, {
|
||||
leaseExpiresAt: Date.now() + LEASE_MS,
|
||||
startedAt: attempt.startedAt ?? Date.now(),
|
||||
status: "running",
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const settleSliceAndWork = async (
|
||||
ctx: MutationCtx,
|
||||
run: Doc<"workRuns">,
|
||||
succeeded: boolean,
|
||||
workStatus: Doc<"works">["status"]
|
||||
) => {
|
||||
if (!run.sliceRowId) {
|
||||
return;
|
||||
}
|
||||
const slice = await ctx.db.get(run.sliceRowId);
|
||||
if (!slice) {
|
||||
return;
|
||||
}
|
||||
let sliceStatus: "blocked" | "completed" | "ready" = "ready";
|
||||
if (succeeded) {
|
||||
sliceStatus = "completed";
|
||||
} else if (workStatus === "blocked") {
|
||||
sliceStatus = "blocked";
|
||||
}
|
||||
await ctx.db.patch(slice._id, { status: sliceStatus });
|
||||
const work = await ctx.db.get(run.workId);
|
||||
if (!work) {
|
||||
return;
|
||||
}
|
||||
let status = workStatus;
|
||||
if (succeeded) {
|
||||
const slices = await ctx.db
|
||||
.query("workSlices")
|
||||
.withIndex("by_workId_and_designVersion", (q) =>
|
||||
q.eq("workId", work._id).eq("designVersion", slice.designVersion)
|
||||
)
|
||||
.collect();
|
||||
const next = slices
|
||||
.sort((left, right) => left.ordinal - right.ordinal)
|
||||
.find((candidate) => candidate.status === "planned");
|
||||
if (next) {
|
||||
await ctx.db.patch(next._id, { status: "ready" });
|
||||
status = "ready";
|
||||
}
|
||||
}
|
||||
await ctx.db.patch(work._id, { status, updatedAt: Date.now() });
|
||||
};
|
||||
|
||||
export const completeAttempt = internalMutation({
|
||||
args: {
|
||||
attemptId: v.id("workAttempts"),
|
||||
result: v.object({
|
||||
baseRevision: v.string(),
|
||||
candidateRevision: v.string(),
|
||||
changedFiles: v.array(v.string()),
|
||||
diff: v.string(),
|
||||
environmentId: v.string(),
|
||||
events: v.array(
|
||||
v.object({
|
||||
kind: v.string(),
|
||||
message: v.string(),
|
||||
metadata: v.record(v.string(), v.string()),
|
||||
occurredAt: v.number(),
|
||||
sequence: v.number(),
|
||||
})
|
||||
),
|
||||
summary: v.string(),
|
||||
}),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const attempt = await ctx.db.get(args.attemptId);
|
||||
// Cancellation fencing: a terminal or cancelled attempt/run must never
|
||||
// later settle success, even if the agent action raced to completion.
|
||||
if (!attempt || attempt.status === "terminal") {
|
||||
return;
|
||||
}
|
||||
const run = await ctx.db.get(attempt.runId);
|
||||
const work = await ctx.db.get(attempt.workId);
|
||||
if (!run || !work) {
|
||||
throw new ConvexError("Execution records not found");
|
||||
}
|
||||
if (run.status === "terminal" || run.status === "cancelled") {
|
||||
return;
|
||||
}
|
||||
// Empty-change rejection: a no-op result (no changed files, or identical
|
||||
// base/candidate revisions) is not a successful implementation. Fail it
|
||||
// as a permanent InvalidInput so the resolver does not mark Work done.
|
||||
const noOp =
|
||||
args.result.changedFiles.length === 0 ||
|
||||
args.result.baseRevision === args.result.candidateRevision;
|
||||
if (noOp) {
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification: "PermanentFailure",
|
||||
endedAt: Date.now(),
|
||||
failureReason: "InvalidInput",
|
||||
leaseExpiresAt: undefined,
|
||||
status: "terminal",
|
||||
summary: "Execution produced no repository changes",
|
||||
});
|
||||
await ctx.db.patch(run._id, {
|
||||
endedAt: Date.now(),
|
||||
status: "terminal",
|
||||
terminalClassification: "PermanentFailure",
|
||||
terminalSummary: "Execution produced no repository changes",
|
||||
});
|
||||
await settleSliceAndWork(ctx, run, false, "failed");
|
||||
return;
|
||||
}
|
||||
for (const item of args.result.events) {
|
||||
await ctx.db.insert("workAttemptEvents", {
|
||||
attemptId: attempt._id,
|
||||
kind: item.kind,
|
||||
message: item.message,
|
||||
metadataJson: JSON.stringify(item.metadata),
|
||||
occurredAt: item.occurredAt,
|
||||
sequence: item.sequence,
|
||||
});
|
||||
}
|
||||
const endedAt = Date.now();
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification: "Succeeded",
|
||||
endedAt,
|
||||
leaseExpiresAt: undefined,
|
||||
status: "terminal",
|
||||
summary: args.result.summary,
|
||||
});
|
||||
await ctx.db.patch(run._id, {
|
||||
baseRevision: args.result.baseRevision,
|
||||
candidateRevision: args.result.candidateRevision,
|
||||
endedAt,
|
||||
environmentId: args.result.environmentId,
|
||||
status: "terminal",
|
||||
terminalClassification: "Succeeded",
|
||||
terminalSummary: args.result.summary,
|
||||
});
|
||||
await ctx.db.insert("workArtifacts", {
|
||||
attemptId: attempt._id,
|
||||
createdAt: endedAt,
|
||||
designVersion: run.designVersion,
|
||||
environmentId: args.result.environmentId,
|
||||
idempotencyKey: `real-diff:${attempt._id}`,
|
||||
kind: "diff",
|
||||
metadataJson: JSON.stringify({ changedFiles: args.result.changedFiles }),
|
||||
organizationId: work.organizationId,
|
||||
producer: "agentos-pi",
|
||||
projectId: work.projectId,
|
||||
provenanceJson: JSON.stringify({
|
||||
baseRevision: args.result.baseRevision,
|
||||
}),
|
||||
runId: run._id,
|
||||
sliceId: run.sliceId,
|
||||
sourceRevision: args.result.candidateRevision,
|
||||
title: "Implementation diff",
|
||||
verificationStatus: "unverified",
|
||||
workId: work._id,
|
||||
...(args.result.diff.length > 0
|
||||
? {
|
||||
uri: `data:text/plain;charset=utf-8,${encodeURIComponent(args.result.diff.slice(0, 50_000))}`,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
await settleSliceAndWork(ctx, run, true, "completed");
|
||||
await ctx.db.insert("workEvents", {
|
||||
createdAt: endedAt,
|
||||
idempotencyKey: `real-run-completed:${run._id}`,
|
||||
kind: "run.completed",
|
||||
payloadJson: JSON.stringify({ classification: "Succeeded" }),
|
||||
referenceId: String(run._id),
|
||||
workId: work._id,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const launchAttemptWorkflow = internalMutation({
|
||||
args: { attemptId: v.id("workAttempts") },
|
||||
handler: async (ctx, args) => {
|
||||
const attempt = await ctx.db.get(args.attemptId);
|
||||
if (!attempt || attempt.status === "terminal") {
|
||||
return;
|
||||
}
|
||||
const run = await ctx.db.get(attempt.runId);
|
||||
if (!run || run.status !== "running") {
|
||||
return;
|
||||
}
|
||||
const workflowId: WorkflowId = await workflow.start(
|
||||
ctx,
|
||||
internal.workExecutionWorkflow.execute,
|
||||
args
|
||||
);
|
||||
await ctx.db.patch(run._id, { workflowId });
|
||||
},
|
||||
});
|
||||
|
||||
export const failAttempt = internalMutation({
|
||||
args: {
|
||||
attemptId: v.id("workAttempts"),
|
||||
reason: failureReasonValues,
|
||||
retryable: v.boolean(),
|
||||
summary: v.string(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const attempt = await ctx.db.get(args.attemptId);
|
||||
// Cancellation fencing: once an attempt or run is terminal/cancelled, a
|
||||
// late failure from the workflow catch block must not overwrite the
|
||||
// settled state. This also prevents a cancelled attempt from settling
|
||||
// as a different classification after cancelExecution ran.
|
||||
if (!attempt || attempt.status === "terminal") {
|
||||
return;
|
||||
}
|
||||
const run = await ctx.db.get(attempt.runId);
|
||||
if (!run || run.status === "terminal" || run.status === "cancelled") {
|
||||
return;
|
||||
}
|
||||
const classification = classifyFailure(args.reason);
|
||||
const endedAt = Date.now();
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification,
|
||||
endedAt,
|
||||
failureReason: args.reason,
|
||||
leaseExpiresAt: undefined,
|
||||
status: "terminal",
|
||||
summary: args.summary,
|
||||
});
|
||||
const outcome = resolveOutcome(
|
||||
{ classification, retryable: args.retryable, summary: args.summary },
|
||||
attempt.number,
|
||||
defaultCodingKitV0.retryPolicy
|
||||
);
|
||||
await ctx.db.insert("resolverDecisions", {
|
||||
attemptId: attempt._id,
|
||||
attemptNumber: attempt.number,
|
||||
classification,
|
||||
createdAt: endedAt,
|
||||
decision: outcome.kind,
|
||||
...(outcome.kind === "terminal"
|
||||
? { resultingWorkStatus: outcome.workStatus }
|
||||
: {}),
|
||||
runId: run._id,
|
||||
summary: args.summary,
|
||||
workId: attempt.workId,
|
||||
});
|
||||
if (outcome.kind === "retry") {
|
||||
const nextAttemptId = await ctx.db.insert("workAttempts", {
|
||||
number: attempt.number + 1,
|
||||
runId: run._id,
|
||||
status: "queued",
|
||||
workId: attempt.workId,
|
||||
workspaceKey: attempt.workspaceKey,
|
||||
});
|
||||
await ctx.scheduler.runAfter(
|
||||
0,
|
||||
internal.workExecutionWorkflow.launchAttemptWorkflow,
|
||||
{ attemptId: nextAttemptId }
|
||||
);
|
||||
return;
|
||||
}
|
||||
await ctx.db.patch(run._id, {
|
||||
endedAt,
|
||||
status: "terminal",
|
||||
terminalClassification: classification,
|
||||
terminalSummary: args.summary,
|
||||
});
|
||||
await settleSliceAndWork(ctx, run, false, outcome.workStatus);
|
||||
const work = await ctx.db.get(run.workId);
|
||||
if (work) {
|
||||
await ctx.db.insert("workEvents", {
|
||||
createdAt: endedAt,
|
||||
idempotencyKey: `real-run-failed:${run._id}`,
|
||||
kind: "run.completed",
|
||||
payloadJson: JSON.stringify({ classification }),
|
||||
referenceId: String(run._id),
|
||||
workId: work._id,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const cancelExecution = mutation({
|
||||
args: { runId: v.id("workRuns") },
|
||||
handler: async (ctx, args) => {
|
||||
const run = await ctx.db.get(args.runId);
|
||||
if (!run) {
|
||||
throw new ConvexError("Run not found");
|
||||
}
|
||||
await requireProjectMember(ctx, (await ctx.db.get(run.workId))!.projectId);
|
||||
if (run.status !== "running") {
|
||||
return { cancelled: false };
|
||||
}
|
||||
if (run.workflowId) {
|
||||
await workflow.cancel(ctx, run.workflowId as WorkflowId);
|
||||
}
|
||||
const attempts = await ctx.db
|
||||
.query("workAttempts")
|
||||
.withIndex("by_runId_and_number", (q) => q.eq("runId", run._id))
|
||||
.collect();
|
||||
const attempt = attempts.find(
|
||||
(candidate) => candidate.status !== "terminal"
|
||||
);
|
||||
if (attempt?.workspaceKey) {
|
||||
await ctx.scheduler.runAfter(
|
||||
0,
|
||||
internal.workExecutionAgent.cancelAttempt,
|
||||
{
|
||||
attemptId: String(attempt._id),
|
||||
workspaceKey: attempt.workspaceKey,
|
||||
}
|
||||
);
|
||||
const cancelledAt = Date.now();
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification: "Cancelled",
|
||||
endedAt: cancelledAt,
|
||||
failureReason: "Cancelled",
|
||||
leaseExpiresAt: undefined,
|
||||
status: "terminal",
|
||||
summary: "Execution cancelled",
|
||||
});
|
||||
await ctx.db.insert("resolverDecisions", {
|
||||
attemptId: attempt._id,
|
||||
attemptNumber: attempt.number,
|
||||
classification: "Cancelled",
|
||||
createdAt: cancelledAt,
|
||||
decision: "terminal",
|
||||
resultingWorkStatus: "ready",
|
||||
runId: run._id,
|
||||
summary: "Execution cancelled",
|
||||
workId: run.workId,
|
||||
});
|
||||
}
|
||||
await ctx.db.patch(run._id, {
|
||||
endedAt: Date.now(),
|
||||
status: "cancelled",
|
||||
terminalClassification: "Cancelled",
|
||||
terminalSummary: "Execution cancelled",
|
||||
});
|
||||
if (run.sliceRowId) {
|
||||
await ctx.db.patch(run.sliceRowId, { status: "ready" });
|
||||
}
|
||||
const work = await ctx.db.get(run.workId);
|
||||
if (work) {
|
||||
await ctx.db.patch(work._id, { status: "ready", updatedAt: Date.now() });
|
||||
}
|
||||
return { cancelled: true };
|
||||
},
|
||||
});
|
||||
@@ -771,13 +771,41 @@ export const listForProject = query({
|
||||
.eq("designVersion", work.designVersion ?? 0)
|
||||
)
|
||||
.collect();
|
||||
const runs = await ctx.db
|
||||
const runRows = await ctx.db
|
||||
.query("workRuns")
|
||||
.withIndex("by_work_and_createdAt", (q: any) =>
|
||||
q.eq("workId", work._id)
|
||||
)
|
||||
.order("desc")
|
||||
.take(10);
|
||||
const runs = await Promise.all(
|
||||
runRows.map(async (run) => {
|
||||
const attempts = await ctx.db
|
||||
.query("workAttempts")
|
||||
.withIndex("by_runId_and_number", (q) => q.eq("runId", run._id))
|
||||
.collect();
|
||||
const eventsByAttempt = await Promise.all(
|
||||
attempts.map((attempt) =>
|
||||
ctx.db
|
||||
.query("workAttemptEvents")
|
||||
.withIndex("by_attempt_and_sequence", (q: any) =>
|
||||
q.eq("attemptId", attempt._id)
|
||||
)
|
||||
.collect()
|
||||
)
|
||||
);
|
||||
const attemptEvents = eventsByAttempt
|
||||
.flat()
|
||||
.sort((left, right) => left.occurredAt - right.occurredAt);
|
||||
const artifacts = await ctx.db
|
||||
.query("workArtifacts")
|
||||
.withIndex("by_runId_and_createdAt", (q) =>
|
||||
q.eq("runId", run._id)
|
||||
)
|
||||
.collect();
|
||||
return { ...run, artifacts, attemptEvents, attempts };
|
||||
})
|
||||
);
|
||||
const events = await ctx.db
|
||||
.query("workEvents")
|
||||
.withIndex("by_work_and_createdAt", (q: any) =>
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"@code/env": "workspace:*",
|
||||
"@code/primitives": "workspace:*",
|
||||
"@convex-dev/better-auth": "catalog:",
|
||||
"@convex-dev/workflow": "0.4.4",
|
||||
"better-auth": "catalog:",
|
||||
"convex": "catalog:",
|
||||
"effect": "catalog:",
|
||||
|
||||
4
packages/env/src/agent.ts
vendored
4
packages/env/src/agent.ts
vendored
@@ -14,6 +14,10 @@ const agentEnvSchema = z.object({
|
||||
GITEA_TOKEN: z.string().min(1).optional(),
|
||||
GITEA_URL: z.url().default("https://git.openputer.com"),
|
||||
OPENROUTER_API_KEY: z.string().min(1).optional(),
|
||||
RIVET_ENDPOINT: z.url(),
|
||||
RIVET_PUBLIC_ENDPOINT: z.url().optional(),
|
||||
RIVET_WORKSPACE_TOKEN: z.string().min(32),
|
||||
ZOPU_SOURCE_REPOSITORY: z.string().min(1).default("/opt/zopu-source"),
|
||||
});
|
||||
|
||||
export type AgentEnv = z.infer<typeof agentEnvSchema>;
|
||||
|
||||
5
packages/env/src/convex.ts
vendored
5
packages/env/src/convex.ts
vendored
@@ -5,10 +5,15 @@ export const env = createEnv({
|
||||
emptyStringAsUndefined: true,
|
||||
runtimeEnv: process.env,
|
||||
server: {
|
||||
AGENT_BACKEND_URL: z.url().optional(),
|
||||
CONVEX_SITE_URL: z.url(),
|
||||
FLUE_DB_TOKEN: z.string().min(1),
|
||||
FLUE_URL: z.url().optional(),
|
||||
GITEA_TOKEN: z.string().min(1).optional(),
|
||||
GITEA_URL: z.url().default("https://git.openputer.com"),
|
||||
GITHUB_CLIENT_ID: z.string().min(1).optional(),
|
||||
GITHUB_CLIENT_SECRET: z.string().min(1).optional(),
|
||||
GIT_CREDENTIAL_ENCRYPTION_KEY: z.string().min(43).optional(),
|
||||
NATIVE_APP_URL: z.string().min(1).default("code://"),
|
||||
SITE_URL: z.url(),
|
||||
},
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./agent-os": "./src/agent-os.ts",
|
||||
"./execution-runtime": "./src/execution-runtime.ts",
|
||||
"./git": "./src/git.ts",
|
||||
"./git-local-runtime": "./src/git-local-runtime.ts",
|
||||
"./git-remote-runtime": "./src/git-remote-runtime.ts",
|
||||
@@ -29,9 +30,9 @@
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentos-software/codex-cli": "0.3.4",
|
||||
"@agentos-software/pi": "0.2.7",
|
||||
"@agentos-software/git": "0.3.3",
|
||||
"@rivet-dev/agentos": "catalog:",
|
||||
"@rivet-dev/agentos": "0.2.14",
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { codexSessionEnv, makeCodexAgentOsConfig } from "./agent-os";
|
||||
|
||||
describe("Codex agent-os config", () => {
|
||||
it("always includes the codex + git software bundle", () => {
|
||||
const config = makeCodexAgentOsConfig();
|
||||
expect(config.software).toHaveLength(2);
|
||||
expect(config.software?.[0]).toBeTypeOf("object");
|
||||
});
|
||||
|
||||
it("builds model-provider session env", () => {
|
||||
const env = codexSessionEnv(
|
||||
{
|
||||
apiKey: "sk-test",
|
||||
baseUrl: "https://ai.example.com/v1",
|
||||
model: "glm-5.2",
|
||||
},
|
||||
{ CODEX_MODEL: "glm-5.2" }
|
||||
);
|
||||
expect(env.OPENAI_API_KEY).toBe("sk-test");
|
||||
expect(env.OPENAI_BASE_URL).toBe("https://ai.example.com/v1");
|
||||
expect(env.CODEX_MODEL).toBe("glm-5.2");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable max-classes-per-file -- the AgentOS service and its tagged error form one adapter contract. */
|
||||
import codex from "@agentos-software/codex-cli";
|
||||
import pi from "@agentos-software/pi";
|
||||
import { agentOS as createAgentOsActor } from "@rivet-dev/agentos";
|
||||
import type { AgentOSConfigInput } from "@rivet-dev/agentos";
|
||||
import { Context, Effect, Layer, Schema } from "effect";
|
||||
@@ -73,50 +73,94 @@ export const createAgentOsActorEffect = Effect.fn("createAgentOsActorEffect")(
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Codex harness configuration
|
||||
// Pi harness configuration
|
||||
//
|
||||
// The canonical execution registry runs exactly one AgentOS actor for the
|
||||
// puter/zopu-code repo, booted with the Codex CLI harness + git. The model
|
||||
// provider is injected as VM env (OpenAI-compatible base URL + key) so Codex
|
||||
// authenticates against the configured gateway without a second credentials
|
||||
// path. This is a pure config builder; the RivetKit registry/server that hosts
|
||||
// the actor lives in the agents package.
|
||||
// Slice 5 intentionally runs one harness against the server's fixed Zopu
|
||||
// checkout. Pi speaks ACP natively and reads its model gateway from a mounted
|
||||
// HOME, avoiding a second executable adapter or credentials path.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Software bundle for a Codex-capable VM: the Codex harness plus git. */
|
||||
export const codexSoftware = [codex, getExecutableGitSoftware()] as const;
|
||||
/** Software bundle for a Pi-capable VM: the Pi ACP harness plus git. */
|
||||
export const piSoftware = [pi, getExecutableGitSoftware()] as const;
|
||||
|
||||
/** Model-provider env that Codex reads inside the VM. Pass this to the session's
|
||||
* `env` when opening a Codex session (`agent: "codex"`). */
|
||||
export interface CodexModelEnv {
|
||||
readonly apiKey: string;
|
||||
export interface PiModelConfig {
|
||||
readonly api: "openai-completions";
|
||||
readonly apiKeyEnvironmentVariable: string;
|
||||
readonly baseUrl: string;
|
||||
readonly contextWindow: number;
|
||||
readonly maxTokens: number;
|
||||
readonly model: string;
|
||||
readonly provider: string;
|
||||
}
|
||||
|
||||
/** Builds the VM env record Codex reads to authenticate against the model gateway. */
|
||||
export const codexSessionEnv = (
|
||||
model: CodexModelEnv,
|
||||
export interface PiHomeFiles {
|
||||
readonly models: string;
|
||||
readonly settings: string;
|
||||
}
|
||||
|
||||
/** Builds the two files Pi reads from ~/.pi/agent. */
|
||||
export const makePiHomeFiles = (model: PiModelConfig): PiHomeFiles => ({
|
||||
models: JSON.stringify(
|
||||
{
|
||||
providers: {
|
||||
[model.provider]: {
|
||||
api: model.api,
|
||||
apiKey: model.apiKeyEnvironmentVariable,
|
||||
authHeader: true,
|
||||
baseUrl: model.baseUrl,
|
||||
models: [
|
||||
{
|
||||
contextWindow: model.contextWindow,
|
||||
id: model.model,
|
||||
maxTokens: model.maxTokens,
|
||||
name: model.model,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
),
|
||||
settings: JSON.stringify(
|
||||
{
|
||||
defaultModel: model.model,
|
||||
defaultProvider: model.provider,
|
||||
quietStartup: true,
|
||||
},
|
||||
null,
|
||||
2
|
||||
),
|
||||
});
|
||||
|
||||
/** Environment supplied to the Pi ACP session. */
|
||||
export const piSessionEnv = (
|
||||
apiKey: string,
|
||||
extra: Readonly<Record<string, string>> = {}
|
||||
): Record<string, string> => ({
|
||||
OPENAI_API_KEY: model.apiKey,
|
||||
OPENAI_BASE_URL: model.baseUrl,
|
||||
AGENT_MODEL_API_KEY: apiKey,
|
||||
HOME: "/home/zopu",
|
||||
PATH: "/opt/zopu-tools/bin:/usr/local/bin:/usr/bin:/bin",
|
||||
...extra,
|
||||
});
|
||||
|
||||
export interface CodexAgentOsConfigInput {
|
||||
/** Extra software merged after the Codex+git bundle. */
|
||||
export interface PiAgentOsConfigInput {
|
||||
/** Extra software merged after the Pi+git bundle. */
|
||||
readonly software?: NonNullable<AgentOSConfigInput<undefined>["software"]>;
|
||||
/** VM permission overrides merged over the execution policy. */
|
||||
readonly permissions?: AgentOSConfigInput<undefined>["permissions"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an AgentOS actor config for a Codex-backed VM. The Codex CLI and git
|
||||
* are always present; software the caller passes is appended, never replacing
|
||||
* the harness or git. Model-provider env is supplied per session via
|
||||
* `codexSessionEnv`, not here — the actor config has no env field.
|
||||
*/
|
||||
export const makeCodexAgentOsConfig = (
|
||||
input: CodexAgentOsConfigInput = {}
|
||||
export const makePiAgentOsConfig = (
|
||||
input: PiAgentOsConfigInput = {}
|
||||
): AgentOSConfigInput<undefined> => ({
|
||||
software: [...codexSoftware, ...(input.software ?? [])],
|
||||
permissions: {
|
||||
childProcess: "allow",
|
||||
env: "allow",
|
||||
fs: "allow",
|
||||
network: "allow",
|
||||
process: "allow",
|
||||
...input.permissions,
|
||||
},
|
||||
software: [...piSoftware, ...(input.software ?? [])],
|
||||
});
|
||||
|
||||
38
packages/primitives/src/execution-runtime.test.ts
Normal file
38
packages/primitives/src/execution-runtime.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
decodeGitConnectionInput,
|
||||
decodeWorkAttemptExecutionResult,
|
||||
} from "./execution-runtime";
|
||||
|
||||
describe("execution runtime contracts", () => {
|
||||
test("accepts one authenticated Gitea connection", async () => {
|
||||
const decoded = await Effect.runPromise(
|
||||
decodeGitConnectionInput({
|
||||
credential: "secret",
|
||||
credentialKind: "token",
|
||||
provider: "gitea",
|
||||
serverUrl: "https://git.example.com",
|
||||
username: "zopu",
|
||||
})
|
||||
);
|
||||
expect(decoded.provider).toBe("gitea");
|
||||
});
|
||||
|
||||
test("requires exact base and candidate revisions", async () => {
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
decodeWorkAttemptExecutionResult({
|
||||
baseRevision: "",
|
||||
candidateRevision: "abc123",
|
||||
changedFiles: [],
|
||||
diff: "",
|
||||
environmentId: "workspace-1",
|
||||
events: [],
|
||||
summary: "done",
|
||||
})
|
||||
)
|
||||
).rejects.toMatchObject({ reason: "InvalidInput" });
|
||||
});
|
||||
});
|
||||
171
packages/primitives/src/execution-runtime.ts
Normal file
171
packages/primitives/src/execution-runtime.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/* eslint-disable max-classes-per-file -- execution boundary errors live with their schemas. */
|
||||
import { Effect, Schema } from "effect";
|
||||
|
||||
const Text = Schema.String.check(
|
||||
Schema.makeFilter((value) => value.trim().length > 0, {
|
||||
expected: "a non-empty string",
|
||||
})
|
||||
);
|
||||
|
||||
const HttpUrl = Schema.String.check(
|
||||
Schema.makeFilter(
|
||||
(value) => {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "http:" || url.protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
{ expected: "an HTTP URL" }
|
||||
)
|
||||
);
|
||||
|
||||
export const GitProvider = Schema.Literals(["github", "gitea"]);
|
||||
export type GitProvider = typeof GitProvider.Type;
|
||||
|
||||
export const GitCredentialKind = Schema.Literals(["oauth", "token"]);
|
||||
export type GitCredentialKind = typeof GitCredentialKind.Type;
|
||||
|
||||
export const GitConnectionInput = Schema.Struct({
|
||||
credential: Text,
|
||||
credentialKind: GitCredentialKind,
|
||||
provider: GitProvider,
|
||||
serverUrl: HttpUrl,
|
||||
username: Schema.optional(Text),
|
||||
});
|
||||
export type GitConnectionInput = typeof GitConnectionInput.Type;
|
||||
|
||||
export const GitConnectionView = Schema.Struct({
|
||||
connectedAt: Schema.Number,
|
||||
credentialKind: GitCredentialKind,
|
||||
id: Text,
|
||||
provider: GitProvider,
|
||||
serverUrl: HttpUrl,
|
||||
username: Schema.optional(Text),
|
||||
});
|
||||
export type GitConnectionView = typeof GitConnectionView.Type;
|
||||
|
||||
export const RepositoryExecutionAuth = Schema.Struct({
|
||||
credential: Text,
|
||||
provider: GitProvider,
|
||||
serverUrl: HttpUrl,
|
||||
username: Schema.optional(Text),
|
||||
});
|
||||
export type RepositoryExecutionAuth = typeof RepositoryExecutionAuth.Type;
|
||||
|
||||
export const ExecutionEventKind = Schema.Literals([
|
||||
"runtime.preparing",
|
||||
"repository.cloning",
|
||||
"repository.ready",
|
||||
"harness.started",
|
||||
"harness.progress",
|
||||
"harness.log",
|
||||
"repository.changed",
|
||||
"runtime.completed",
|
||||
"runtime.failed",
|
||||
"runtime.cancelled",
|
||||
]);
|
||||
export type ExecutionEventKind = typeof ExecutionEventKind.Type;
|
||||
|
||||
export const ExecutionEvent = Schema.Struct({
|
||||
kind: ExecutionEventKind,
|
||||
message: Text,
|
||||
metadata: Schema.Record(Schema.String, Schema.String),
|
||||
occurredAt: Schema.Number,
|
||||
sequence: Schema.Int,
|
||||
});
|
||||
export type ExecutionEvent = typeof ExecutionEvent.Type;
|
||||
|
||||
export const WorkAttemptExecutionInput = Schema.Struct({
|
||||
attemptId: Text,
|
||||
auth: RepositoryExecutionAuth,
|
||||
baseBranch: Text,
|
||||
prompt: Text,
|
||||
repositoryUrl: HttpUrl,
|
||||
runId: Text,
|
||||
workId: Text,
|
||||
workspaceKey: Text,
|
||||
});
|
||||
export type WorkAttemptExecutionInput = typeof WorkAttemptExecutionInput.Type;
|
||||
|
||||
export const WorkAttemptExecutionResult = Schema.Struct({
|
||||
baseRevision: Text,
|
||||
candidateRevision: Text,
|
||||
changedFiles: Schema.Array(Text),
|
||||
diff: Schema.String,
|
||||
environmentId: Text,
|
||||
events: Schema.Array(ExecutionEvent),
|
||||
summary: Text,
|
||||
});
|
||||
export type WorkAttemptExecutionResult = typeof WorkAttemptExecutionResult.Type;
|
||||
|
||||
export const WorkAttemptExecutionErrorReason = Schema.Literals([
|
||||
"Authentication",
|
||||
"Cancelled",
|
||||
"HarnessFailed",
|
||||
"InvalidInput",
|
||||
"ProviderUnavailable",
|
||||
"RepositoryFailed",
|
||||
"Timeout",
|
||||
]);
|
||||
export type WorkAttemptExecutionErrorReason =
|
||||
typeof WorkAttemptExecutionErrorReason.Type;
|
||||
|
||||
export class WorkAttemptExecutionError extends Schema.TaggedErrorClass<WorkAttemptExecutionError>()(
|
||||
"WorkAttemptExecutionError",
|
||||
{
|
||||
message: Schema.String,
|
||||
reason: WorkAttemptExecutionErrorReason,
|
||||
retryable: Schema.Boolean,
|
||||
}
|
||||
) {}
|
||||
|
||||
export const WorkAttemptExecutionFailure = Schema.Struct({
|
||||
error: Schema.Struct({
|
||||
message: Text,
|
||||
reason: WorkAttemptExecutionErrorReason,
|
||||
retryable: Schema.Boolean,
|
||||
}),
|
||||
});
|
||||
export type WorkAttemptExecutionFailure =
|
||||
typeof WorkAttemptExecutionFailure.Type;
|
||||
|
||||
const invalidInput = (message: string) =>
|
||||
new WorkAttemptExecutionError({
|
||||
message,
|
||||
reason: "InvalidInput",
|
||||
retryable: false,
|
||||
});
|
||||
|
||||
export const decodeGitConnectionInput = (input: unknown) =>
|
||||
Schema.decodeUnknownEffect(GitConnectionInput)(input).pipe(
|
||||
Effect.mapError((cause) => invalidInput(cause.message))
|
||||
);
|
||||
|
||||
export const decodeWorkAttemptExecutionInput = (input: unknown) =>
|
||||
Schema.decodeUnknownEffect(WorkAttemptExecutionInput)(input).pipe(
|
||||
Effect.mapError((cause) => invalidInput(cause.message))
|
||||
);
|
||||
|
||||
export const decodeWorkAttemptExecutionResult = (input: unknown) =>
|
||||
Schema.decodeUnknownEffect(WorkAttemptExecutionResult)(input).pipe(
|
||||
Effect.mapError((cause) => invalidInput(cause.message))
|
||||
);
|
||||
|
||||
export const decodeWorkAttemptExecutionFailure = (input: unknown) =>
|
||||
Schema.decodeUnknownEffect(WorkAttemptExecutionFailure)(input).pipe(
|
||||
Effect.mapError((cause) => invalidInput(cause.message))
|
||||
);
|
||||
|
||||
export interface SandboxRuntime {
|
||||
readonly name: string;
|
||||
readonly execute: (
|
||||
input: WorkAttemptExecutionInput,
|
||||
signal?: AbortSignal
|
||||
) => Effect.Effect<WorkAttemptExecutionResult, WorkAttemptExecutionError>;
|
||||
readonly cancel: (
|
||||
workspaceKey: string,
|
||||
attemptId: string
|
||||
) => Effect.Effect<void, WorkAttemptExecutionError>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// oxlint-disable-next-line no-barrel-file -- The package root intentionally exposes its public modules.
|
||||
export * from "./agent-os";
|
||||
export * from "./execution-runtime";
|
||||
export * from "./git";
|
||||
export * from "./git-local-runtime";
|
||||
export * from "./git-remote-runtime";
|
||||
|
||||
20928
pnpm-lock.yaml
generated
Normal file
20928
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
62
pnpm-workspace.yaml
Normal file
62
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,62 @@
|
||||
packages:
|
||||
- apps/web
|
||||
- packages/agents
|
||||
- packages/auth
|
||||
- packages/backend
|
||||
- packages/config
|
||||
- packages/env
|
||||
- packages/primitives
|
||||
- packages/ui
|
||||
|
||||
allowBuilds:
|
||||
"@google/genai": true
|
||||
"@mongodb-js/zstd": true
|
||||
better-sqlite3: true
|
||||
cbor-extract: true
|
||||
esbuild: true
|
||||
isolated-vm: true
|
||||
koffi: true
|
||||
msgpackr-extract: true
|
||||
node-liblzma: true
|
||||
protobufjs: true
|
||||
workerd: true
|
||||
|
||||
catalog:
|
||||
"@rivet-dev/agentos": "^0.2.7"
|
||||
"@rivet-dev/agentos-core": "^0.2.10"
|
||||
"@effect/platform-bun": "4.0.0-beta.99"
|
||||
dotenv: "^17.4.2"
|
||||
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"
|
||||
"@convex-dev/better-auth": "^0.12.5"
|
||||
"@tanstack/react-form": "^1.33.0"
|
||||
"@types/react-dom": "^19.2.3"
|
||||
tailwindcss: "^4.3.2"
|
||||
tailwind-merge: "^3.6.0"
|
||||
"@better-auth/expo": "1.6.15"
|
||||
effect: "4.0.0-beta.99"
|
||||
typescript: "^7.0.2"
|
||||
"@types/bun": "latest"
|
||||
heroui-native: "^1.0.5"
|
||||
vite: "^7.3.6"
|
||||
vitest: "^4.1.10"
|
||||
convex-test: "^0.0.54"
|
||||
react-native: "0.86.0"
|
||||
"@types/react": "^19.2.17"
|
||||
"@types/node": "^22.13.14"
|
||||
hono: "^4.8.3"
|
||||
valibot: "^1.4.2"
|
||||
streamdown: "2.5.0"
|
||||
"@tailwindcss/postcss": "^4.3.2"
|
||||
"@tailwindcss/vite": "^4.3.2"
|
||||
|
||||
overrides:
|
||||
react: 19.2.8
|
||||
react-dom: 19.2.8
|
||||
vite: npm:@voidzero-dev/vite-plus-core@0.2.2
|
||||
Reference in New Issue
Block a user