Compare commits
17 Commits
feat/slice
...
d8a4bbe804
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8a4bbe804 | ||
|
|
9eb6bcd25f | ||
|
|
a907539810 | ||
|
|
601aca73c2 | ||
|
|
ffecff3857 | ||
|
|
0d7162544b | ||
|
|
092a9793ea | ||
|
|
5ee0a8d50e | ||
|
|
420676f2d7 | ||
|
|
24d82e2a06 | ||
|
|
d47fa0e96a | ||
|
|
1e7c893985 | ||
|
|
f9ebcb4a01 | ||
|
|
dceaa2b417 | ||
|
|
a4f121e190 | ||
|
|
4edd456b5b | ||
|
|
4d9f6da41b |
@@ -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
|
||||
|
||||
@@ -1,789 +0,0 @@
|
||||
import { projectWorkNotices } from "@code/primitives/work";
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
} from "@code/ui/components/ai-elements/conversation";
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import {
|
||||
ChevronRight,
|
||||
Check,
|
||||
FolderGit2,
|
||||
Hammer,
|
||||
LoaderCircle,
|
||||
Menu,
|
||||
MessageSquareText,
|
||||
ImagePlus,
|
||||
Play,
|
||||
RotateCcw,
|
||||
Send,
|
||||
Sparkles,
|
||||
Settings,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
|
||||
import { PendingChatAttachments } from "@/components/chat/chat-attachments";
|
||||
import { ChatMessage } from "@/components/chat/chat-message";
|
||||
import { ChatThinkingResponse } from "@/components/chat/chat-thinking-response";
|
||||
import { useChatImages } from "@/hooks/chat/use-chat-images";
|
||||
import { useSliceOne } from "@/hooks/slice-one/use-slice-one";
|
||||
import { useVisualViewportStyle } from "@/hooks/slice-one/use-visual-viewport";
|
||||
import {
|
||||
buildSliceOneTimeline,
|
||||
findSourceMessageTarget,
|
||||
} from "@/lib/slice-one/presentation";
|
||||
|
||||
type SliceWork = NonNullable<ReturnType<typeof useSliceOne>["works"]>[number];
|
||||
const EMPTY_WORKS: readonly SliceWork[] = [];
|
||||
|
||||
interface WorkCardProps {
|
||||
readonly onSourceSelect: (rawText: string) => void;
|
||||
readonly work: SliceWork;
|
||||
readonly slice: SliceOneState;
|
||||
}
|
||||
|
||||
const starterDefinition = (work: SliceWork) => ({
|
||||
acceptanceCriteria: ["The requested outcome is observable and documented"],
|
||||
affectedUsers: ["Project users"],
|
||||
assumptions: [],
|
||||
constraints: [],
|
||||
desiredOutcome: work.objective,
|
||||
inScope: [work.objective],
|
||||
outOfScope: ["Unrelated product changes"],
|
||||
problem: work.objective,
|
||||
questions: [],
|
||||
requiredArtifacts: ["Simulation activity and terminal outcome"],
|
||||
risk: "medium",
|
||||
});
|
||||
|
||||
const starterDesign = (work: SliceWork) => ({
|
||||
architectureSummary:
|
||||
"Validate the approved Definition, then exercise one deterministic fake slice.",
|
||||
callFlowDelta: [
|
||||
"Work -> Run -> Attempt -> normalized events -> terminal outcome",
|
||||
],
|
||||
concerns: [],
|
||||
evidenceRequirements: ["Terminal Run classification"],
|
||||
fileTreeDelta: [],
|
||||
impactMap: {
|
||||
files: [],
|
||||
modules: [],
|
||||
risks: [],
|
||||
summary: "Compact vertical-slice simulation",
|
||||
},
|
||||
invariants: [
|
||||
"Simulation never claims implementation",
|
||||
"Every Attempt reaches a terminal classification",
|
||||
],
|
||||
keyInterfaces: ["HarnessRuntime", "AttemptOutcome"],
|
||||
slices: [
|
||||
{
|
||||
codeBoundaries: ["workExecution"],
|
||||
dependsOn: [],
|
||||
evidenceRequirements: ["Normalized activity events"],
|
||||
id: "slice-1",
|
||||
objective: work.objective,
|
||||
observableBehavior: "A terminal fake Run is visible",
|
||||
reviewRequired: false,
|
||||
title: "Deterministic simulation",
|
||||
verification: ["Run completes with a terminal classification"],
|
||||
},
|
||||
],
|
||||
tradeoffs: ["Fake runtime proves contract before sandbox integration"],
|
||||
});
|
||||
|
||||
// oxlint-disable-next-line complexity -- the expanded card intentionally keeps the three review sections together.
|
||||
const WorkCard = ({ onSourceSelect, work, slice }: WorkCardProps) => {
|
||||
const [sourcesOpen, setSourcesOpen] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const sources = work.signals.flatMap((signal) => signal.sources);
|
||||
const { definition } = work;
|
||||
const { design } = work;
|
||||
const [latestRun] = work.runs;
|
||||
return (
|
||||
<article className="border border-[#d7d3c7] bg-[#fffefa] p-4 text-[#20201d] shadow-[0_10px_30px_rgba(30,30,20,0.06)]">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="grid size-8 shrink-0 place-items-center bg-[#dcff68]">
|
||||
<Sparkles className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[10px] font-semibold uppercase text-[#65713a]">
|
||||
Proposed Work
|
||||
</p>
|
||||
<h2 className="mt-1 text-[15px] font-semibold leading-5">
|
||||
{work.title}
|
||||
</h2>
|
||||
<p className="mt-1.5 text-[13px] leading-5 text-[#626057]">
|
||||
{work.objective}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="mt-3 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs text-[#69675e]"
|
||||
onClick={() => setSourcesOpen((open) => !open)}
|
||||
type="button"
|
||||
>
|
||||
<span>
|
||||
{sources.length} exact source{" "}
|
||||
{sources.length === 1 ? "message" : "messages"}
|
||||
</span>
|
||||
<ChevronRight
|
||||
className={`size-4 transition-transform ${sourcesOpen ? "rotate-90" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
className="mt-2 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs font-medium text-[#20201d]"
|
||||
onClick={() => setExpanded((open) => !open)}
|
||||
type="button"
|
||||
>
|
||||
<span>{expanded ? "Hide Work details" : "Open Work details"}</span>
|
||||
<ChevronRight
|
||||
className={`size-4 transition-transform ${expanded ? "rotate-90" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
{sourcesOpen ? (
|
||||
<div className="mt-3 space-y-2">
|
||||
{sources.map((source) => (
|
||||
<button
|
||||
className="flex w-full items-start gap-2 border-l-2 border-[#a8b750] bg-[#f4f2e9] px-3 py-2 text-left text-xs leading-5 hover:bg-[#ece9dd]"
|
||||
key={source.messageId}
|
||||
onClick={() => onSourceSelect(source.rawText)}
|
||||
type="button"
|
||||
>
|
||||
<MessageSquareText className="mt-1 size-3.5 shrink-0 text-[#65713a]" />
|
||||
<span className="min-w-0 flex-1">{source.rawText}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{expanded ? (
|
||||
<div className="mt-4 space-y-4 border-t border-[#e7e3d9] pt-4 text-xs">
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Outcome
|
||||
</p>
|
||||
<p className="mt-1 leading-5 text-[#626057]">{work.objective}</p>
|
||||
<p className="mt-2 text-[#747168]">
|
||||
Risk: {definition?.risk ?? "not defined"}
|
||||
</p>
|
||||
{definition?.questions?.length ? (
|
||||
<p className="mt-1 text-amber-800">
|
||||
{
|
||||
definition.questions.filter(
|
||||
(question) => question.status === "open"
|
||||
).length
|
||||
}{" "}
|
||||
open question(s)
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "proposed" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => void slice.requestDefinition(work._id)}
|
||||
>
|
||||
<Sparkles className="size-3.5" /> Define
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "defining" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void slice.saveDefinition(work._id, starterDefinition(work))
|
||||
}
|
||||
>
|
||||
<Hammer className="size-3.5" /> Save definition
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "awaiting-definition-approval" &&
|
||||
work.definitionVersion ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void slice.approveDefinition(
|
||||
work._id,
|
||||
work.definitionVersion as number
|
||||
)
|
||||
}
|
||||
>
|
||||
<Check className="size-3.5" /> Approve
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Design
|
||||
</p>
|
||||
<p className="mt-1 leading-5 text-[#626057]">
|
||||
{design?.architectureSummary ?? "No Design Packet yet."}
|
||||
</p>
|
||||
{design?.slices?.map((item) => (
|
||||
<p className="mt-1 text-[#747168]" key={item.id}>
|
||||
{item.title}: {item.observableBehavior}
|
||||
</p>
|
||||
))}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "designing" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void slice.saveDesign(work._id, starterDesign(work))
|
||||
}
|
||||
>
|
||||
<Hammer className="size-3.5" /> Save design
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "awaiting-design-approval" &&
|
||||
work.definitionApprovalVersion &&
|
||||
work.designVersion ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void slice.approveDesign(
|
||||
work._id,
|
||||
work.definitionApprovalVersion as number,
|
||||
work.designVersion as number
|
||||
)
|
||||
}
|
||||
>
|
||||
<Check className="size-3.5" /> Approve design
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Build
|
||||
</p>
|
||||
{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.attemptEvents?.slice(-5).map((item) => (
|
||||
<p
|
||||
className="border-l-2 border-[#b8c760] pl-2"
|
||||
key={item._id}
|
||||
>
|
||||
{item.message}
|
||||
</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) => (
|
||||
<a
|
||||
className="block font-medium underline"
|
||||
href={artifact.uri}
|
||||
key={artifact._id}
|
||||
rel="noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{artifact.title}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<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, design?.slices?.[0]?.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
|
||||
)
|
||||
}
|
||||
>
|
||||
<Play className="size-3.5" /> Simulate
|
||||
</Button>
|
||||
) : null}
|
||||
{latestRun?.status === "running" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
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.terminalClassification === "RetryableFailure" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void slice.retrySimulation(latestRun._id)}
|
||||
>
|
||||
<RotateCcw className="size-3.5" /> Retry
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
};
|
||||
|
||||
const ConversationLoading = () => (
|
||||
<output
|
||||
aria-label="Loading conversation"
|
||||
className="mx-auto flex min-h-[55vh] w-full max-w-md flex-col justify-center gap-4"
|
||||
>
|
||||
<span className="h-16 w-4/5 animate-pulse rounded-sm bg-[#e3e0d5]" />
|
||||
<span className="ml-auto h-12 w-3/5 animate-pulse rounded-sm bg-[#dedbd0]" />
|
||||
<span className="h-24 w-full animate-pulse rounded-sm bg-[#e3e0d5]" />
|
||||
<span className="sr-only">Loading conversation…</span>
|
||||
</output>
|
||||
);
|
||||
|
||||
const ConversationEmptyState = () => (
|
||||
<div className="grid min-h-[55vh] place-items-center text-center">
|
||||
<div>
|
||||
<MessageSquareText className="mx-auto size-7 text-[#8a887f]" />
|
||||
<h1 className="mt-4 text-xl font-semibold">What should move forward?</h1>
|
||||
<p className="mx-auto mt-2 max-w-sm text-sm leading-6 text-[#69675f]">
|
||||
Describe an outcome or problem. Casual conversation stays conversation.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
type SliceOneState = ReturnType<typeof useSliceOne>;
|
||||
|
||||
const ProjectsLoading = () => (
|
||||
<div className="grid min-h-svh place-items-center bg-[#f2f0e7]">
|
||||
<LoaderCircle className="size-5 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
const ConnectProject = ({ slice }: { slice: SliceOneState }) => (
|
||||
<main className="grid min-h-svh place-items-center bg-[#f2f0e7] px-5 text-[#20201d]">
|
||||
<form
|
||||
className="w-full max-w-sm"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void slice.connectRepository();
|
||||
}}
|
||||
>
|
||||
<span className="grid size-11 place-items-center bg-[#20201d] text-white">
|
||||
<FolderGit2 className="size-5" />
|
||||
</span>
|
||||
<h1 className="mt-6 text-2xl font-semibold">Connect one project</h1>
|
||||
<p className="mt-2 text-sm leading-6 text-[#68665e]">
|
||||
Slice 1 turns actionable conversation into proposed Work with exact
|
||||
provenance.
|
||||
</p>
|
||||
<input
|
||||
aria-label="Public Git repository URL"
|
||||
className="mt-6 h-12 w-full border border-[#c9c5b9] bg-[#fffefa] px-3 text-sm outline-none focus:border-[#55564e]"
|
||||
onChange={(event) => slice.setRepository(event.target.value)}
|
||||
placeholder="https://github.com/owner/repository"
|
||||
required
|
||||
value={slice.repository}
|
||||
/>
|
||||
{slice.error ? (
|
||||
<p className="mt-2 text-xs text-red-700">{slice.error.message}</p>
|
||||
) : null}
|
||||
<Button
|
||||
className="mt-3 h-12 w-full"
|
||||
disabled={slice.pending}
|
||||
type="submit"
|
||||
>
|
||||
{slice.pending ? (
|
||||
<LoaderCircle className="size-4 animate-spin" />
|
||||
) : null}
|
||||
{slice.pending ? "Connecting" : "Connect project"}
|
||||
</Button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
|
||||
export const SliceOnePage = () => {
|
||||
const slice = useSliceOne();
|
||||
const viewportStyle = useVisualViewportStyle();
|
||||
const [draft, setDraft] = useState("");
|
||||
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;
|
||||
const workById = useMemo(
|
||||
() => new Map(works.map((work) => [String(work._id), work])),
|
||||
[works]
|
||||
);
|
||||
const notices = useMemo(() => projectWorkNotices(works), [works]);
|
||||
const timeline = useMemo(
|
||||
() => buildSliceOneTimeline(slice.agent.messages, notices),
|
||||
[notices, slice.agent.messages]
|
||||
);
|
||||
const busy =
|
||||
slice.agent.status === "submitted" || slice.agent.status === "streaming";
|
||||
|
||||
const revealSourceMessage = (rawText: string) => {
|
||||
const messageId = findSourceMessageTarget(slice.agent.messages, rawText);
|
||||
if (!messageId) {
|
||||
return;
|
||||
}
|
||||
setDrawerOpen(false);
|
||||
setHighlightedMessageId(messageId);
|
||||
if (highlightTimer.current) {
|
||||
clearTimeout(highlightTimer.current);
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
document
|
||||
.querySelector(`#${CSS.escape(`slice-message-${messageId}`)}`)
|
||||
?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
});
|
||||
highlightTimer.current = setTimeout(
|
||||
() => setHighlightedMessageId(undefined),
|
||||
1800
|
||||
);
|
||||
};
|
||||
|
||||
if (slice.projects === undefined) {
|
||||
return <ProjectsLoading />;
|
||||
}
|
||||
|
||||
if (!slice.selectedProject) {
|
||||
return <ConnectProject slice={slice} />;
|
||||
}
|
||||
|
||||
const send = async () => {
|
||||
const message = draft.trim();
|
||||
if (!message || busy) {
|
||||
return;
|
||||
}
|
||||
await slice.agent.sendMessage(message, {
|
||||
images: attachments.images.map((image) => image.file),
|
||||
});
|
||||
setDraft("");
|
||||
attachments.clear();
|
||||
};
|
||||
|
||||
return (
|
||||
<main
|
||||
className="slice-one-surface fixed inset-x-0 top-0 flex min-h-0 overflow-hidden bg-[#f2f0e7] text-[#20201d]"
|
||||
style={viewportStyle}
|
||||
>
|
||||
<section className="flex min-w-0 flex-1 flex-col">
|
||||
<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"
|
||||
className="block h-7 max-w-full border-0 bg-transparent pr-7 text-sm font-semibold text-[#20201d] outline-none"
|
||||
onChange={(event) => slice.selectProject(event.target.value)}
|
||||
value={slice.selectedProject.id}
|
||||
>
|
||||
{slice.projects.map((project) => (
|
||||
<option key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-[10px] uppercase text-[#858277]">
|
||||
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)}
|
||||
type="button"
|
||||
>
|
||||
<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>
|
||||
<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">
|
||||
{!slice.agent.historyReady && timeline.length === 0 ? (
|
||||
<ConversationLoading />
|
||||
) : null}
|
||||
{slice.agent.historyReady && timeline.length === 0 ? (
|
||||
<ConversationEmptyState />
|
||||
) : null}
|
||||
{timeline.map((item) => {
|
||||
if (item.kind === "work") {
|
||||
const work = workById.get(item.notice.workId);
|
||||
return work ? (
|
||||
<div
|
||||
className="chat-message ml-7"
|
||||
key={`notice-${item.notice.eventId}`}
|
||||
>
|
||||
<p className="mb-2 text-[10px] font-semibold uppercase text-[#65713a]">
|
||||
Work proposed from this conversation
|
||||
</p>
|
||||
<WorkCard
|
||||
onSourceSelect={revealSourceMessage}
|
||||
slice={slice}
|
||||
work={work}
|
||||
/>
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={`rounded-sm transition-colors duration-300 ${
|
||||
highlightedMessageId === item.message.id
|
||||
? "bg-[#dcff68]/70 ring-2 ring-[#7f9130] ring-offset-4 ring-offset-[#f2f0e7]"
|
||||
: ""
|
||||
}`}
|
||||
id={`slice-message-${item.message.id}`}
|
||||
key={item.message.id}
|
||||
>
|
||||
<ChatMessage message={item.message} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{slice.agent.status === "submitted" ? (
|
||||
<ChatThinkingResponse />
|
||||
) : null}
|
||||
</ConversationContent>
|
||||
</Conversation>
|
||||
<div className="shrink-0 border-t border-[#d7d3c7] bg-[#faf9f4] p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||
{attachments.images.length > 0 ? (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<PendingChatAttachments
|
||||
images={attachments.images}
|
||||
onRemove={attachments.handleRemove}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{slice.agent.error ? (
|
||||
<p className="mx-auto mb-2 max-w-2xl text-xs text-red-700">
|
||||
{slice.agent.error.message}
|
||||
</p>
|
||||
) : null}
|
||||
{attachments.error ? (
|
||||
<p className="mx-auto mb-2 max-w-2xl text-xs text-red-700">
|
||||
{attachments.error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mx-auto flex max-w-2xl items-end gap-2">
|
||||
<input
|
||||
accept="image/*"
|
||||
aria-label="Attach images"
|
||||
className="sr-only"
|
||||
multiple
|
||||
onChange={(event) => {
|
||||
attachments.addFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}}
|
||||
ref={imageInput}
|
||||
type="file"
|
||||
/>
|
||||
<Button
|
||||
aria-label="Attach images"
|
||||
className="size-11 shrink-0"
|
||||
disabled={busy}
|
||||
onClick={() => imageInput.current?.click()}
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<ImagePlus className="size-4" />
|
||||
</Button>
|
||||
<textarea
|
||||
aria-label="Message Zopu"
|
||||
className="max-h-32 min-h-11 flex-1 resize-none border border-[#c9c5b9] bg-white px-3 py-2.5 text-sm outline-none focus:border-[#55564e]"
|
||||
disabled={busy}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}
|
||||
}}
|
||||
placeholder="Describe an outcome or problem…"
|
||||
rows={1}
|
||||
value={draft}
|
||||
/>
|
||||
<Button
|
||||
aria-label="Send message"
|
||||
className="size-11 shrink-0"
|
||||
disabled={!draft.trim() || busy}
|
||||
onClick={() => void send()}
|
||||
size="icon"
|
||||
type="button"
|
||||
>
|
||||
{busy ? (
|
||||
<LoaderCircle className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<aside className="hidden w-[380px] shrink-0 overflow-y-auto border-l border-[#d7d3c7] bg-[#e9e7de] p-4 lg:block">
|
||||
<h2 className="text-sm font-semibold">Proposed Work</h2>
|
||||
<p className="mb-4 text-xs text-[#747168]">
|
||||
{works.length} durable outcomes
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
{works.map((work) => (
|
||||
<WorkCard
|
||||
key={work._id}
|
||||
onSourceSelect={revealSourceMessage}
|
||||
slice={slice}
|
||||
work={work}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
{drawerOpen ? (
|
||||
<div className="fixed inset-0 z-50 bg-black/30 lg:hidden">
|
||||
<button
|
||||
aria-label="Close Work drawer"
|
||||
className="absolute inset-0"
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
type="button"
|
||||
/>
|
||||
<section className="absolute inset-y-0 right-0 flex w-[min(92vw,380px)] flex-col bg-[#e9e7de] shadow-2xl">
|
||||
<header className="flex h-14 items-center border-b border-[#cfcbc0] px-4">
|
||||
<h2 className="flex-1 text-sm font-semibold">Proposed Work</h2>
|
||||
<button
|
||||
aria-label="Close Work drawer"
|
||||
className="grid size-9 place-items-center"
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</header>
|
||||
<div className="flex-1 space-y-3 overflow-y-auto p-4">
|
||||
{works.length === 0 ? (
|
||||
<p className="py-12 text-center text-sm text-[#747168]">
|
||||
Actionable messages will appear here.
|
||||
</p>
|
||||
) : null}
|
||||
{works.map((work) => (
|
||||
<WorkCard
|
||||
key={work._id}
|
||||
onSourceSelect={revealSourceMessage}
|
||||
slice={slice}
|
||||
work={work}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
};
|
||||
112
apps/web/src/components/workspace/conversation-composer.tsx
Normal file
112
apps/web/src/components/workspace/conversation-composer.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import { ImagePlus, LoaderCircle, Send } from "lucide-react";
|
||||
import { useRef } from "react";
|
||||
|
||||
import { PendingChatAttachments } from "@/components/chat/chat-attachments";
|
||||
import { useChatImages } from "@/hooks/chat/use-chat-images";
|
||||
import type { WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
export const ConversationComposer = ({
|
||||
draft,
|
||||
onDraftChange,
|
||||
workspace,
|
||||
}: {
|
||||
readonly draft: string;
|
||||
readonly onDraftChange: (draft: string) => void;
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => {
|
||||
const imageInput = useRef<HTMLInputElement>(null);
|
||||
const attachments = useChatImages();
|
||||
const busy =
|
||||
workspace.agent.status === "submitted" ||
|
||||
workspace.agent.status === "streaming";
|
||||
|
||||
const send = async () => {
|
||||
const message = draft.trim();
|
||||
if (!message || busy) {
|
||||
return;
|
||||
}
|
||||
await workspace.agent.sendMessage(message, {
|
||||
images: attachments.images.map((image) => image.file),
|
||||
});
|
||||
onDraftChange("");
|
||||
attachments.clear();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-t border-[#d7d3c7] bg-[#faf9f4] p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
|
||||
{attachments.images.length > 0 ? (
|
||||
<div className="mx-auto max-w-2xl">
|
||||
<PendingChatAttachments
|
||||
images={attachments.images}
|
||||
onRemove={attachments.handleRemove}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{workspace.agent.error ? (
|
||||
<p className="mx-auto mb-2 max-w-2xl text-xs text-red-700">
|
||||
{workspace.agent.error.message}
|
||||
</p>
|
||||
) : null}
|
||||
{attachments.error ? (
|
||||
<p className="mx-auto mb-2 max-w-2xl text-xs text-red-700">
|
||||
{attachments.error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mx-auto flex max-w-2xl items-end gap-2">
|
||||
<input
|
||||
accept="image/*"
|
||||
aria-label="Attach images"
|
||||
className="sr-only"
|
||||
multiple
|
||||
onChange={(event) => {
|
||||
attachments.addFiles(event.target.files);
|
||||
event.target.value = "";
|
||||
}}
|
||||
ref={imageInput}
|
||||
type="file"
|
||||
/>
|
||||
<Button
|
||||
aria-label="Attach images"
|
||||
className="size-11 shrink-0"
|
||||
disabled={busy}
|
||||
onClick={() => imageInput.current?.click()}
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<ImagePlus className="size-4" />
|
||||
</Button>
|
||||
<textarea
|
||||
aria-label="Message Zopu"
|
||||
className="max-h-32 min-h-11 flex-1 resize-none border border-[#c9c5b9] bg-white px-3 py-2.5 text-sm outline-none focus:border-[#55564e]"
|
||||
disabled={busy}
|
||||
onChange={(event) => onDraftChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}
|
||||
}}
|
||||
placeholder="Describe an outcome or problem…"
|
||||
rows={1}
|
||||
value={draft}
|
||||
/>
|
||||
<Button
|
||||
aria-label="Send message"
|
||||
className="size-11 shrink-0"
|
||||
disabled={!draft.trim() || busy}
|
||||
onClick={() => void send()}
|
||||
size="icon"
|
||||
type="button"
|
||||
>
|
||||
{busy ? (
|
||||
<LoaderCircle className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
108
apps/web/src/components/workspace/conversation-feed.tsx
Normal file
108
apps/web/src/components/workspace/conversation-feed.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { projectWorkNotices } from "@code/primitives/work";
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
} from "@code/ui/components/ai-elements/conversation";
|
||||
import { MessageSquareText } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { ChatMessage } from "@/components/chat/chat-message";
|
||||
import { ChatThinkingResponse } from "@/components/chat/chat-thinking-response";
|
||||
import { buildWorkspaceTimeline } from "@/lib/workspace/presentation";
|
||||
import type { WorkRecord, WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
import { WorkCard } from "./work-card";
|
||||
|
||||
const ConversationLoading = () => (
|
||||
<output
|
||||
aria-label="Loading conversation"
|
||||
className="mx-auto flex min-h-[55vh] w-full max-w-md flex-col justify-center gap-4"
|
||||
>
|
||||
<span className="h-16 w-4/5 animate-pulse rounded-sm bg-[#e3e0d5]" />
|
||||
<span className="ml-auto h-12 w-3/5 animate-pulse rounded-sm bg-[#dedbd0]" />
|
||||
<span className="h-24 w-full animate-pulse rounded-sm bg-[#e3e0d5]" />
|
||||
<span className="sr-only">Loading conversation…</span>
|
||||
</output>
|
||||
);
|
||||
|
||||
const ConversationEmptyState = () => (
|
||||
<div className="grid min-h-[55vh] place-items-center text-center">
|
||||
<div>
|
||||
<MessageSquareText className="mx-auto size-7 text-[#8a887f]" />
|
||||
<h1 className="mt-4 text-xl font-semibold">What should move forward?</h1>
|
||||
<p className="mx-auto mt-2 max-w-sm text-sm leading-6 text-[#69675f]">
|
||||
Describe an outcome or problem. Casual conversation stays conversation.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ConversationFeed = ({
|
||||
highlightedMessageId,
|
||||
onSourceSelect,
|
||||
workspace,
|
||||
}: {
|
||||
readonly highlightedMessageId?: string;
|
||||
readonly onSourceSelect: (rawText: string) => void;
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => {
|
||||
const works = workspace.works ?? [];
|
||||
const workById = new Map(
|
||||
works.map((work) => [String(work._id), work] as const)
|
||||
);
|
||||
const notices = projectWorkNotices(works);
|
||||
const timeline = useMemo(
|
||||
() => buildWorkspaceTimeline(workspace.agent.messages, notices),
|
||||
[notices, workspace.agent.messages]
|
||||
);
|
||||
|
||||
return (
|
||||
<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">
|
||||
{!workspace.agent.historyReady && timeline.length === 0 ? (
|
||||
<ConversationLoading />
|
||||
) : null}
|
||||
{workspace.agent.historyReady && timeline.length === 0 ? (
|
||||
<ConversationEmptyState />
|
||||
) : null}
|
||||
{timeline.map((item) => {
|
||||
if (item.kind === "work") {
|
||||
const work = workById.get(item.notice.workId) as
|
||||
| WorkRecord
|
||||
| undefined;
|
||||
return work ? (
|
||||
<div
|
||||
className="chat-message ml-7"
|
||||
key={`notice-${item.notice.eventId}`}
|
||||
>
|
||||
<p className="mb-2 text-[10px] font-semibold uppercase text-[#65713a]">
|
||||
Work proposed from this conversation
|
||||
</p>
|
||||
<div className="rounded-sm">
|
||||
<span className="sr-only">Proposed Work</span>
|
||||
<WorkCard
|
||||
onSourceSelect={onSourceSelect}
|
||||
work={work}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={`rounded-sm transition-colors duration-300 ${highlightedMessageId === item.message.id ? "bg-[#dcff68]/70 ring-2 ring-[#7f9130] ring-offset-4 ring-offset-[#f2f0e7]" : ""}`}
|
||||
id={`workspace-message-${item.message.id}`}
|
||||
key={item.message.id}
|
||||
>
|
||||
<ChatMessage message={item.message} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{workspace.agent.status === "submitted" ? (
|
||||
<ChatThinkingResponse />
|
||||
) : null}
|
||||
</ConversationContent>
|
||||
</Conversation>
|
||||
);
|
||||
};
|
||||
50
apps/web/src/components/workspace/project-connect-form.tsx
Normal file
50
apps/web/src/components/workspace/project-connect-form.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import { FolderGit2, LoaderCircle } from "lucide-react";
|
||||
|
||||
import type { WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
export const ProjectConnectForm = ({
|
||||
workspace,
|
||||
}: {
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => (
|
||||
<main className="grid min-h-svh place-items-center bg-[#f2f0e7] px-5 text-[#20201d]">
|
||||
<form
|
||||
className="w-full max-w-sm"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void workspace.connectRepository();
|
||||
}}
|
||||
>
|
||||
<span className="grid size-11 place-items-center bg-[#20201d] text-white">
|
||||
<FolderGit2 className="size-5" />
|
||||
</span>
|
||||
<h1 className="mt-6 text-2xl font-semibold">Connect a project</h1>
|
||||
<p className="mt-2 text-sm leading-6 text-[#68665e]">
|
||||
Turn actionable project conversation into proposed Work with exact
|
||||
provenance.
|
||||
</p>
|
||||
<input
|
||||
aria-label="Public Git repository URL"
|
||||
className="mt-6 h-12 w-full border border-[#c9c5b9] bg-[#fffefa] px-3 text-sm outline-none focus:border-[#55564e]"
|
||||
onChange={(event) => workspace.setRepository(event.target.value)}
|
||||
placeholder="https://github.com/owner/repository"
|
||||
required
|
||||
value={workspace.repository}
|
||||
/>
|
||||
{workspace.error ? (
|
||||
<p className="mt-2 text-xs text-red-700">{workspace.error.message}</p>
|
||||
) : null}
|
||||
<Button
|
||||
className="mt-3 h-12 w-full"
|
||||
disabled={workspace.pending}
|
||||
type="submit"
|
||||
>
|
||||
{workspace.pending ? (
|
||||
<LoaderCircle className="size-4 animate-spin" />
|
||||
) : null}
|
||||
{workspace.pending ? "Connecting" : "Connect project"}
|
||||
</Button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
63
apps/web/src/components/workspace/project-header.tsx
Normal file
63
apps/web/src/components/workspace/project-header.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import { Menu, Settings } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
import { ProjectSettingsPanel } from "./project-settings-panel";
|
||||
|
||||
export const ProjectHeader = ({
|
||||
onOpenDrawer,
|
||||
workspace,
|
||||
}: {
|
||||
readonly onOpenDrawer: () => void;
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => {
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const works = workspace.works ?? [];
|
||||
|
||||
return (
|
||||
<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"
|
||||
className="block h-7 max-w-full border-0 bg-transparent pr-7 text-sm font-semibold text-[#20201d] outline-none"
|
||||
onChange={(event) => workspace.selectProject(event.target.value)}
|
||||
value={workspace.selectedProject?.id ?? ""}
|
||||
>
|
||||
{(workspace.projects ?? []).map((project) => (
|
||||
<option key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-[10px] uppercase text-[#858277]">
|
||||
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={onOpenDrawer}
|
||||
type="button"
|
||||
>
|
||||
<Menu className="size-4" /> Work{" "}
|
||||
{workspace.works === undefined ? "…" : works.length}
|
||||
</button>
|
||||
{settingsOpen ? (
|
||||
<ProjectSettingsPanel
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
workspace={workspace}
|
||||
/>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
};
|
||||
100
apps/web/src/components/workspace/project-settings-panel.tsx
Normal file
100
apps/web/src/components/workspace/project-settings-panel.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import { AlertTriangle, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
export const ProjectSettingsPanel = ({
|
||||
onClose,
|
||||
workspace,
|
||||
}: {
|
||||
readonly onClose: () => void;
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => {
|
||||
const [serverUrl, setServerUrl] = useState("https://git.openputer.com");
|
||||
const [username, setUsername] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const handleClearOperationError = () => workspace.clearOperationError();
|
||||
|
||||
return (
|
||||
<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={onClose} type="button">
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-[#747168]">
|
||||
{workspace.projectGitConnection
|
||||
? `${workspace.projectGitConnection.provider} · ${workspace.projectGitConnection.serverUrl}`
|
||||
: "No Git credentials attached"}
|
||||
</p>
|
||||
{workspace.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">
|
||||
{workspace.operationError.message}
|
||||
</span>
|
||||
<button
|
||||
aria-label="Dismiss error"
|
||||
className="shrink-0"
|
||||
onClick={handleClearOperationError}
|
||||
type="button"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void workspace.authorizeGithub()}
|
||||
>
|
||||
Authorize GitHub
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => void workspace.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) => setServerUrl(event.target.value)}
|
||||
value={serverUrl}
|
||||
/>
|
||||
<input
|
||||
aria-label="Gitea username"
|
||||
className="h-9 w-full border px-2 text-xs"
|
||||
onChange={(event) => setUsername(event.target.value)}
|
||||
placeholder="Username (optional)"
|
||||
value={username}
|
||||
/>
|
||||
<input
|
||||
aria-label="Gitea access token"
|
||||
className="h-9 w-full border px-2 text-xs"
|
||||
onChange={(event) => setToken(event.target.value)}
|
||||
placeholder="Personal access token"
|
||||
type="password"
|
||||
value={token}
|
||||
/>
|
||||
<Button
|
||||
className="w-full"
|
||||
disabled={!token.trim()}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void workspace.connectGitea({
|
||||
serverUrl,
|
||||
token,
|
||||
username: username || undefined,
|
||||
});
|
||||
setToken("");
|
||||
}}
|
||||
>
|
||||
Connect Gitea
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
123
apps/web/src/components/workspace/project-workspace-page.tsx
Normal file
123
apps/web/src/components/workspace/project-workspace-page.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import { useProjectWorkspace } from "@/hooks/workspace/use-project-workspace";
|
||||
import { useVisualViewportStyle } from "@/hooks/workspace/use-visual-viewport";
|
||||
import { findSourceMessageTarget } from "@/lib/workspace/presentation";
|
||||
|
||||
import { ConversationComposer } from "./conversation-composer";
|
||||
import { ConversationFeed } from "./conversation-feed";
|
||||
import { ProjectConnectForm } from "./project-connect-form";
|
||||
import { ProjectHeader } from "./project-header";
|
||||
import { WorkFeed } from "./work-feed";
|
||||
|
||||
const ProjectLoading = () => (
|
||||
<main className="grid min-h-svh place-items-center bg-[#f2f0e7]">
|
||||
<span className="size-5 animate-spin rounded-full border-2 border-[#20201d] border-t-transparent" />
|
||||
</main>
|
||||
);
|
||||
|
||||
export const ProjectWorkspacePage = () => {
|
||||
const workspace = useProjectWorkspace();
|
||||
const viewportStyle = useVisualViewportStyle();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [highlightedMessageId, setHighlightedMessageId] = useState<string>();
|
||||
const highlightTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
if (workspace.projects === undefined) {
|
||||
return <ProjectLoading />;
|
||||
}
|
||||
if (!workspace.selectedProject) {
|
||||
return <ProjectConnectForm workspace={workspace} />;
|
||||
}
|
||||
|
||||
const works = workspace.works ?? [];
|
||||
const revealSourceMessage = (rawText: string) => {
|
||||
const messageId = findSourceMessageTarget(
|
||||
workspace.agent.messages,
|
||||
rawText
|
||||
);
|
||||
if (!messageId) {
|
||||
return;
|
||||
}
|
||||
setDrawerOpen(false);
|
||||
setHighlightedMessageId(messageId);
|
||||
if (highlightTimer.current) {
|
||||
clearTimeout(highlightTimer.current);
|
||||
}
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.querySelector(`#workspace-message-${CSS.escape(messageId)}`)
|
||||
?.scrollIntoView({ behavior: "smooth", block: "center" })
|
||||
);
|
||||
highlightTimer.current = setTimeout(
|
||||
() => setHighlightedMessageId(undefined),
|
||||
1800
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<main
|
||||
className="workspace-surface fixed inset-x-0 top-0 flex min-h-0 overflow-hidden bg-[#f2f0e7] text-[#20201d]"
|
||||
style={viewportStyle}
|
||||
>
|
||||
<section className="flex min-w-0 flex-1 flex-col">
|
||||
<ProjectHeader
|
||||
onOpenDrawer={() => setDrawerOpen(true)}
|
||||
workspace={workspace}
|
||||
/>
|
||||
<ConversationFeed
|
||||
highlightedMessageId={highlightedMessageId}
|
||||
onSourceSelect={revealSourceMessage}
|
||||
workspace={workspace}
|
||||
/>
|
||||
<ConversationComposer
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</section>
|
||||
<aside className="hidden w-[380px] shrink-0 overflow-y-auto border-l border-[#d7d3c7] bg-[#e9e7de] p-4 lg:block">
|
||||
<h2 className="text-sm font-semibold">Proposed Work</h2>
|
||||
<p className="mb-4 text-xs text-[#747168]">
|
||||
{works.length} durable outcomes
|
||||
</p>
|
||||
<WorkFeed
|
||||
onSourceSelect={revealSourceMessage}
|
||||
works={works}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</aside>
|
||||
{drawerOpen ? (
|
||||
<div className="fixed inset-0 z-50 bg-black/30 lg:hidden">
|
||||
<button
|
||||
aria-label="Close Work drawer"
|
||||
className="absolute inset-0"
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
type="button"
|
||||
/>
|
||||
<section className="absolute inset-y-0 right-0 flex w-[min(92vw,380px)] flex-col bg-[#e9e7de] shadow-2xl">
|
||||
<header className="flex h-14 items-center border-b border-[#cfcbc0] px-4">
|
||||
<h2 className="flex-1 text-sm font-semibold">Proposed Work</h2>
|
||||
<button
|
||||
aria-label="Close Work drawer"
|
||||
className="grid size-9 place-items-center"
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
type="button"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<WorkFeed
|
||||
onSourceSelect={revealSourceMessage}
|
||||
works={works}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
};
|
||||
395
apps/web/src/components/workspace/work-card.tsx
Normal file
395
apps/web/src/components/workspace/work-card.tsx
Normal file
@@ -0,0 +1,395 @@
|
||||
import { Button } from "@code/ui/components/button";
|
||||
import {
|
||||
AlertTriangle,
|
||||
Check,
|
||||
ChevronRight,
|
||||
FileCode2,
|
||||
Hammer,
|
||||
Play,
|
||||
RotateCcw,
|
||||
ScrollText,
|
||||
Sparkles,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { changedFilesFor } from "@/lib/workspace/types";
|
||||
import type { WorkRecord, WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
interface WorkCardProps {
|
||||
readonly onSourceSelect: (rawText: string) => void;
|
||||
readonly work: WorkRecord;
|
||||
readonly workspace: WorkspaceState;
|
||||
}
|
||||
|
||||
const starterDefinition = (work: WorkRecord) => ({
|
||||
acceptanceCriteria: ["The requested outcome is observable and documented"],
|
||||
affectedUsers: ["Project users"],
|
||||
assumptions: [],
|
||||
constraints: [],
|
||||
desiredOutcome: work.objective,
|
||||
inScope: [work.objective],
|
||||
outOfScope: ["Unrelated product changes"],
|
||||
problem: work.objective,
|
||||
questions: [],
|
||||
requiredArtifacts: ["Simulation activity and terminal outcome"],
|
||||
risk: "medium",
|
||||
});
|
||||
|
||||
const starterDesign = (work: WorkRecord) => ({
|
||||
architectureSummary:
|
||||
"Validate the approved Definition, then exercise one deterministic fake slice.",
|
||||
callFlowDelta: [
|
||||
"Work -> Run -> Attempt -> normalized events -> terminal outcome",
|
||||
],
|
||||
concerns: [],
|
||||
evidenceRequirements: ["Terminal Run classification"],
|
||||
fileTreeDelta: [],
|
||||
impactMap: {
|
||||
files: [],
|
||||
modules: [],
|
||||
risks: [],
|
||||
summary: "Compact vertical-slice simulation",
|
||||
},
|
||||
invariants: [
|
||||
"Simulation never claims implementation",
|
||||
"Every Attempt reaches a terminal classification",
|
||||
],
|
||||
keyInterfaces: ["HarnessRuntime", "AttemptOutcome"],
|
||||
slices: [
|
||||
{
|
||||
codeBoundaries: ["workExecution"],
|
||||
dependsOn: [],
|
||||
evidenceRequirements: ["Normalized activity events"],
|
||||
id: "deterministic-simulation",
|
||||
objective: work.objective,
|
||||
observableBehavior: "A terminal fake Run is visible",
|
||||
reviewRequired: false,
|
||||
title: "Deterministic simulation",
|
||||
verification: ["Run completes with a terminal classification"],
|
||||
},
|
||||
],
|
||||
tradeoffs: ["Fake runtime proves contract before sandbox integration"],
|
||||
});
|
||||
|
||||
// oxlint-disable-next-line complexity -- this card intentionally coordinates review actions and run evidence.
|
||||
export const WorkCard = ({
|
||||
onSourceSelect,
|
||||
work,
|
||||
workspace,
|
||||
}: 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 [latestRun] = work.runs;
|
||||
const openQuestions =
|
||||
work.definition?.questions?.filter((question) => question.status === "open")
|
||||
.length ?? 0;
|
||||
|
||||
return (
|
||||
<article className="border border-[#d7d3c7] bg-[#fffefa] p-4 text-[#20201d] shadow-[0_10px_30px_rgba(30,30,20,0.06)]">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="grid size-8 shrink-0 place-items-center bg-[#dcff68]">
|
||||
<Sparkles className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[10px] font-semibold uppercase text-[#65713a]">
|
||||
Proposed Work
|
||||
</p>
|
||||
<h2 className="mt-1 text-[15px] font-semibold leading-5">
|
||||
{work.title}
|
||||
</h2>
|
||||
<p className="mt-1.5 text-[13px] leading-5 text-[#626057]">
|
||||
{work.objective}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="mt-3 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs text-[#69675e]"
|
||||
onClick={() => setSourcesOpen((open) => !open)}
|
||||
type="button"
|
||||
>
|
||||
<span>
|
||||
{sources.length} exact source{" "}
|
||||
{sources.length === 1 ? "message" : "messages"}
|
||||
</span>
|
||||
<ChevronRight
|
||||
className={`size-4 transition-transform ${sourcesOpen ? "rotate-90" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
className="mt-2 flex w-full items-center justify-between border-t border-[#e7e3d9] pt-3 text-left text-xs font-medium text-[#20201d]"
|
||||
onClick={() => setExpanded((open) => !open)}
|
||||
type="button"
|
||||
>
|
||||
<span>{expanded ? "Hide Work details" : "Open Work details"}</span>
|
||||
<ChevronRight
|
||||
className={`size-4 transition-transform ${expanded ? "rotate-90" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
{sourcesOpen ? (
|
||||
<div className="mt-3 space-y-2">
|
||||
{sources.map((source) => (
|
||||
<button
|
||||
className="flex w-full items-start gap-2 border-l-2 border-[#a8b750] bg-[#f4f2e9] px-3 py-2 text-left text-xs leading-5 hover:bg-[#ece9dd]"
|
||||
key={source.messageId}
|
||||
onClick={() => onSourceSelect(source.rawText)}
|
||||
type="button"
|
||||
>
|
||||
<span className="min-w-0 flex-1">{source.rawText}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{expanded ? (
|
||||
<div className="mt-4 space-y-4 border-t border-[#e7e3d9] pt-4 text-xs">
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Outcome
|
||||
</p>
|
||||
<p className="mt-1 leading-5 text-[#626057]">{work.objective}</p>
|
||||
<p className="mt-2 text-[#747168]">
|
||||
Risk: {work.definition?.risk ?? "not defined"}
|
||||
</p>
|
||||
{openQuestions > 0 ? (
|
||||
<p className="mt-1 text-amber-800">
|
||||
{openQuestions} open question(s)
|
||||
</p>
|
||||
) : null}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "proposed" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => void workspace.requestDefinition(work._id)}
|
||||
>
|
||||
<Sparkles className="size-3.5" /> Define
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "defining" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void workspace.saveDefinition(
|
||||
work._id,
|
||||
starterDefinition(work)
|
||||
)
|
||||
}
|
||||
>
|
||||
<Hammer className="size-3.5" /> Save definition
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "awaiting-definition-approval" &&
|
||||
work.definitionVersion ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void workspace.approveDefinition(
|
||||
work._id,
|
||||
work.definitionVersion as number
|
||||
)
|
||||
}
|
||||
>
|
||||
<Check className="size-3.5" /> Approve
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Design
|
||||
</p>
|
||||
<p className="mt-1 leading-5 text-[#626057]">
|
||||
{work.design?.architectureSummary ?? "No Design Packet yet."}
|
||||
</p>
|
||||
{work.design?.slices?.map((item) => (
|
||||
<p className="mt-1 text-[#747168]" key={item.id}>
|
||||
{item.title}: {item.observableBehavior}
|
||||
</p>
|
||||
))}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "designing" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void workspace.saveDesign(work._id, starterDesign(work))
|
||||
}
|
||||
>
|
||||
<Hammer className="size-3.5" /> Save design
|
||||
</Button>
|
||||
) : null}
|
||||
{work.status === "awaiting-design-approval" &&
|
||||
work.definitionApprovalVersion &&
|
||||
work.designVersion ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void workspace.approveDesign(
|
||||
work._id,
|
||||
work.definitionApprovalVersion as number,
|
||||
work.designVersion as number
|
||||
)
|
||||
}
|
||||
>
|
||||
<Check className="size-3.5" /> Approve design
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<p className="font-semibold uppercase tracking-wide text-[#65713a]">
|
||||
Build
|
||||
</p>
|
||||
{workspace.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">
|
||||
{workspace.operationError.message}
|
||||
</span>
|
||||
<button
|
||||
aria-label="Dismiss error"
|
||||
className="shrink-0"
|
||||
onClick={() => workspace.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) => (
|
||||
<div key={artifact._id} className="space-y-1">
|
||||
<p className="font-medium">
|
||||
{artifact.uri ? (
|
||||
<a
|
||||
className="underline"
|
||||
href={artifact.uri}
|
||||
rel="noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{artifact.title}
|
||||
</a>
|
||||
) : (
|
||||
artifact.title
|
||||
)}
|
||||
</p>
|
||||
{changedFilesFor(artifact).length > 0 ? (
|
||||
<ul className="space-y-0.5">
|
||||
{changedFilesFor(artifact).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 implementation Run yet.</p>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{work.status === "ready" ? (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!workspace.projectGitConnection}
|
||||
onClick={() => void workspace.startExecution(work._id)}
|
||||
>
|
||||
<Play className="size-3.5" /> Run
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void workspace.startSimulation(work._id, "success")
|
||||
}
|
||||
>
|
||||
<Play className="size-3.5" /> Simulate
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{latestRun?.status === "running" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
void (latestRun.executionKind === "real"
|
||||
? workspace.cancelExecution(latestRun._id)
|
||||
: workspace.cancelSimulation(latestRun._id))
|
||||
}
|
||||
>
|
||||
<X className="size-3.5" /> Cancel
|
||||
</Button>
|
||||
) : null}
|
||||
{latestRun?.executionKind !== "real" &&
|
||||
latestRun?.status === "terminal" &&
|
||||
latestRun.terminalClassification === "RetryableFailure" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void workspace.retrySimulation(latestRun._id)}
|
||||
>
|
||||
<RotateCcw className="size-3.5" /> Retry
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
};
|
||||
29
apps/web/src/components/workspace/work-feed.tsx
Normal file
29
apps/web/src/components/workspace/work-feed.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { WorkRecord, WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
import { WorkCard } from "./work-card";
|
||||
|
||||
export const WorkFeed = ({
|
||||
onSourceSelect,
|
||||
works,
|
||||
workspace,
|
||||
}: {
|
||||
readonly onSourceSelect: (rawText: string) => void;
|
||||
readonly works: readonly WorkRecord[];
|
||||
readonly workspace: WorkspaceState;
|
||||
}) => (
|
||||
<div className="space-y-3">
|
||||
{works.length === 0 ? (
|
||||
<p className="py-12 text-center text-sm text-[#747168]">
|
||||
Actionable messages will appear here.
|
||||
</p>
|
||||
) : null}
|
||||
{works.map((work) => (
|
||||
<WorkCard
|
||||
key={work._id}
|
||||
onSourceSelect={onSourceSelect}
|
||||
work={work}
|
||||
workspace={workspace}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
@@ -7,58 +7,17 @@ import { useMemo, useState } from "react";
|
||||
|
||||
import { useOrganizationChatAgent } from "@/hooks/chat/use-chat-agent";
|
||||
import { usePersonalOrganization } from "@/hooks/use-personal-organization";
|
||||
import type { WorkRecord, WorkspaceState } from "@/lib/workspace/types";
|
||||
|
||||
const toError = (error: unknown) =>
|
||||
error instanceof Error ? error : new Error(String(error));
|
||||
|
||||
interface WorkRecord {
|
||||
readonly _id: Id<"works">;
|
||||
readonly title: string;
|
||||
readonly objective: string;
|
||||
readonly status: string;
|
||||
readonly definitionVersion?: number;
|
||||
readonly definitionApprovalVersion?: number;
|
||||
readonly designVersion?: number;
|
||||
readonly designApprovalVersion?: number;
|
||||
readonly signals: readonly {
|
||||
sources: readonly { messageId: string; rawText: string }[];
|
||||
}[];
|
||||
readonly events: readonly { _id: string; createdAt: number; kind: string }[];
|
||||
readonly definitions: readonly unknown[];
|
||||
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;
|
||||
occurredAt: number;
|
||||
}[];
|
||||
readonly baseRevision?: string;
|
||||
readonly candidateRevision?: string;
|
||||
readonly executionKind?: string;
|
||||
_id: Id<"workRuns">;
|
||||
status: string;
|
||||
terminalClassification?: string;
|
||||
terminalSummary?: string;
|
||||
}[];
|
||||
readonly definition: {
|
||||
risk?: string;
|
||||
questions?: { status: string }[];
|
||||
} | null;
|
||||
readonly design: {
|
||||
architectureSummary?: string;
|
||||
slices?: { id: string; title: string; observableBehavior: string }[];
|
||||
} | null;
|
||||
}
|
||||
type ExecutionScenario =
|
||||
| "success"
|
||||
| "transient-failure-then-success"
|
||||
| "needs-input"
|
||||
| "permanent-failure"
|
||||
| "cancelled";
|
||||
|
||||
const workListRef = makeFunctionReference<
|
||||
"query",
|
||||
@@ -92,16 +51,7 @@ const approveDesignRef = makeFunctionReference<
|
||||
>("workPlanning:approveDesign");
|
||||
const startSimulationRef = makeFunctionReference<
|
||||
"mutation",
|
||||
{
|
||||
workId: Id<"works">;
|
||||
scenario:
|
||||
| "success"
|
||||
| "transient-failure-then-success"
|
||||
| "needs-input"
|
||||
| "permanent-failure"
|
||||
| "cancelled";
|
||||
sliceId?: string;
|
||||
},
|
||||
{ workId: Id<"works">; scenario: ExecutionScenario; sliceId?: string },
|
||||
unknown
|
||||
>("workExecution:startSimulatedExecution");
|
||||
const cancelSimulationRef = makeFunctionReference<
|
||||
@@ -160,13 +110,7 @@ const attachGitConnectionRef = makeFunctionReference<
|
||||
unknown
|
||||
>("gitConnectionData:attachToProject");
|
||||
|
||||
const authorizeGithub = () =>
|
||||
authClient.signIn.social({
|
||||
callbackURL: window.location.href,
|
||||
provider: "github",
|
||||
});
|
||||
|
||||
export const useSliceOne = () => {
|
||||
export const useProjectWorkspace = (): WorkspaceState => {
|
||||
const organization = usePersonalOrganization();
|
||||
const projects = useQuery(
|
||||
api.projects.list,
|
||||
@@ -179,6 +123,8 @@ export const useSliceOne = () => {
|
||||
const [repository, setRepository] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<Error>();
|
||||
const [operationError, setOperationError] = useState<Error>();
|
||||
|
||||
const selectedProjectStillExists = projects?.some(
|
||||
(project) => project.id === (selectedProjectId as unknown as string)
|
||||
);
|
||||
@@ -218,6 +164,16 @@ export const useSliceOne = () => {
|
||||
[activeProjectId, projects]
|
||||
);
|
||||
|
||||
const runOperation = async <T>(operation: () => Promise<T>): Promise<T> => {
|
||||
setOperationError(undefined);
|
||||
try {
|
||||
return await operation();
|
||||
} catch (caughtError) {
|
||||
setOperationError(toError(caughtError));
|
||||
throw caughtError;
|
||||
}
|
||||
};
|
||||
|
||||
const connectRepository = async () => {
|
||||
const repositoryUrl = repository.trim();
|
||||
if (!repositoryUrl || pending) {
|
||||
@@ -236,41 +192,6 @@ export const useSliceOne = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const selectProject = (projectId: string) => {
|
||||
setSelectedProjectId(projectId as unknown as Id<"projects">);
|
||||
};
|
||||
|
||||
const requestDefinition = (workId: Id<"works">) =>
|
||||
requestDefinitionMutation({ workId });
|
||||
const saveDefinition = (workId: Id<"works">, payload: unknown) =>
|
||||
saveDefinitionMutation({ payloadJson: JSON.stringify(payload), workId });
|
||||
const approveDefinition = (workId: Id<"works">, version: number) =>
|
||||
approveDefinitionMutation({ version, workId });
|
||||
const saveDesign = (workId: Id<"works">, payload: unknown) =>
|
||||
saveDesignMutation({ payloadJson: JSON.stringify(payload), workId });
|
||||
const approveDesign = (
|
||||
workId: Id<"works">,
|
||||
definitionVersion: number,
|
||||
designVersion: number
|
||||
) => approveDesignMutation({ definitionVersion, designVersion, workId });
|
||||
const startSimulation = (
|
||||
workId: Id<"works">,
|
||||
scenario:
|
||||
| "success"
|
||||
| "transient-failure-then-success"
|
||||
| "needs-input"
|
||||
| "permanent-failure"
|
||||
| "cancelled",
|
||||
sliceId?: string
|
||||
) => startSimulationMutation({ scenario, sliceId, workId });
|
||||
const cancelSimulation = (runId: Id<"workRuns">) =>
|
||||
cancelSimulationMutation({ runId });
|
||||
const retrySimulation = (runId: Id<"workRuns">) =>
|
||||
retrySimulationMutation({ runId });
|
||||
const startExecution = (workId: Id<"works">, sliceId?: string) =>
|
||||
startExecutionMutation({ sliceId, workId });
|
||||
const cancelExecution = (runId: Id<"workRuns">) =>
|
||||
cancelExecutionMutation({ runId });
|
||||
const attachConnection = async (connectionId: Id<"gitConnections">) => {
|
||||
if (!activeProjectId) {
|
||||
throw new Error("Select a project first");
|
||||
@@ -280,44 +201,76 @@ export const useSliceOne = () => {
|
||||
projectId: activeProjectId,
|
||||
});
|
||||
};
|
||||
const connectGitea = async (input: {
|
||||
|
||||
const connectGitea = (input: {
|
||||
serverUrl: string;
|
||||
token: string;
|
||||
username?: string;
|
||||
}) => {
|
||||
const result = await connectGiteaAction(input);
|
||||
await attachConnection(result.connectionId);
|
||||
};
|
||||
const connectLinkedGithub = async () => {
|
||||
const result = await connectGithubAction({});
|
||||
await attachConnection(result.connectionId);
|
||||
};
|
||||
}) =>
|
||||
runOperation(async () => {
|
||||
const result = await connectGiteaAction(input);
|
||||
await attachConnection(result.connectionId);
|
||||
});
|
||||
|
||||
const connectLinkedGithub = () =>
|
||||
runOperation(async () => {
|
||||
const result = await connectGithubAction({});
|
||||
await attachConnection(result.connectionId);
|
||||
});
|
||||
|
||||
return {
|
||||
agent,
|
||||
approveDefinition,
|
||||
approveDesign,
|
||||
authorizeGithub,
|
||||
cancelExecution,
|
||||
cancelSimulation,
|
||||
approveDefinition: (workId: Id<"works">, version: number) =>
|
||||
approveDefinitionMutation({ version, workId }),
|
||||
approveDesign: (
|
||||
workId: Id<"works">,
|
||||
definitionVersion: number,
|
||||
designVersion: number
|
||||
) => approveDesignMutation({ definitionVersion, designVersion, workId }),
|
||||
authorizeGithub: () =>
|
||||
authClient.signIn.social({
|
||||
callbackURL: window.location.href,
|
||||
provider: "github",
|
||||
}),
|
||||
cancelExecution: (runId: Id<"workRuns">) =>
|
||||
runOperation(() => cancelExecutionMutation({ runId })),
|
||||
cancelSimulation: (runId: Id<"workRuns">) =>
|
||||
runOperation(() => cancelSimulationMutation({ runId })),
|
||||
clearOperationError: () => setOperationError(undefined),
|
||||
connectGitea,
|
||||
connectLinkedGithub,
|
||||
connectRepository,
|
||||
error,
|
||||
gitConnections,
|
||||
operationError,
|
||||
pending,
|
||||
projectGitConnection,
|
||||
projects,
|
||||
repository,
|
||||
requestDefinition,
|
||||
retrySimulation,
|
||||
saveDefinition,
|
||||
saveDesign,
|
||||
selectProject,
|
||||
selectedProject,
|
||||
requestDefinition: (workId: Id<"works">) =>
|
||||
requestDefinitionMutation({ workId }),
|
||||
retrySimulation: (runId: Id<"workRuns">) =>
|
||||
runOperation(() => retrySimulationMutation({ runId })),
|
||||
saveDefinition: (workId: Id<"works">, payload: unknown) =>
|
||||
saveDefinitionMutation({ payloadJson: JSON.stringify(payload), workId }),
|
||||
saveDesign: (workId: Id<"works">, payload: unknown) =>
|
||||
saveDesignMutation({ payloadJson: JSON.stringify(payload), workId }),
|
||||
selectProject: (projectId: string) =>
|
||||
setSelectedProjectId(projectId as unknown as Id<"projects">),
|
||||
selectedProject: selectedProject
|
||||
? { id: selectedProject.id, name: selectedProject.name }
|
||||
: null,
|
||||
setRepository,
|
||||
startExecution,
|
||||
startSimulation,
|
||||
startExecution: (workId: Id<"works">, sliceId?: string) =>
|
||||
runOperation(() => startExecutionMutation({ sliceId, workId })),
|
||||
startSimulation: (
|
||||
workId: Id<"works">,
|
||||
scenario: ExecutionScenario,
|
||||
sliceId?: string
|
||||
) =>
|
||||
runOperation(() =>
|
||||
startSimulationMutation({ scenario, sliceId, workId })
|
||||
),
|
||||
works,
|
||||
} as const;
|
||||
};
|
||||
};
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import { visualViewportStyle } from "./use-visual-viewport";
|
||||
|
||||
describe("Slice 1 visual viewport", () => {
|
||||
describe("Workspace visual viewport", () => {
|
||||
test("shrinks the application surface to the keyboard-visible height", () => {
|
||||
expect(visualViewportStyle({ height: 500, offsetTop: 0 })).toEqual({
|
||||
height: "500px",
|
||||
@@ -33,7 +33,7 @@ export const useVisualViewportStyle = (): CSSProperties => {
|
||||
});
|
||||
};
|
||||
|
||||
root.classList.add("slice-one-viewport-lock");
|
||||
root.classList.add("workspace-viewport-lock");
|
||||
update();
|
||||
window.addEventListener("resize", update);
|
||||
viewport?.addEventListener("resize", update);
|
||||
@@ -41,7 +41,7 @@ export const useVisualViewportStyle = (): CSSProperties => {
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(animationFrame);
|
||||
root.classList.remove("slice-one-viewport-lock");
|
||||
root.classList.remove("workspace-viewport-lock");
|
||||
window.removeEventListener("resize", update);
|
||||
viewport?.removeEventListener("resize", update);
|
||||
viewport?.removeEventListener("scroll", update);
|
||||
@@ -6,8 +6,8 @@ body {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
html.slice-one-viewport-lock,
|
||||
html.slice-one-viewport-lock body {
|
||||
html.workspace-viewport-lock,
|
||||
html.workspace-viewport-lock body {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
overscroll-behavior: none;
|
||||
@@ -116,9 +116,9 @@ html.slice-one-viewport-lock body {
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.slice-one-surface .chat-markdown,
|
||||
.slice-one-surface .chat-reasoning,
|
||||
.slice-one-surface .thinking-line {
|
||||
.workspace-surface .chat-markdown,
|
||||
.workspace-surface .chat-reasoning,
|
||||
.workspace-surface .thinking-line {
|
||||
color: #232321;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,27 +5,36 @@ import { describe, expect, test } from "vitest";
|
||||
const source = (relativePath: string) =>
|
||||
readFileSync(new URL(relativePath, import.meta.url), "utf-8");
|
||||
|
||||
describe("Slice 1 frontend regression contracts", () => {
|
||||
describe("Workspace frontend regression contracts", () => {
|
||||
test("keeps keyboard resizing on the visual viewport instead of page scroll", () => {
|
||||
const page = source("../../components/slice-one/slice-one-page.tsx");
|
||||
const page = source(
|
||||
"../../components/workspace/project-workspace-page.tsx"
|
||||
);
|
||||
const viewport = source("../../hooks/workspace/use-visual-viewport.ts");
|
||||
const root = source("../../root.tsx");
|
||||
const styles = source("../../index.css");
|
||||
|
||||
expect(root).toContain("interactive-widget=resizes-content");
|
||||
expect(page).toContain("style={viewportStyle}");
|
||||
expect(page).toContain("fixed inset-x-0 top-0");
|
||||
expect(page).not.toContain("slice-one-surface flex h-svh");
|
||||
expect(styles).toContain("html.slice-one-viewport-lock body");
|
||||
expect(viewport).toContain("workspace-viewport-lock");
|
||||
expect(styles).toContain("html.workspace-viewport-lock body");
|
||||
expect(styles).toContain("overflow: hidden");
|
||||
});
|
||||
|
||||
test("keeps the responsive shell shrinkable with a pinned composer", () => {
|
||||
const page = source("../../components/slice-one/slice-one-page.tsx");
|
||||
const page = source(
|
||||
"../../components/workspace/project-workspace-page.tsx"
|
||||
);
|
||||
const feed = source("../../components/workspace/conversation-feed.tsx");
|
||||
const composer = source(
|
||||
"../../components/workspace/conversation-composer.tsx"
|
||||
);
|
||||
|
||||
expect(page).toContain('className="flex min-w-0 flex-1 flex-col"');
|
||||
expect(page).toContain('<Conversation className="min-h-0 flex-1">');
|
||||
expect(page).toContain('className="shrink-0 border-t');
|
||||
expect(page).toContain(
|
||||
expect(feed).toContain('<Conversation className="min-h-0 flex-1">');
|
||||
expect(composer).toContain('className="shrink-0 border-t');
|
||||
expect(composer).toContain(
|
||||
'className="mx-auto flex max-w-2xl items-end gap-2"'
|
||||
);
|
||||
});
|
||||
@@ -3,7 +3,10 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { ConversationMessage } from "@/lib/chat/types";
|
||||
|
||||
import { buildSliceOneTimeline, findSourceMessageTarget } from "./presentation";
|
||||
import {
|
||||
buildWorkspaceTimeline,
|
||||
findSourceMessageTarget,
|
||||
} from "./presentation";
|
||||
|
||||
const textMessage = (
|
||||
id: string,
|
||||
@@ -23,9 +26,9 @@ const notice: WorkNotice = {
|
||||
workId: "work-1",
|
||||
};
|
||||
|
||||
describe("Slice 1 presentation", () => {
|
||||
describe("Workspace presentation", () => {
|
||||
test("places proposed Work after the assistant response to its source", () => {
|
||||
const timeline = buildSliceOneTimeline(
|
||||
const timeline = buildWorkspaceTimeline(
|
||||
[
|
||||
textMessage("user-1", "user", "Build the phone flow."),
|
||||
textMessage("assistant-1", "assistant", "Captured and proposed Work."),
|
||||
@@ -7,14 +7,9 @@ import {
|
||||
} from "@/lib/chat/transforms";
|
||||
import type { ConversationMessage } from "@/lib/chat/types";
|
||||
|
||||
export type SliceTimelineItem =
|
||||
| {
|
||||
readonly kind: "message";
|
||||
readonly message: ConversationMessage;
|
||||
}
|
||||
| { readonly kind: "work"; readonly notice: WorkNotice };
|
||||
import type { WorkspaceTimelineItem } from "./types";
|
||||
|
||||
export const isSliceOneVisibleMessage = (
|
||||
export const isVisibleConversationMessage = (
|
||||
message: ConversationMessage
|
||||
): boolean =>
|
||||
message.role === "user" ||
|
||||
@@ -42,11 +37,11 @@ const targetIndexForNotice = (
|
||||
return responseOffset === -1 ? sourceIndex : sourceIndex + responseOffset + 1;
|
||||
};
|
||||
|
||||
export const buildSliceOneTimeline = (
|
||||
export const buildWorkspaceTimeline = (
|
||||
allMessages: readonly ConversationMessage[],
|
||||
notices: readonly WorkNotice[]
|
||||
): readonly SliceTimelineItem[] => {
|
||||
const messages = allMessages.filter(isSliceOneVisibleMessage);
|
||||
): readonly WorkspaceTimelineItem[] => {
|
||||
const messages = allMessages.filter(isVisibleConversationMessage);
|
||||
const noticesByMessageIndex = new Map<number, WorkNotice[]>();
|
||||
for (const notice of notices) {
|
||||
const targetIndex = targetIndexForNotice(messages, notice);
|
||||
@@ -55,7 +50,7 @@ export const buildSliceOneTimeline = (
|
||||
noticesByMessageIndex.set(targetIndex, atTarget);
|
||||
}
|
||||
|
||||
const timeline: SliceTimelineItem[] = [];
|
||||
const timeline: WorkspaceTimelineItem[] = [];
|
||||
for (const [index, message] of messages.entries()) {
|
||||
timeline.push({ kind: "message", message });
|
||||
for (const notice of noticesByMessageIndex.get(index) ?? []) {
|
||||
163
apps/web/src/lib/workspace/types.ts
Normal file
163
apps/web/src/lib/workspace/types.ts
Normal file
@@ -0,0 +1,163 @@
|
||||
import type { Id } from "@code/backend/convex/_generated/dataModel";
|
||||
import type { WorkNotice } from "@code/primitives/work";
|
||||
|
||||
import type { ConversationMessage } from "@/lib/chat/types";
|
||||
|
||||
export interface WorkRecord {
|
||||
readonly _id: Id<"works">;
|
||||
readonly title: string;
|
||||
readonly objective: string;
|
||||
readonly status: string;
|
||||
readonly definitionVersion?: number;
|
||||
readonly definitionApprovalVersion?: number;
|
||||
readonly designVersion?: number;
|
||||
readonly signals: readonly {
|
||||
readonly sources: readonly { messageId: string; rawText: string }[];
|
||||
}[];
|
||||
readonly runs: readonly WorkRun[];
|
||||
readonly definition: {
|
||||
readonly risk?: string;
|
||||
readonly questions?: readonly { status: string }[];
|
||||
} | null;
|
||||
readonly design: {
|
||||
readonly architectureSummary?: string;
|
||||
readonly slices?: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly observableBehavior: string;
|
||||
}[];
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface WorkRun {
|
||||
readonly artifacts?: readonly WorkArtifact[];
|
||||
readonly attemptEvents?: readonly WorkAttemptEvent[];
|
||||
readonly baseRevision?: string;
|
||||
readonly candidateRevision?: string;
|
||||
readonly executionKind?: string;
|
||||
readonly _id: Id<"workRuns">;
|
||||
readonly status: string;
|
||||
readonly terminalClassification?: string;
|
||||
readonly terminalSummary?: string;
|
||||
}
|
||||
|
||||
export interface WorkArtifact {
|
||||
readonly _id: string;
|
||||
readonly metadataJson: string;
|
||||
readonly title: string;
|
||||
readonly uri?: string;
|
||||
}
|
||||
|
||||
export interface WorkAttemptEvent {
|
||||
readonly _id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export interface GitConnection {
|
||||
readonly id: string;
|
||||
readonly provider: "github" | "gitea";
|
||||
readonly serverUrl: string;
|
||||
readonly username?: string;
|
||||
}
|
||||
|
||||
export interface ProjectListItem {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceState {
|
||||
readonly agent: {
|
||||
readonly error?: Error;
|
||||
readonly historyReady: boolean;
|
||||
readonly messages: readonly ConversationMessage[];
|
||||
readonly sendMessage: (
|
||||
message: string,
|
||||
options?: { readonly images?: readonly File[] }
|
||||
) => Promise<void>;
|
||||
readonly status:
|
||||
| "connecting"
|
||||
| "error"
|
||||
| "idle"
|
||||
| "streaming"
|
||||
| "submitted";
|
||||
};
|
||||
readonly approveDefinition: (
|
||||
workId: Id<"works">,
|
||||
version: number
|
||||
) => Promise<unknown>;
|
||||
readonly approveDesign: (
|
||||
workId: Id<"works">,
|
||||
definitionVersion: number,
|
||||
designVersion: number
|
||||
) => Promise<unknown>;
|
||||
readonly authorizeGithub: () => Promise<unknown>;
|
||||
readonly cancelExecution: (runId: Id<"workRuns">) => Promise<unknown>;
|
||||
readonly cancelSimulation: (runId: Id<"workRuns">) => Promise<unknown>;
|
||||
readonly clearOperationError: () => void;
|
||||
readonly connectGitea: (input: {
|
||||
readonly serverUrl: string;
|
||||
readonly token: string;
|
||||
readonly username?: string;
|
||||
}) => Promise<void>;
|
||||
readonly connectLinkedGithub: () => Promise<void>;
|
||||
readonly connectRepository: () => Promise<void>;
|
||||
readonly error?: Error;
|
||||
readonly gitConnections: readonly GitConnection[] | undefined;
|
||||
readonly operationError?: Error;
|
||||
readonly pending: boolean;
|
||||
readonly projectGitConnection: GitConnection | null | undefined;
|
||||
readonly projects: readonly ProjectListItem[] | undefined;
|
||||
readonly repository: string;
|
||||
readonly requestDefinition: (workId: Id<"works">) => Promise<unknown>;
|
||||
readonly retrySimulation: (runId: Id<"workRuns">) => Promise<unknown>;
|
||||
readonly saveDefinition: (
|
||||
workId: Id<"works">,
|
||||
payload: unknown
|
||||
) => Promise<unknown>;
|
||||
readonly saveDesign: (
|
||||
workId: Id<"works">,
|
||||
payload: unknown
|
||||
) => Promise<unknown>;
|
||||
readonly selectProject: (projectId: string) => void;
|
||||
readonly selectedProject: ProjectListItem | null;
|
||||
readonly setRepository: (value: string) => void;
|
||||
readonly startExecution: (
|
||||
workId: Id<"works">,
|
||||
sliceId?: string
|
||||
) => Promise<unknown>;
|
||||
readonly startSimulation: (
|
||||
workId: Id<"works">,
|
||||
scenario:
|
||||
| "success"
|
||||
| "transient-failure-then-success"
|
||||
| "needs-input"
|
||||
| "permanent-failure"
|
||||
| "cancelled",
|
||||
sliceId?: string
|
||||
) => Promise<unknown>;
|
||||
readonly works: readonly WorkRecord[] | undefined;
|
||||
}
|
||||
|
||||
export type WorkspaceTimelineItem =
|
||||
| { readonly kind: "message"; readonly message: ConversationMessage }
|
||||
| { readonly kind: "work"; readonly notice: WorkNotice };
|
||||
|
||||
export interface ArtifactMetadata {
|
||||
readonly changedFiles?: readonly string[];
|
||||
}
|
||||
|
||||
export const parseArtifactMetadata = (
|
||||
artifact: WorkArtifact
|
||||
): ArtifactMetadata => {
|
||||
if (!artifact.metadataJson) {
|
||||
return {};
|
||||
}
|
||||
try {
|
||||
return JSON.parse(artifact.metadataJson) as ArtifactMetadata;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
export const changedFilesFor = (artifact: WorkArtifact): readonly string[] =>
|
||||
parseArtifactMetadata(artifact).changedFiles ?? [];
|
||||
@@ -7,7 +7,6 @@ export default [
|
||||
route("signup", "./routes/auth/signup/page.tsx"),
|
||||
]),
|
||||
layout("./routes/app/layout.tsx", [
|
||||
index("./routes/app/mobile/page.tsx"),
|
||||
route("dashboard", "./routes/app/dashboard/page.tsx"),
|
||||
index("./routes/app/workspace/page.tsx"),
|
||||
]),
|
||||
] satisfies RouteConfig;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { SliceOnePage } from "@/components/slice-one/slice-one-page";
|
||||
|
||||
export default function Dashboard() {
|
||||
return <SliceOnePage />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import { SliceOnePage } from "@/components/slice-one/slice-one-page";
|
||||
|
||||
export default function MobileLandingRedirect() {
|
||||
return <SliceOnePage />;
|
||||
}
|
||||
5
apps/web/src/routes/app/workspace/page.tsx
Normal file
5
apps/web/src/routes/app/workspace/page.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { ProjectWorkspacePage } from "@/components/workspace/project-workspace-page";
|
||||
|
||||
export default function ProjectWorkspaceRoute() {
|
||||
return <ProjectWorkspacePage />;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 g++ make python3 \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates g++ git make python3 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -4,8 +4,26 @@ services:
|
||||
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:
|
||||
|
||||
70
package.json
70
package.json
@@ -1,59 +1,12 @@
|
||||
{
|
||||
"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",
|
||||
"build": "vp run -r build",
|
||||
"check-types": "vp run -r check-types",
|
||||
"check": "ultracite check package.json vite.config.ts apps/web/package.json apps/web/src/root.tsx apps/web/src/index.css apps/web/src/components/chat apps/web/src/components/slice-one apps/web/src/hooks/chat apps/web/src/hooks/slice-one apps/web/src/lib/chat apps/web/src/lib/slice-one apps/web/src/routes.ts apps/web/src/routes/app/dashboard/page.tsx apps/web/src/routes/app/mobile/page.tsx packages/agents/package.json packages/agents/src/agents/zopu.ts packages/agents/src/app.ts packages/agents/src/auth.ts packages/agents/src/tools/slice-one.ts packages/backend/package.json packages/backend/convex/conversationMessages.ts packages/backend/convex/conversationMessages.test.ts packages/backend/convex/fluePersistence.test.ts packages/backend/convex/projects.ts packages/backend/convex/schema.ts packages/backend/convex/signalRouting.ts packages/backend/convex/signalRouting.test.ts packages/backend/convex/works.ts packages/backend/convex/works.test.ts packages/backend/convex/workArtifacts.ts packages/backend/convex/workArtifacts.test.ts packages/backend/convex/workExecution.ts packages/backend/convex/workExecution.test.ts packages/backend/convex/workPlanning.ts packages/backend/convex/workPlanning.test.ts packages/backend/convex/crons.ts packages/primitives/src/work.ts packages/primitives/src/work.test.ts packages/primitives/src/work-artifact.ts packages/primitives/src/work-artifact.test.ts packages/primitives/src/resolver.ts packages/primitives/src/work-lifecycle.ts packages/primitives/src/work-resolution.test.ts",
|
||||
"check": "ultracite check package.json vite.config.ts apps/web/package.json apps/web/src/root.tsx apps/web/src/index.css apps/web/src/components/chat apps/web/src/components/workspace apps/web/src/hooks/chat apps/web/src/hooks/workspace apps/web/src/lib/chat apps/web/src/lib/workspace apps/web/src/routes.ts apps/web/src/routes/app/dashboard/page.tsx apps/web/src/routes/app/workspace/page.tsx packages/agents/package.json packages/agents/src/agents/zopu.ts packages/agents/src/app.ts packages/agents/src/auth.ts packages/agents/src/tools/slice-one.ts packages/backend/package.json packages/backend/convex/conversationMessages.ts packages/backend/convex/conversationMessages.test.ts packages/backend/convex/fluePersistence.test.ts packages/backend/convex/projects.ts",
|
||||
"lint": "oxlint --disable-nested-config",
|
||||
"format": "vp fmt",
|
||||
"staged": "vp staged",
|
||||
@@ -65,14 +18,10 @@
|
||||
"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",
|
||||
"fix": "ultracite fix",
|
||||
"slice1": "vp run -r dev",
|
||||
"dev:zopu": "vp run --filter @code/agents dev",
|
||||
"dev:zopu:web": "vp run --filter web dev"
|
||||
"docs:update": "node scripts/update-docs.ts",
|
||||
"subtree": "node scripts/subtree.ts",
|
||||
"fix": "ultracite fix"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@code/backend": "workspace:*",
|
||||
"@code/config": "workspace:*",
|
||||
@@ -84,18 +33,13 @@
|
||||
"convex": "catalog:",
|
||||
"convex-test": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "latest",
|
||||
"oxlint": "latest",
|
||||
"oxfmt": "0.61.0",
|
||||
"oxlint": "1.76.0",
|
||||
"rolldown": "1.1.4",
|
||||
"typescript": "catalog:",
|
||||
"ultracite": "7.9.3",
|
||||
"vite-plus": "0.2.2",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"overrides": {
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"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,23 +4,24 @@
|
||||
"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",
|
||||
"runner": "bun --env-file=../../.env src/runner.ts",
|
||||
"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/codex-cli": "0.3.4",
|
||||
"@agentos-software/git": "0.3.3",
|
||||
"@code/backend": "workspace:*",
|
||||
"@code/env": "workspace:*",
|
||||
"@code/primitives": "workspace:*",
|
||||
"@flue/runtime": "latest",
|
||||
"@rivet-dev/agentos": "0.2.10",
|
||||
"@rivet-dev/agentos": "0.2.14",
|
||||
"@rivet-dev/agentos-core": "0.2.14",
|
||||
"convex": "catalog:",
|
||||
"hono": "catalog:",
|
||||
"rivetkit": "2.3.9",
|
||||
@@ -30,6 +31,10 @@
|
||||
"@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,4 +1,5 @@
|
||||
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";
|
||||
@@ -42,8 +43,23 @@ app.post("/internal/work-attempts/execute", async (context) => {
|
||||
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: error instanceof Error ? error.message : "Execution failed" },
|
||||
{
|
||||
error: {
|
||||
message: failure.message,
|
||||
reason: failure.reason,
|
||||
retryable: failure.retryable,
|
||||
},
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
@@ -55,7 +71,11 @@ app.post("/internal/work-attempts/:workspaceKey/cancel", async (context) => {
|
||||
) {
|
||||
return context.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
await cancelAgentOsAttempt(context.req.param("workspaceKey"));
|
||||
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 });
|
||||
});
|
||||
|
||||
|
||||
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.
|
||||
@@ -1,25 +1,38 @@
|
||||
import { parseAgentEnv } from "@code/env/agent";
|
||||
import { agentOS, setup } from "@rivet-dev/agentos";
|
||||
import { createClient } from "@rivet-dev/agentos/client";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import {
|
||||
codexSessionEnv,
|
||||
makeCodexAgentOsConfig,
|
||||
} from "../../../primitives/src/agent-os";
|
||||
import { decodeWorkAttemptExecutionInput } from "../../../primitives/src/execution-runtime";
|
||||
makePiAgentOsConfig,
|
||||
makePiHomeFiles,
|
||||
decodeWorkAttemptExecutionInput,
|
||||
WorkAttemptExecutionError,
|
||||
piSessionEnv,
|
||||
} from "@code/primitives";
|
||||
import type {
|
||||
ExecutionEvent,
|
||||
WorkAttemptExecutionResult,
|
||||
} from "../../../primitives/src/execution-runtime";
|
||||
} 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";
|
||||
|
||||
const workspace = agentOS(makeCodexAgentOsConfig() as never);
|
||||
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 shellQuote = (value: string): string =>
|
||||
`'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
|
||||
const event = (
|
||||
sequence: number,
|
||||
kind: ExecutionEvent["kind"],
|
||||
@@ -33,181 +46,210 @@ const event = (
|
||||
sequence,
|
||||
});
|
||||
|
||||
const requireSuccess = (
|
||||
result: { exitCode: number; stderr: string; stdout: string },
|
||||
operation: string
|
||||
) => {
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`${operation} failed: ${result.stderr || result.stdout}`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
};
|
||||
const executionError = (
|
||||
message: string,
|
||||
reason: WorkAttemptExecutionError["reason"],
|
||||
retryable: boolean
|
||||
) => new WorkAttemptExecutionError({ message, reason, retryable });
|
||||
|
||||
const gitAuthEnv = (username: string, credential: string) => ({
|
||||
GIT_CONFIG_COUNT: "1",
|
||||
GIT_CONFIG_KEY_0: "http.extraHeader",
|
||||
GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`${username}:${credential}`).toString("base64")}`,
|
||||
});
|
||||
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> => {
|
||||
const input = await Effect.runPromise(
|
||||
decodeWorkAttemptExecutionInput(rawInput)
|
||||
);
|
||||
const env = parseAgentEnv(process.env);
|
||||
const client = createClient<typeof runtimeRegistry>({
|
||||
endpoint: env.RIVET_PUBLIC_ENDPOINT ?? env.RIVET_ENDPOINT,
|
||||
});
|
||||
const vm = client.workspace.getOrCreate([input.workspaceKey]);
|
||||
const events: ExecutionEvent[] = [
|
||||
event(0, "runtime.preparing", "AgentOS workspace selected", {
|
||||
workspaceKey: input.workspaceKey,
|
||||
}),
|
||||
];
|
||||
const authEnv = gitAuthEnv(
|
||||
input.auth.username ??
|
||||
(input.auth.provider === "github" ? "x-access-token" : "git"),
|
||||
input.auth.credential
|
||||
);
|
||||
|
||||
await vm.mkdir("/workspace", { recursive: true });
|
||||
if (!(await vm.exists("/workspace/repository/.git"))) {
|
||||
events.push(event(1, "repository.cloning", "Cloning project repository"));
|
||||
const clone = await vm.execArgv(
|
||||
"git",
|
||||
["clone", input.repositoryUrl, "/workspace/repository"],
|
||||
{
|
||||
cwd: "/workspace",
|
||||
env: authEnv,
|
||||
}
|
||||
try {
|
||||
const input = await Effect.runPromise(
|
||||
decodeWorkAttemptExecutionInput(rawInput)
|
||||
);
|
||||
requireSuccess(clone, "Repository clone");
|
||||
}
|
||||
|
||||
const checkout = await vm.exec(
|
||||
`git fetch origin ${shellQuote(input.baseBranch)} && git checkout -B ${shellQuote(`zopu/${input.runId}`)} ${shellQuote(`origin/${input.baseBranch}`)}`,
|
||||
{ cwd: "/workspace/repository", env: authEnv }
|
||||
);
|
||||
requireSuccess(checkout, "Repository checkout");
|
||||
const baseRevision = requireSuccess(
|
||||
await vm.execArgv("git", ["rev-parse", "HEAD"], {
|
||||
cwd: "/workspace/repository",
|
||||
}),
|
||||
"Base revision lookup"
|
||||
);
|
||||
events.push(
|
||||
event(2, "repository.ready", "Repository checkout is ready", {
|
||||
baseRevision,
|
||||
})
|
||||
);
|
||||
|
||||
const sessionId = `codex-${input.attemptId}`;
|
||||
await vm.openSession({
|
||||
additionalInstructions:
|
||||
"Work only inside /workspace/repository. Do not reveal credentials. Make the requested change and run focused verification. Do not push or open a pull request.",
|
||||
agent: "codex",
|
||||
cwd: "/workspace/repository",
|
||||
env: codexSessionEnv({
|
||||
apiKey: env.AGENT_MODEL_API_KEY,
|
||||
baseUrl: env.AGENT_MODEL_BASE_URL,
|
||||
model: env.AGENT_MODEL_NAME,
|
||||
}),
|
||||
permissionPolicy: "allow_all",
|
||||
sessionId,
|
||||
});
|
||||
events.push(
|
||||
event(3, "harness.started", "Codex implementation session started")
|
||||
);
|
||||
const promptResult = await vm.prompt({
|
||||
content: [{ text: input.prompt, type: "text" }],
|
||||
idempotencyKey: input.attemptId,
|
||||
sessionId,
|
||||
});
|
||||
events.push(
|
||||
event(4, "harness.progress", "Codex implementation turn completed", {
|
||||
stopReason: String(promptResult.stopReason),
|
||||
})
|
||||
);
|
||||
|
||||
const status = requireSuccess(
|
||||
await vm.execArgv("git", ["status", "--porcelain"], {
|
||||
cwd: "/workspace/repository",
|
||||
}),
|
||||
"Changed file lookup"
|
||||
);
|
||||
const diff = requireSuccess(
|
||||
await vm.execArgv("git", ["diff", "--binary", "HEAD"], {
|
||||
cwd: "/workspace/repository",
|
||||
}),
|
||||
"Diff collection"
|
||||
);
|
||||
const changedFiles = status
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => line.slice(3).trim());
|
||||
let candidateRevision = baseRevision;
|
||||
if (changedFiles.length > 0) {
|
||||
requireSuccess(
|
||||
await vm.execArgv("git", ["add", "-A"], { cwd: "/workspace/repository" }),
|
||||
"Candidate staging"
|
||||
);
|
||||
const tree = requireSuccess(
|
||||
await vm.execArgv("git", ["write-tree"], {
|
||||
cwd: "/workspace/repository",
|
||||
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,
|
||||
}),
|
||||
"Candidate tree creation"
|
||||
];
|
||||
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"
|
||||
)
|
||||
);
|
||||
candidateRevision = requireSuccess(
|
||||
await vm.exec(
|
||||
`printf %s ${shellQuote(`Zopu candidate for ${input.attemptId}`)} | git commit-tree ${shellQuote(tree)} -p ${shellQuote(baseRevision)}`,
|
||||
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`,
|
||||
{
|
||||
cwd: "/workspace/repository",
|
||||
env: {
|
||||
GIT_AUTHOR_EMAIL: "agent@zopu.dev",
|
||||
GIT_AUTHOR_NAME: "Zopu Agent",
|
||||
GIT_COMMITTER_EMAIL: "agent@zopu.dev",
|
||||
GIT_COMMITTER_NAME: "Zopu Agent",
|
||||
},
|
||||
candidateRevision,
|
||||
}
|
||||
),
|
||||
"Candidate revision creation"
|
||||
event(6, "runtime.completed", "AgentOS execution completed")
|
||||
);
|
||||
requireSuccess(
|
||||
await vm.execArgv("git", ["reset"], { cwd: "/workspace/repository" }),
|
||||
"Candidate index reset"
|
||||
);
|
||||
}
|
||||
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
|
||||
? `Codex changed ${changedFiles.length} file(s)`
|
||||
: "Codex completed without repository changes",
|
||||
};
|
||||
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) => {
|
||||
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]).cancelPrompt({});
|
||||
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 };
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,21 @@ 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(),
|
||||
@@ -110,6 +125,15 @@ export const attachToProject = mutation({
|
||||
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(),
|
||||
|
||||
@@ -367,6 +367,17 @@ export default defineSchema({
|
||||
|
||||
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()),
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
"use node";
|
||||
|
||||
import { env } from "@code/env/convex";
|
||||
import { decodeWorkAttemptExecutionResult } from "@code/primitives/execution-runtime";
|
||||
import {
|
||||
WorkAttemptExecutionError,
|
||||
decodeWorkAttemptExecutionFailure,
|
||||
decodeWorkAttemptExecutionResult,
|
||||
} from "@code/primitives/execution-runtime";
|
||||
import { ConvexError, v } from "convex/values";
|
||||
import { Effect } from "effect";
|
||||
|
||||
@@ -56,23 +60,36 @@ export const executeAttempt = internalAction({
|
||||
);
|
||||
const payload = (await response.json()) as unknown;
|
||||
if (!response.ok) {
|
||||
throw new ConvexError(
|
||||
typeof payload === "object" && payload && "error" in payload
|
||||
? String(payload.error)
|
||||
: `Agent backend returned ${response.status}`
|
||||
// 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: { workspaceKey: v.string() },
|
||||
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`,
|
||||
{
|
||||
headers: { authorization: `Bearer ${env.FLUE_DB_TOKEN}` },
|
||||
body: JSON.stringify({ attemptId: args.attemptId }),
|
||||
headers: {
|
||||
authorization: `Bearer ${env.FLUE_DB_TOKEN}`,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
}
|
||||
);
|
||||
|
||||
@@ -7,94 +7,116 @@ 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 = 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://example.com/zopu",
|
||||
organizationId,
|
||||
repositoryPath: "puter/zopu",
|
||||
sourceHost: "example.com",
|
||||
sourceUrl: "https://example.com/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: "running",
|
||||
workId,
|
||||
});
|
||||
const attemptId = await ctx.db.insert("workAttempts", {
|
||||
number: 1,
|
||||
runId,
|
||||
status: "running",
|
||||
workId,
|
||||
workspaceKey: "workspace-1",
|
||||
});
|
||||
return { attemptId, runId, workId };
|
||||
});
|
||||
|
||||
const { t, ...seeded } = await seedRunningAttempt();
|
||||
await t.mutation(api.workExecutionWorkflow.completeAttempt, {
|
||||
attemptId: seeded.attemptId,
|
||||
result: {
|
||||
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",
|
||||
},
|
||||
result: successResult,
|
||||
});
|
||||
|
||||
const state = await t.run(async (ctx) => ({
|
||||
artifacts: await ctx.db.query("workArtifacts").collect(),
|
||||
attempt: await ctx.db.get(seeded.attemptId),
|
||||
run: await ctx.db.get(seeded.runId),
|
||||
work: await ctx.db.get(seeded.workId),
|
||||
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({
|
||||
@@ -109,3 +131,251 @@ describe("real work execution persistence", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { defaultCodingKitV0 } from "@code/primitives/resolver";
|
||||
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";
|
||||
@@ -8,9 +11,68 @@ 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">,
|
||||
@@ -36,6 +98,34 @@ const resolveReadySlice = async (
|
||||
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> => {
|
||||
@@ -57,9 +147,12 @@ export const execute = workflow
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const failure = toExecutionFailure(error);
|
||||
await step.runMutation(internal.workExecutionWorkflow.failAttempt, {
|
||||
attemptId: args.attemptId,
|
||||
summary: error instanceof Error ? error.message : "Execution failed",
|
||||
reason: failure.reason,
|
||||
retryable: failure.retryable,
|
||||
summary: failure.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -91,10 +184,7 @@ export const startExecution = mutation({
|
||||
) {
|
||||
throw new ConvexError("Execution requires exact approved versions");
|
||||
}
|
||||
const project = await ctx.db.get(work.projectId);
|
||||
if (!project?.gitConnectionId) {
|
||||
throw new ConvexError("Connect Git credentials to this project first");
|
||||
}
|
||||
await validateProjectDeployment(ctx, work);
|
||||
const slice = await resolveReadySlice(ctx, work, args.sliceId);
|
||||
const createdAt = Date.now();
|
||||
const runId = await ctx.db.insert("workRuns", {
|
||||
@@ -159,6 +249,12 @@ export const executionContext = internalQuery({
|
||||
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,
|
||||
@@ -179,11 +275,16 @@ 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 !== "queued") {
|
||||
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, {
|
||||
startedAt: Date.now(),
|
||||
leaseExpiresAt: Date.now() + LEASE_MS,
|
||||
startedAt: attempt.startedAt ?? Date.now(),
|
||||
status: "running",
|
||||
});
|
||||
return true;
|
||||
@@ -193,7 +294,8 @@ export const markAttemptRunning = internalMutation({
|
||||
const settleSliceAndWork = async (
|
||||
ctx: MutationCtx,
|
||||
run: Doc<"workRuns">,
|
||||
succeeded: boolean
|
||||
succeeded: boolean,
|
||||
workStatus: Doc<"works">["status"]
|
||||
) => {
|
||||
if (!run.sliceRowId) {
|
||||
return;
|
||||
@@ -202,12 +304,18 @@ const settleSliceAndWork = async (
|
||||
if (!slice) {
|
||||
return;
|
||||
}
|
||||
await ctx.db.patch(slice._id, { status: succeeded ? "completed" : "ready" });
|
||||
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: Doc<"works">["status"] = succeeded ? "completed" : "failed";
|
||||
let status = workStatus;
|
||||
if (succeeded) {
|
||||
const slices = await ctx.db
|
||||
.query("workSlices")
|
||||
@@ -249,6 +357,8 @@ export const completeAttempt = internalMutation({
|
||||
},
|
||||
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;
|
||||
}
|
||||
@@ -257,6 +367,33 @@ export const completeAttempt = internalMutation({
|
||||
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,
|
||||
@@ -271,6 +408,7 @@ export const completeAttempt = internalMutation({
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification: "Succeeded",
|
||||
endedAt,
|
||||
leaseExpiresAt: undefined,
|
||||
status: "terminal",
|
||||
summary: args.result.summary,
|
||||
});
|
||||
@@ -292,7 +430,7 @@ export const completeAttempt = internalMutation({
|
||||
kind: "diff",
|
||||
metadataJson: JSON.stringify({ changedFiles: args.result.changedFiles }),
|
||||
organizationId: work.organizationId,
|
||||
producer: "agentos-codex",
|
||||
producer: "agentos-pi",
|
||||
projectId: work.projectId,
|
||||
provenanceJson: JSON.stringify({
|
||||
baseRevision: args.result.baseRevision,
|
||||
@@ -309,7 +447,7 @@ export const completeAttempt = internalMutation({
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
await settleSliceAndWork(ctx, run, true);
|
||||
await settleSliceAndWork(ctx, run, true, "completed");
|
||||
await ctx.db.insert("workEvents", {
|
||||
createdAt: endedAt,
|
||||
idempotencyKey: `real-run-completed:${run._id}`,
|
||||
@@ -321,31 +459,107 @@ export const completeAttempt = internalMutation({
|
||||
},
|
||||
});
|
||||
|
||||
export const failAttempt = internalMutation({
|
||||
args: { attemptId: v.id("workAttempts"), summary: v.string() },
|
||||
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) {
|
||||
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: "PermanentFailure",
|
||||
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: "PermanentFailure",
|
||||
terminalClassification: classification,
|
||||
terminalSummary: args.summary,
|
||||
});
|
||||
await settleSliceAndWork(ctx, run, false);
|
||||
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,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -375,15 +589,30 @@ export const cancelExecution = mutation({
|
||||
0,
|
||||
internal.workExecutionAgent.cancelAttempt,
|
||||
{
|
||||
attemptId: String(attempt._id),
|
||||
workspaceKey: attempt.workspaceKey,
|
||||
}
|
||||
);
|
||||
const cancelledAt = Date.now();
|
||||
await ctx.db.patch(attempt._id, {
|
||||
classification: "Cancelled",
|
||||
endedAt: Date.now(),
|
||||
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(),
|
||||
|
||||
2
packages/env/src/agent.ts
vendored
2
packages/env/src/agent.ts
vendored
@@ -16,6 +16,8 @@ const agentEnvSchema = z.object({
|
||||
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>;
|
||||
|
||||
@@ -30,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 ?? [])],
|
||||
});
|
||||
|
||||
@@ -121,6 +121,16 @@ export class WorkAttemptExecutionError extends Schema.TaggedErrorClass<WorkAttem
|
||||
}
|
||||
) {}
|
||||
|
||||
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,
|
||||
@@ -143,6 +153,11 @@ export const decodeWorkAttemptExecutionResult = (input: unknown) =>
|
||||
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: (
|
||||
@@ -150,6 +165,7 @@ export interface SandboxRuntime {
|
||||
signal?: AbortSignal
|
||||
) => Effect.Effect<WorkAttemptExecutionResult, WorkAttemptExecutionError>;
|
||||
readonly cancel: (
|
||||
workspaceKey: string
|
||||
workspaceKey: string,
|
||||
attemptId: string
|
||||
) => Effect.Effect<void, WorkAttemptExecutionError>;
|
||||
}
|
||||
|
||||
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.14"
|
||||
"@rivet-dev/agentos-core": "0.2.14"
|
||||
"@effect/platform-bun": "4.0.0-beta.99"
|
||||
dotenv: "17.4.2"
|
||||
zod: "4.4.3"
|
||||
lucide-react: "1.27.0"
|
||||
next-themes: "0.4.6"
|
||||
react: "19.2.8"
|
||||
react-dom: "19.2.8"
|
||||
sonner: "2.0.7"
|
||||
convex: "1.42.3"
|
||||
better-auth: "1.6.15"
|
||||
"@convex-dev/better-auth": "0.12.5"
|
||||
"@tanstack/react-form": "1.33.2"
|
||||
"@types/react-dom": "19.2.3"
|
||||
tailwindcss: "4.3.3"
|
||||
tailwind-merge: "3.6.0"
|
||||
"@better-auth/expo": "1.6.15"
|
||||
effect: "4.0.0-beta.99"
|
||||
typescript: "7.0.2"
|
||||
"@types/bun": "1.3.14"
|
||||
heroui-native: "1.0.6"
|
||||
vite: "8.1.5"
|
||||
vitest: "4.1.10"
|
||||
convex-test: "0.0.54"
|
||||
react-native: "0.86.0"
|
||||
"@types/react": "19.2.17"
|
||||
"@types/node": "22.20.1"
|
||||
hono: "4.12.32"
|
||||
valibot: "1.4.2"
|
||||
streamdown: "2.5.0"
|
||||
"@tailwindcss/postcss": "4.3.3"
|
||||
"@tailwindcss/vite": "4.3.3"
|
||||
|
||||
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