13 Commits

Author SHA1 Message Date
-Puter
a907539810 flue refactor and migrations 2026-07-29 00:45:46 +05:30
-Puter
601aca73c2 pnpm migrations 2026-07-29 00:45:33 +05:30
-Puter
ffecff3857 Run fixed Zopu worktrees with Pi 2026-07-28 22:20:42 +05:30
-Puter
0d7162544b fix: run AgentOS workspaces on remote runner 2026-07-28 20:08:46 +05:30
-Puter
092a9793ea fix: resolve repository hosts outside AgentOS 2026-07-28 18:30:08 +05:30
-Puter
5ee0a8d50e fix: allow AgentOS process environment 2026-07-28 18:27:16 +05:30
-Puter
420676f2d7 fix: allow AgentOS command execution 2026-07-28 18:21:31 +05:30
-Puter
24d82e2a06 fix: allow AgentOS workspace filesystem 2026-07-28 18:18:24 +05:30
-Puter
d47fa0e96a fix: allow slow AgentOS workspace boot 2026-07-28 18:14:32 +05:30
-Puter
1e7c893985 fix: apply AgentOS runtime permissions 2026-07-28 17:49:41 +05:30
-Puter
f9ebcb4a01 fix: align AgentOS runtime packages 2026-07-28 17:40:40 +05:30
-Puter
dceaa2b417 fix: allow AgentOS outbound networking 2026-07-28 17:29:47 +05:30
-Puter
a4f121e190 chore: preserve work attempt schema order 2026-07-28 17:12:54 +05:30
21 changed files with 21527 additions and 4959 deletions

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
verify-deps-before-run=false

4647
bun.lock

File diff suppressed because it is too large Load Diff

View File

@@ -25,14 +25,7 @@ CONVEX_INSTANCE_NAME=zopu-production
CONVEX_INSTANCE_SECRET= CONVEX_INSTANCE_SECRET=
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 2. Self-hosted Git / Gitea — REQUIRED for issue lifecycle # 2. Model gateway — REQUIRED
# 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
# All model calls route through this OpenAI-compatible endpoint. # All model calls route through this OpenAI-compatible endpoint.
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
AGENT_MODEL_PROVIDER=cheaptricks AGENT_MODEL_PROVIDER=cheaptricks
@@ -44,17 +37,17 @@ AGENT_MODEL_CONTEXT_WINDOW=262000
AGENT_MODEL_MAX_TOKENS=131072 AGENT_MODEL_MAX_TOKENS=131072
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. AgentOS / Rivet Engine — REQUIRED for the execution runner # 3. AgentOS / Rivet Engine — REQUIRED for the execution runner
# The agent service and runner connect through the public engine endpoint. # The runner creates isolated worktrees from ZOPU_SOURCE_REPOSITORY and
# RIVET_WORKSPACE_TOKEN authenticates every workspace actor connection. # connects to AgentOS through the public engine endpoint.
# RIVET_ENVOY_VERSION must change for each runner deployment.
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
RIVET_ENDPOINT=https://default:@rivet.example.com RIVET_ENDPOINT=https://default:@rivet.example.com
RIVET_PUBLIC_ENDPOINT=https://default@rivet.example.com RIVET_PUBLIC_ENDPOINT=https://default@rivet.example.com
RIVET_ENVOY_VERSION=1 RIVET_ENVOY_VERSION=1
RIVET_WORKSPACE_TOKEN=replace-with-a-long-random-workspace-token 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. # FLUE_DB_TOKEN authenticates the Flue persistence adapter.
# zopu-agent.service pins the Flue Node server to port 3583. # zopu-agent.service pins the Flue Node server to port 3583.
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -62,7 +55,7 @@ FLUE_DB_TOKEN=replace-with-long-random-token
AGENT_BACKEND_URL=https://zopu-agent.example.com AGENT_BACKEND_URL=https://zopu-agent.example.com
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 6. Daemon identity # 5. Daemon identity
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
DAEMON_ID=zopu-dedicated DAEMON_ID=zopu-dedicated
DAEMON_NAME=Zopu-Dedicated-Server DAEMON_NAME=Zopu-Dedicated-Server

View File

@@ -5,7 +5,7 @@ FROM node:24-bookworm-slim
COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
RUN apt-get update \ 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/* && rm -rf /var/lib/apt/lists/*
WORKDIR /app WORKDIR /app

View File

@@ -19,4 +19,11 @@ services:
RIVET_ENVOY_VERSION: ${RIVET_ENVOY_VERSION} RIVET_ENVOY_VERSION: ${RIVET_ENVOY_VERSION}
RIVET_WORKSPACE_TOKEN: ${RIVET_WORKSPACE_TOKEN} RIVET_WORKSPACE_TOKEN: ${RIVET_WORKSPACE_TOKEN}
RIVET_POOL: default RIVET_POOL: default
ZOPU_SOURCE_REPOSITORY: /opt/zopu-source
volumes:
- ../..:/opt/zopu-source
- zopu-agentos-workspaces:/var/lib/zopu/workspaces
restart: unless-stopped restart: unless-stopped
volumes:
zopu-agentos-workspaces:

View File

@@ -1,53 +1,6 @@
{ {
"name": "code", "name": "code",
"private": true, "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", "type": "module",
"scripts": { "scripts": {
"dev": "vp run -r dev", "dev": "vp run -r dev",
@@ -65,8 +18,8 @@
"dev:server": "vp run --filter @code/backend dev", "dev:server": "vp run --filter @code/backend dev",
"dev:setup": "vp run --filter @code/backend dev:setup", "dev:setup": "vp run --filter @code/backend dev:setup",
"build:agents": "vp run --filter @code/agents build", "build:agents": "vp run --filter @code/agents build",
"docs:update": "bun run scripts/update-docs.ts", "docs:update": "node scripts/update-docs.ts",
"subtree": "bun run scripts/subtree.ts", "subtree": "node scripts/subtree.ts",
"fix": "ultracite fix", "fix": "ultracite fix",
"slice1": "vp run -r dev", "slice1": "vp run -r dev",
"dev:zopu": "vp run --filter @code/agents dev", "dev:zopu": "vp run --filter @code/agents dev",
@@ -92,10 +45,5 @@
"vite-plus": "0.2.2", "vite-plus": "0.2.2",
"vitest": "catalog:" "vitest": "catalog:"
}, },
"overrides": { "packageManager": "pnpm@11.17.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"vite": "npm:@voidzero-dev/vite-plus-core@0.2.2"
},
"packageManager": "bun@1.3.14"
} }

View File

@@ -1,5 +1,5 @@
import { defineConfig } from '@flue/cli/config'; import { defineConfig } from "@flue/cli/config";
export default defineConfig({ export default defineConfig({
target: 'node', target: "node",
}); });

View File

@@ -4,23 +4,24 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "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", "check-types": "tsc --noEmit",
"dev": "bun --env-file=../../.env flue dev", "dev": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs dev",
"dev:tailscale": "bun --env-file=../../.env flue dev", "dev:tailscale": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs dev",
"run": "bun --env-file=../../.env flue run", "run": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run",
"runner": "bun --env-file=../../.env src/runner.ts", "runner": "node --env-file=../../.env src/runner.ts",
"run:zopu": "bun --env-file=../../.env flue run zopu", "run:zopu": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run zopu",
"run:work-planner": "bun --env-file=../../.env flue run work-planner" "run:work-planner": "node --env-file=../../.env node_modules/@flue/cli/bin/flue.mjs run work-planner"
}, },
"dependencies": { "dependencies": {
"@agentos-software/codex-cli": "0.3.4",
"@agentos-software/git": "0.3.3", "@agentos-software/git": "0.3.3",
"@code/backend": "workspace:*", "@code/backend": "workspace:*",
"@code/env": "workspace:*", "@code/env": "workspace:*",
"@code/primitives": "workspace:*", "@code/primitives": "workspace:*",
"@flue/runtime": "latest", "@flue/runtime": "latest",
"@rivet-dev/agentos": "0.2.10", "@rivet-dev/agentos": "0.2.14",
"@rivet-dev/agentos-core": "0.2.14",
"convex": "catalog:", "convex": "catalog:",
"hono": "catalog:", "hono": "catalog:",
"rivetkit": "2.3.9", "rivetkit": "2.3.9",
@@ -30,6 +31,10 @@
"@code/config": "workspace:*", "@code/config": "workspace:*",
"@flue/cli": "latest", "@flue/cli": "latest",
"@types/bun": "catalog:", "@types/bun": "catalog:",
"@types/node": "catalog:",
"typescript": "catalog:" "typescript": "catalog:"
},
"engines": {
"node": ">=22.18 <23 || >=23.6"
} }
} }

View File

@@ -1,54 +1,9 @@
import { parseAgentEnv } from "@code/env/agent"; import { parseAgentEnv } from "@code/env/agent";
import { defineAgent } from "@flue/runtime"; import { defineAgent } from "@flue/runtime";
import INSTRUCTIONS from "../prompts/zopu-instructions.md" with { type: "markdown" };
import { createSliceOneTools } from "../tools/slice-one"; 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 { export {
convexAgentRoute as attachments, convexAgentRoute as attachments,
convexAgentRoute as route, convexAgentRoute as route,

View 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.

View File

@@ -1,36 +1,38 @@
import { parseAgentEnv } from "@code/env/agent"; 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 { import {
makePiAgentOsConfig,
makePiHomeFiles,
decodeWorkAttemptExecutionInput, decodeWorkAttemptExecutionInput,
WorkAttemptExecutionError, WorkAttemptExecutionError,
} from "../../../primitives/src/execution-runtime"; piSessionEnv,
} from "@code/primitives";
import type { import type {
ExecutionEvent, ExecutionEvent,
WorkAttemptExecutionResult, 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 codexConfig = makeCodexAgentOsConfig(); import { HostRepositoryWorkspace } from "./host-repository";
const piConfig = makePiAgentOsConfig();
const workspace = agentOS<undefined, { token: string }>({ const workspace = agentOS<undefined, { token: string }>({
onBeforeConnect: (_context, params) => { onBeforeConnect: (_context, params) => {
if (params.token !== process.env.RIVET_WORKSPACE_TOKEN) { if (params.token !== process.env.RIVET_WORKSPACE_TOKEN) {
throw new Error("Unauthorized workspace connection"); throw new Error("Unauthorized workspace connection");
} }
}, },
software: codexConfig.software, options: {
actionTimeout: 10 * 60 * 1000,
},
permissions: piConfig.permissions,
software: piConfig.software,
}); });
export const runtimeRegistry = setup({ use: { workspace } }); export const runtimeRegistry = setup({ use: { workspace } });
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'"'"'`)}'`;
const event = ( const event = (
sequence: number, sequence: number,
kind: ExecutionEvent["kind"], kind: ExecutionEvent["kind"],
@@ -44,16 +46,6 @@ const event = (
sequence, 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 = ( const executionError = (
message: string, message: string,
reason: WorkAttemptExecutionError["reason"], reason: WorkAttemptExecutionError["reason"],
@@ -80,12 +72,6 @@ const classifyRuntimeFailure = (cause: unknown): WorkAttemptExecutionError => {
return executionError(message, "HarnessFailed", false); return executionError(message, "HarnessFailed", false);
}; };
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")}`,
});
export const executeAgentOsAttempt = async ( export const executeAgentOsAttempt = async (
rawInput: unknown rawInput: unknown
): Promise<WorkAttemptExecutionResult> => { ): Promise<WorkAttemptExecutionResult> => {
@@ -106,59 +92,95 @@ export const executeAgentOsAttempt = async (
workspaceKey: input.workspaceKey, workspaceKey: input.workspaceKey,
}), }),
]; ];
const authEnv = gitAuthEnv( const hostRepository = new HostRepositoryWorkspace();
input.auth.username ?? const prepared = await hostRepository.prepare({
(input.auth.provider === "github" ? "x-access-token" : "git"), attemptId: input.attemptId,
input.auth.credential piHomeFiles: makePiHomeFiles({
); api: env.AGENT_MODEL_API,
apiKeyEnvironmentVariable: "AGENT_MODEL_API_KEY",
await vm.mkdir("/workspace", { recursive: true }); baseUrl: env.AGENT_MODEL_BASE_URL,
if (!(await vm.exists("/workspace/repository/.git"))) { contextWindow: env.AGENT_MODEL_CONTEXT_WINDOW,
events.push(event(1, "repository.cloning", "Cloning project repository")); maxTokens: env.AGENT_MODEL_MAX_TOKENS,
const clone = await vm.execArgv( model: env.AGENT_MODEL_NAME,
"git", provider: env.AGENT_MODEL_PROVIDER,
["clone", input.repositoryUrl, "/workspace/repository"],
{
cwd: "/workspace",
env: authEnv,
}
);
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(
1,
"runtime.preparing",
prepared.created
? "Isolated Zopu worktree created on the execution host"
: "Isolated Zopu worktree recreated"
)
); );
const mounts = [
{
hostPath: prepared.checkoutPath,
path: "/workspace/repository",
readOnly: false,
},
{
hostPath: prepared.sourceRepositoryPath,
path: prepared.sourceRepositoryPath,
readOnly: false,
},
{
hostPath: prepared.piHomePath,
path: "/home/zopu",
readOnly: false,
},
{
hostPath: prepared.toolsPath,
path: "/opt/zopu-tools",
readOnly: true,
},
] as const;
const mountNext = async (index: number): Promise<void> => {
const mount = mounts[index];
if (!mount) {
return;
}
try {
await vm.mountFs({
path: mount.path,
plugin: createHostDirBackend({
hostPath: mount.hostPath,
readOnly: mount.readOnly,
}),
readOnly: mount.readOnly,
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw executionError(
`Failed to mount ${mount.hostPath} at ${mount.path}: ${message}`,
"HarnessFailed",
false
);
}
await mountNext(index + 1);
};
await mountNext(0);
const { baseRevision } = prepared;
events.push( events.push(
event(2, "repository.ready", "Repository checkout is ready", { event(2, "repository.ready", "Repository checkout is ready", {
baseRevision, baseRevision,
}) })
); );
const sessionId = `codex-${input.attemptId}`; const sessionId = `pi-${input.attemptId}`;
await vm.openSession({ await vm.openSession({
additionalDirectories: [`${prepared.sourceRepositoryPath}/.git`],
additionalInstructions: 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.", "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: "codex", agent: "pi",
cwd: "/workspace/repository", cwd: "/workspace/repository",
env: codexSessionEnv({ env: piSessionEnv(env.AGENT_MODEL_API_KEY),
apiKey: env.AGENT_MODEL_API_KEY,
baseUrl: env.AGENT_MODEL_BASE_URL,
model: env.AGENT_MODEL_NAME,
}),
permissionPolicy: "allow_all", permissionPolicy: "allow_all",
sessionId, sessionId,
}); });
events.push( events.push(
event(3, "harness.started", "Codex implementation session started") event(3, "harness.started", "Pi implementation session started")
); );
const promptResult = await vm.prompt({ const promptResult = await vm.prompt({
content: [{ text: input.prompt, type: "text" }], content: [{ text: input.prompt, type: "text" }],
@@ -169,68 +191,24 @@ export const executeAgentOsAttempt = async (
const reason = const reason =
promptResult.stopReason === "cancelled" ? "Cancelled" : "HarnessFailed"; promptResult.stopReason === "cancelled" ? "Cancelled" : "HarnessFailed";
throw executionError( throw executionError(
`Codex stopped with ${promptResult.stopReason}`, `Pi stopped with ${promptResult.stopReason}`,
reason, reason,
promptResult.stopReason === "max_tokens" || promptResult.stopReason === "max_tokens" ||
promptResult.stopReason === "max_turn_requests" promptResult.stopReason === "max_turn_requests"
); );
} }
events.push( events.push(
event(4, "harness.progress", "Codex implementation turn completed", { event(4, "harness.progress", "Pi implementation turn completed", {
stopReason: promptResult.stopReason, stopReason: promptResult.stopReason,
}) })
); );
const status = requireSuccess( const collected = await HostRepositoryWorkspace.collect({
await vm.execArgv("git", ["status", "--porcelain"], { attemptId: input.attemptId,
cwd: "/workspace/repository", baseRevision,
}), checkoutPath: prepared.checkoutPath,
"Changed file lookup" });
); const { candidateRevision, changedFiles, diff } = collected;
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",
}),
"Candidate tree creation"
);
candidateRevision = requireSuccess(
await vm.exec(
`printf %s ${shellQuote(`Zopu candidate for ${input.attemptId}`)} | git commit-tree ${shellQuote(tree)} -p ${shellQuote(baseRevision)}`,
{
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",
},
}
),
"Candidate revision creation"
);
requireSuccess(
await vm.execArgv("git", ["reset"], { cwd: "/workspace/repository" }),
"Candidate index reset"
);
}
events.push( events.push(
event( event(
5, 5,
@@ -252,8 +230,8 @@ export const executeAgentOsAttempt = async (
events, events,
summary: summary:
changedFiles.length > 0 changedFiles.length > 0
? `Codex changed ${changedFiles.length} file(s)` ? `Pi changed ${changedFiles.length} file(s)`
: "Codex completed without repository changes", : "Pi completed without repository changes",
}; };
} catch (error) { } catch (error) {
throw classifyRuntimeFailure(error); throw classifyRuntimeFailure(error);
@@ -273,5 +251,5 @@ export const cancelAgentOsAttempt = async (
.getOrCreate([workspaceKey], { .getOrCreate([workspaceKey], {
params: { token: env.RIVET_WORKSPACE_TOKEN }, params: { token: env.RIVET_WORKSPACE_TOKEN },
}) })
.cancelPrompt({ sessionId: `codex-${attemptId}` }); .cancelPrompt({ sessionId: `pi-${attemptId}` });
}; };

View 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 };
}
}

View File

@@ -367,7 +367,6 @@ export default defineSchema({
workAttempts: defineTable({ workAttempts: defineTable({
classification: v.optional(attemptClassification), classification: v.optional(attemptClassification),
endedAt: v.optional(v.number()),
failureReason: v.optional( failureReason: v.optional(
v.union( v.union(
v.literal("Authentication"), v.literal("Authentication"),
@@ -379,6 +378,7 @@ export default defineSchema({
v.literal("Timeout") v.literal("Timeout")
) )
), ),
endedAt: v.optional(v.number()),
leaseExpiresAt: v.optional(v.number()), leaseExpiresAt: v.optional(v.number()),
leaseOwner: v.optional(v.string()), leaseOwner: v.optional(v.string()),
number: v.number(), number: v.number(),

View File

@@ -81,7 +81,7 @@ export const cancelAttempt = internalAction({
handler: async (_ctx, args) => { handler: async (_ctx, args) => {
// The workspace key remains the URL path segment (workspace identity), // The workspace key remains the URL path segment (workspace identity),
// while the body carries the attemptId so the runtime can target the // while the body carries the attemptId so the runtime can target the
// codex session `codex-${attemptId}` for cancellation. // matching Pi ACP session for cancellation.
await fetch( await fetch(
`${backendUrl()}/internal/work-attempts/${encodeURIComponent(args.workspaceKey)}/cancel`, `${backendUrl()}/internal/work-attempts/${encodeURIComponent(args.workspaceKey)}/cancel`,
{ {

View File

@@ -430,7 +430,7 @@ export const completeAttempt = internalMutation({
kind: "diff", kind: "diff",
metadataJson: JSON.stringify({ changedFiles: args.result.changedFiles }), metadataJson: JSON.stringify({ changedFiles: args.result.changedFiles }),
organizationId: work.organizationId, organizationId: work.organizationId,
producer: "agentos-codex", producer: "agentos-pi",
projectId: work.projectId, projectId: work.projectId,
provenanceJson: JSON.stringify({ provenanceJson: JSON.stringify({
baseRevision: args.result.baseRevision, baseRevision: args.result.baseRevision,

View File

@@ -17,6 +17,7 @@ const agentEnvSchema = z.object({
RIVET_ENDPOINT: z.url(), RIVET_ENDPOINT: z.url(),
RIVET_PUBLIC_ENDPOINT: z.url().optional(), RIVET_PUBLIC_ENDPOINT: z.url().optional(),
RIVET_WORKSPACE_TOKEN: z.string().min(32), 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>; export type AgentEnv = z.infer<typeof agentEnvSchema>;

View File

@@ -30,9 +30,9 @@
"test:watch": "vitest" "test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"@agentos-software/codex": "0.2.7", "@agentos-software/pi": "0.2.7",
"@agentos-software/git": "0.3.3", "@agentos-software/git": "0.3.3",
"@rivet-dev/agentos": "catalog:", "@rivet-dev/agentos": "0.2.14",
"effect": "catalog:" "effect": "catalog:"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -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");
});
});

View File

@@ -1,5 +1,5 @@
/* eslint-disable max-classes-per-file -- the AgentOS service and its tagged error form one adapter contract. */ /* eslint-disable max-classes-per-file -- the AgentOS service and its tagged error form one adapter contract. */
import codex from "@agentos-software/codex"; import pi from "@agentos-software/pi";
import { agentOS as createAgentOsActor } from "@rivet-dev/agentos"; import { agentOS as createAgentOsActor } from "@rivet-dev/agentos";
import type { AgentOSConfigInput } from "@rivet-dev/agentos"; import type { AgentOSConfigInput } from "@rivet-dev/agentos";
import { Context, Effect, Layer, Schema } from "effect"; import { Context, Effect, Layer, Schema } from "effect";
@@ -73,51 +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 // Slice 5 intentionally runs one harness against the server's fixed Zopu
// puter/zopu-code repo, booted with the Codex CLI harness + git. The model // checkout. Pi speaks ACP natively and reads its model gateway from a mounted
// provider is injected as VM env (OpenAI-compatible base URL + key) so Codex // HOME, avoiding a second executable adapter or credentials path.
// 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.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** Software bundle for a Codex-capable VM: the Codex harness plus git. */ /** Software bundle for a Pi-capable VM: the Pi ACP harness plus git. */
export const codexSoftware = [codex, getExecutableGitSoftware()] as const; export const piSoftware = [pi, getExecutableGitSoftware()] as const;
/** Model-provider env that Codex reads inside the VM. Pass this to the session's export interface PiModelConfig {
* `env` when opening a Codex session (`agent: "codex"`). */ readonly api: "openai-completions";
export interface CodexModelEnv { readonly apiKeyEnvironmentVariable: string;
readonly apiKey: string;
readonly baseUrl: string; readonly baseUrl: string;
readonly contextWindow: number;
readonly maxTokens: number;
readonly model: string; readonly model: string;
readonly provider: string;
} }
/** Builds the VM env record Codex reads to authenticate against the model gateway. */ export interface PiHomeFiles {
export const codexSessionEnv = ( readonly models: string;
model: CodexModelEnv, 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>> = {} extra: Readonly<Record<string, string>> = {}
): Record<string, string> => ({ ): Record<string, string> => ({
CODEX_MODEL: model.model, AGENT_MODEL_API_KEY: apiKey,
OPENAI_API_KEY: model.apiKey, HOME: "/home/zopu",
OPENAI_BASE_URL: model.baseUrl, PATH: "/opt/zopu-tools/bin:/usr/local/bin:/usr/bin:/bin",
...extra, ...extra,
}); });
export interface CodexAgentOsConfigInput { export interface PiAgentOsConfigInput {
/** Extra software merged after the Codex+git bundle. */ /** Extra software merged after the Pi+git bundle. */
readonly software?: NonNullable<AgentOSConfigInput<undefined>["software"]>; readonly software?: NonNullable<AgentOSConfigInput<undefined>["software"]>;
/** VM permission overrides merged over the execution policy. */
readonly permissions?: AgentOSConfigInput<undefined>["permissions"];
} }
/** export const makePiAgentOsConfig = (
* Builds an AgentOS actor config for a Codex-backed VM. The Codex CLI and git input: PiAgentOsConfigInput = {}
* 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 = {}
): AgentOSConfigInput<undefined> => ({ ): AgentOSConfigInput<undefined> => ({
software: [...codexSoftware, ...(input.software ?? [])], permissions: {
childProcess: "allow",
env: "allow",
fs: "allow",
network: "allow",
process: "allow",
...input.permissions,
},
software: [...piSoftware, ...(input.software ?? [])],
}); });

20928
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

62
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,62 @@
packages:
- apps/web
- packages/agents
- packages/auth
- packages/backend
- packages/config
- packages/env
- packages/primitives
- packages/ui
allowBuilds:
"@google/genai": true
"@mongodb-js/zstd": true
better-sqlite3: true
cbor-extract: true
esbuild: true
isolated-vm: true
koffi: true
msgpackr-extract: true
node-liblzma: true
protobufjs: true
workerd: true
catalog:
"@rivet-dev/agentos": "^0.2.7"
"@rivet-dev/agentos-core": "^0.2.10"
"@effect/platform-bun": "4.0.0-beta.99"
dotenv: "^17.4.2"
zod: "^4.4.3"
lucide-react: "^1.23.0"
next-themes: "^0.4.6"
react: "19.2.8"
react-dom: "19.2.8"
sonner: "^2.0.7"
convex: "^1.42.1"
better-auth: "1.6.15"
"@convex-dev/better-auth": "^0.12.5"
"@tanstack/react-form": "^1.33.0"
"@types/react-dom": "^19.2.3"
tailwindcss: "^4.3.2"
tailwind-merge: "^3.6.0"
"@better-auth/expo": "1.6.15"
effect: "4.0.0-beta.99"
typescript: "^7.0.2"
"@types/bun": "latest"
heroui-native: "^1.0.5"
vite: "^7.3.6"
vitest: "^4.1.10"
convex-test: "^0.0.54"
react-native: "0.86.0"
"@types/react": "^19.2.17"
"@types/node": "^22.13.14"
hono: "^4.8.3"
valibot: "^1.4.2"
streamdown: "2.5.0"
"@tailwindcss/postcss": "^4.3.2"
"@tailwindcss/vite": "^4.3.2"
overrides:
react: 19.2.8
react-dom: 19.2.8
vite: npm:@voidzero-dev/vite-plus-core@0.2.2