Skip to content

An open-source, faster Devin alternative

TypeScript

feat: add repository templates for serverless agents (#702)

Mohamed Habibba2f0218e262
diff --git a/cli/package-lock.json b/cli/package-lock.json
index eb95dc37..550d7685 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.6.6",
+ "version": "0.6.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.6.6",
+ "version": "0.6.7",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
diff --git a/cli/package.json b/cli/package.json
index 7fd057e5..a643eb10 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.6.6",
+ "version": "0.6.7",
"description": "Build, test, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
diff --git a/cli/src/api.ts b/cli/src/api.ts
index ca6a183b..586daec6 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -96,6 +96,72 @@ export interface AgentRuntimeVariableMetadata {
updatedAt: string;
}
+export interface TemplateInspection {
+ id: string;
+ repository: {
+ url: string;
+ fullName: string;
+ defaultBranch: "main";
+ commitSha: string;
+ };
+ template: {
+ name: string;
+ description: string;
+ documentation?: string;
+ defaultProjectName?: string;
+ firstRun?: { agent: string; prompt: string };
+ };
+ agents: Array<{ id: string; name: string }>;
+ requirements: {
+ secrets: Array<{
+ name: string;
+ description?: string;
+ documentation?: string;
+ required?: boolean;
+ agentId?: string;
+ allowedOrigins: string[];
+ }>;
+ runtimeVariables: Array<{
+ name: string;
+ description?: string;
+ documentation?: string;
+ required: boolean;
+ example?: string;
+ agentId?: string;
+ }>;
+ connections: Array<{
+ id: string;
+ description?: string;
+ provider: string;
+ permissions: string[];
+ }>;
+ };
+ expiresAt: string;
+}
+
+interface TemplateInspectionPreparing {
+ id: string;
+ status: "preparing";
+ repositoryUrl: string;
+ retryAfterMs: number;
+}
+
+export interface TemplateInstallation {
+ id: string;
+ inspectionId: string;
+ projectId: string;
+ projectAgentId: string;
+ projectUrl: string;
+ state:
+ | "awaiting_configuration"
+ | "creating_project"
+ | "building"
+ | "deploying"
+ | "ready"
+ | "failed";
+ error?: { stage: string; message: string };
+}
+
export interface ManagedAgentWebhook {
id: string;
projectId: string;
@@ -196,11 +262,11 @@ export class OpenComputerClient {
private readonly idempotencyKey?: string,
) {}
- private async request<T>(
+ private async response(
path: string,
init: RequestInit = {},
authenticated = true,
- ): Promise<T> {
+ ): Promise<Response> {
const headers = new Headers(init.headers);
if (init.body && !headers.has("content-type")) {
headers.set("content-type", "application/json");
@@ -234,11 +300,21 @@ export class OpenComputerClient {
redirect: "manual",
signal: AbortSignal.timeout(30_000),
});
- if (response.status === 204) return undefined as T;
- const body: unknown = await response.json().catch(() => undefined);
if (!response.ok) {
+ const body: unknown = await response.json().catch(() => undefined);
throw new APIError(errorMessage(body, response.status), response.status);
}
+ return response;
+ }
+
+ private async request<T>(
+ path: string,
+ init: RequestInit = {},
+ authenticated = true,
+ ): Promise<T> {
+ const response = await this.response(path, init, authenticated);
+ if (response.status === 204) return undefined as T;
+ const body: unknown = await response.json().catch(() => undefined);
return body as T;
}
@@ -305,6 +381,60 @@ export class OpenComputerClient {
});
}
+ projectSourceArchive(projectId: string): Promise<Response> {
+ return this.response(
+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/source-archive`,
+ );
+ }
+
+ async inspectTemplate(repositoryUrl: string): Promise<TemplateInspection> {
+ const deadline = Date.now() + 10 * 60_000;
+ for (;;) {
+ const result = await this.request<
+ TemplateInspection | TemplateInspectionPreparing
+ >("/api/managed-agents/template-inspections", {
+ method: "POST",
+ body: JSON.stringify({ repositoryUrl }),
+ });
+ if ((result as TemplateInspectionPreparing).status !== "preparing") {
+ return result as TemplateInspection;
+ }
+ const preparing = result as TemplateInspectionPreparing;
+ if (Date.now() >= deadline) {
+ throw new Error(
+ "Template preparation is still running; try again shortly",
+ );
+ }
+ await new Promise((resolvePromise) =>
+ setTimeout(resolvePromise, Math.max(500, preparing.retryAfterMs)),
+ );
+ }
+ }
+
+ createTemplateInstallation(input: {
+ inspectionId: string;
+ projectName: string;
+ idempotencyKey: string;
+ }) {
+ return this.request<TemplateInstallation>(
+ "/api/managed-agents/template-installations",
+ { method: "POST", body: JSON.stringify(input) },
+ );
+ }
+
+ finalizeTemplateInstallation(installationId: string) {
+ return this.request<TemplateInstallation>(
+ `/api/managed-agents/template-installations/${encodeURIComponent(installationId)}/finalize`,
+ { method: "POST" },
+ );
+ }
+
+ templateInstallation(installationId: string) {
+ return this.request<TemplateInstallation>(
+ `/api/managed-agents/template-installations/${encodeURIComponent(installationId)}`,
+ );
+ }
+
async secrets(input: {
projectId: string;
environment?: "development" | "production";
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 4f490a33..d7753add 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -28,6 +28,18 @@ import {
resolveProjectAgent,
} from "./session-command.js";
import { formatSessionEvent } from "./session-prompt.js";
+import {
+ buildTemplateProject,
+ normalizeTemplateRepositoryUrl,
+ readTemplateManifest,
+ templateDeployUrl,
+} from "./template.js";
+import {
+ defaultTemplateDirectory,
+ materializeTemplateCheckout,
+} from "./template-local.js";
+import { materializeProjectArchive } from "./project-local.js";
+import { createInterface } from "node:readline/promises";
import { doctorProject, type DoctorResult } from "./doctor.js";
import { CLIError } from "./errors.js";
@@ -100,6 +112,42 @@ function consumeModelAccessProvider(args: string[]): "claude" | "codex" {
return "codex";
}
+async function readTemplateSecretValue(): Promise<string> {
+ if (!process.stdin.isTTY) {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
+ if (!value) throw new Error("Secret value was empty");
+ return value;
+ }
+ process.stderr.write("Secret value (hidden): ");
+ process.stdin.setRawMode(true);
+ process.stdin.resume();
+ return new Promise<string>((resolve, reject) => {
+ let value = "";
+ const finish = (error?: Error): void => {
+ process.stdin.off("data", onData);
+ process.stdin.setRawMode(false);
+ process.stdin.pause();
+ process.stderr.write("\n");
+ if (error) reject(error);
+ else if (!value) reject(new Error("Secret value was empty"));
+ else resolve(value);
+ };
+ const onData = (chunk: Buffer): void => {
+ for (const byte of chunk) {
+ if (byte === 3) return finish(new Error("Secret entry cancelled"));
+ if (byte === 10 || byte === 13) return finish();
+ if (byte === 8 || byte === 127) value = value.slice(0, -1);
+ else value += String.fromCharCode(byte);
+ }
+ };
+ process.stdin.on("data", onData);
+ });
+}
+
async function readStdinValue(enabled: boolean): Promise<string> {
if (!enabled) {
throw new CLIError(
@@ -516,9 +564,270 @@ export async function runCommand(
globals: GlobalOptions,
): Promise<void> {
const args = [...rawArgs];
+
+ if (command === "template" && args[0] === "validate") {
+ args.shift();
+ const repositoryUrl = option(args, "--repository-url");
+ const appUrl = option(args, "--app-url");
+ const directory = args.shift() ?? process.cwd();
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const manifest = await readTemplateManifest(directory);
+ const deployUrl = repositoryUrl
+ ? templateDeployUrl(repositoryUrl, appUrl)
+ : undefined;
+ if (globals.json) {
+ printJSON({ file: "oc-template.toml", manifest, deployUrl });
+ } else {
+ process.stdout.write(
+ `Valid template: ${manifest.template.name}\n` +
+ (deployUrl ? `Deploy URL: ${deployUrl}\n` : ""),
+ );
+ }
+ return;
+ }
+
+ if (command === "template" && args[0] === "build") {
+ args.shift();
+ const output = option(args, "--output");
+ const directory = args.shift() ?? process.cwd();
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const bundle = await buildTemplateProject(directory);
+ const serialized = `${JSON.stringify(bundle)}\n`;
+ if (output) {
+ const { writeFile } = await import("node:fs/promises");
+ await writeFile(output, serialized, { mode: 0o600 });
+ if (!globals.json)
+ process.stdout.write(`Built template bundle: ${output}\n`);
+ } else {
+ process.stdout.write(serialized);
+ }
+ return;
+ }
+
const config = await resolveConfig(globals);
const client = new OpenComputerClient(config, globals.idempotencyKey);
+ if (command === "project" && args[0] === "clone") {
+ args.shift();
+ const directory = option(args, "--directory");
+ const projectId = args.shift();
+ if (!projectId || args.length) {
+ throw new Error(
+ "Usage: opencomputer project clone <project-id> [--directory <path>]",
+ );
+ }
+ const project = (await client.projects()).find(
+ (candidate) => candidate.id === projectId,
+ );
+ if (!project) throw new Error(`Project not found: ${projectId}`);
+ const checkout = await materializeProjectArchive({
+ response: await client.projectSourceArchive(project.id),
+ directory: directory ?? project.slug,
+ });
+ const binding = await ensureProjectBinding(client, config, checkout.directory, {
+ project: project.id,
+ });
+ if (globals.json) printJSON({ checkout, binding });
+ else {
+ process.stdout.write(
+ `Cloned ${binding.projectName} (${binding.projectId}).\n\n` +
+ `Next:\n cd ${checkout.directory}\n npm install\n` +
+ ` npm run deploy -- --watch --api-url ${config.apiUrl}\n`,
+ );
+ }
+ return;
+ }
+
+ if (command === "template") {
+ const action = args.shift();
+ if (action === "clone") {
+ const commitSha = option(args, "--commit");
+ const project = option(args, "--project");
+ const directory = option(args, "--directory");
+ const repositoryUrl = args.shift();
+ if (!repositoryUrl || !commitSha || !project || args.length) {
+ throw new Error(
+ "Usage: opencomputer template clone <repository-url> --commit <sha> --project <id> [--directory <path>]",
+ );
+ }
+ const normalized = normalizeTemplateRepositoryUrl(repositoryUrl);
+ const checkout = await materializeTemplateCheckout(
+ normalized,
+ commitSha,
+ directory,
+ );
+ const binding = await ensureProjectBinding(
+ client,
+ config,
+ checkout.directory,
+ { project },
+ );
+ if (globals.json) printJSON({ checkout, binding });
+ else {
+ process.stdout.write(
+ `Cloned ${normalized}@${commitSha.slice(0, 12)}\n` +
+ `Linked to ${binding.projectName} (${binding.projectId}).\n\n` +
+ `Next:\n cd ${checkout.directory}\n npm install\n npm run deploy -- --watch\n`,
+ );
+ }
+ return;
+ }
+ if (action !== "deploy") {
+ throw new Error(
+ "Usage: opencomputer template <deploy|clone> ...",
+ );
+ }
+ const projectNameOption = option(args, "--project-name");
+ const directoryOption = option(args, "--directory");
+ const confirmed = flag(args, "--yes");
+ const repositoryUrl = args.shift();
+ if (!repositoryUrl) {
+ throw new Error("A GitHub repository URL is required");
+ }
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const inspection = await client.inspectTemplate(
+ normalizeTemplateRepositoryUrl(repositoryUrl),
+ );
+ if (!globals.json) {
+ process.stdout.write(
+ `\n${inspection.template.name}\n${inspection.template.description}\n` +
+ `Source: ${inspection.repository.fullName}@${inspection.repository.commitSha.slice(0, 12)}\n` +
+ `Agents: ${inspection.agents.map((agent) => agent.name).join(", ")}\n` +
+ `Target: Development\n\n`,
+ );
+ }
+ if (inspection.requirements.connections.length) {
+ throw new Error(
+ "This template needs an interactive provider connection. Open its deploy URL in the dashboard to continue.",
+ );
+ }
+ const requiredSecrets = inspection.requirements.secrets.filter(
+ (requirement) => requirement.required !== false,
+ );
+ if (!process.stdin.isTTY && requiredSecrets.length) {
+ throw new Error(
+ `Secret ${requiredSecrets[0]!.name} requires an interactive terminal; secret values are never accepted as command-line arguments`,
+ );
+ }
+ if ((!process.stdin.isTTY || !process.stdout.isTTY) && !projectNameOption) {
+ throw new Error("--project-name is required in non-interactive mode");
+ }
+ const terminal =
+ process.stdin.isTTY && process.stdout.isTTY
+ ? createInterface({ input: process.stdin, output: process.stdout })
+ : undefined;
+ let projectName =
+ projectNameOption ??
+ inspection.template.defaultProjectName ??
+ inspection.template.name;
+ if (terminal && !projectNameOption) {
+ projectName =
+ (await terminal.question(`Project name [${projectName}]: `)).trim() ||
+ projectName;
+ }
+ if (terminal && !confirmed) {
+ const answer = (
+ await terminal.question("Create this Development project? [y/N] ")
+ )
+ .trim()
+ .toLowerCase();
+ if (answer !== "y" && answer !== "yes") {
+ terminal.close();
+ throw new Error("Template deployment cancelled");
+ }
+ }
+ const checkout = await materializeTemplateCheckout(
+ inspection.repository.url,
+ inspection.repository.commitSha,
+ directoryOption ?? defaultTemplateDirectory(inspection.repository.url),
+ );
+ const runtimeValues = new Map<string, string>();
+ for (const requirement of inspection.requirements.runtimeVariables) {
+ if (!terminal) {
+ if (requirement.required) {
+ throw new Error(
+ `Runtime variable ${requirement.name} requires an interactive terminal`,
+ );
+ }
+ continue;
+ }
+ const hint = requirement.example ? ` [${requirement.example}]` : "";
+ const value =
+ (await terminal.question(`${requirement.name}${hint}: `)).trim() ||
+ requirement.example ||
+ "";
+ if (requirement.required && !value) {
+ terminal.close();
+ throw new Error(`${requirement.name} is required`);
+ }
+ if (value) runtimeValues.set(requirement.name, value);
+ }
+ terminal?.close();
+ const installation = await client.createTemplateInstallation({
+ inspectionId: inspection.id,
+ projectName,
+ idempotencyKey: crypto.randomUUID(),
+ });
+ const installationAgentId = (localAgentId?: string) =>
+ !localAgentId || localAgentId === inspection.agents[0]?.id
+ ? installation.projectAgentId
+ : `${installation.projectAgentId}--${localAgentId}`;
+ for (const requirement of requiredSecrets) {
+ process.stderr.write(`${requirement.name}\n`);
+ const value = await readTemplateSecretValue();
+ await client.putSecret({
+ projectId: installation.projectId,
+ name: requirement.name,
+ value,
+ environment: "development",
+ agentId: installationAgentId(requirement.agentId),
+ allowedOrigins: requirement.allowedOrigins,
+ });
+ }
+ for (const requirement of inspection.requirements.runtimeVariables) {
+ const value = runtimeValues.get(requirement.name);
+ if (!value) continue;
+ await client.putRuntimeVariable({
+ projectId: installation.projectId,
+ name: requirement.name,
+ value,
+ environment: "development",
+ agentId: installationAgentId(requirement.agentId),
+ });
+ }
+ let current = await client.finalizeTemplateInstallation(installation.id);
+ const deadline = Date.now() + 10 * 60_000;
+ while (
+ !["ready", "failed"].includes(current.state) &&
+ Date.now() < deadline
+ ) {
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 1_000));
+ current = await client.templateInstallation(current.id);
+ if (!globals.json)
+ process.stderr.write(`Template installation: ${current.state}\r`);
+ }
+ if (current.state === "failed") {
+ throw new Error(current.error?.message ?? "Template installation failed");
+ }
+ if (current.state !== "ready") {
+ throw new Error(
+ `Template installation is still ${current.state}; ${current.projectUrl}`,
+ );
+ }
+ const binding = await ensureProjectBinding(client, config, checkout.directory, {
+ project: current.projectId,
+ });
+ if (globals.json) printJSON({ installation: current, checkout, binding });
+ else {
+ process.stdout.write(
+ `\nReady: ${current.projectUrl}\n` +
+ `Local: ${checkout.directory}\n\n` +
+ `Next:\n cd ${checkout.directory}\n npm install\n npm run deploy -- --watch\n`,
+ );
+ }
+ return;
+ }
+
if (command === "login") {
const identity = await login(config, {
noBrowser: flag(args, "--no-browser"),
@@ -884,7 +1193,9 @@ export async function runCommand(
legacyEnvironment &&
!["development", "production", "both"].includes(legacyEnvironment)
)
- throw new Error("--environment must be development, production, or both");
+ throw new Error(
+ "--environment must be development, production, or both",
+ );
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
const currentAgentRoot = projectReference ? null : await findAgentRoot();
const project =
@@ -962,9 +1273,7 @@ export async function runCommand(
else process.stdout.write(`Disconnected ${connection.label}.\n`);
return;
}
- throw new Error(
- "Use `opencomputer model-access connect|list|disconnect`.",
- );
+ throw new Error("Use `opencomputer model-access connect|list|disconnect`.");
}
if (command === "env") {
diff --git a/cli/src/index.ts b/cli/src/index.ts
index 545079ee..f0ed3e1b 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -49,6 +49,11 @@ Usage:
opencomputer whoami
opencomputer agents
opencomputer init <directory|.>
+ opencomputer template validate [directory] [--repository-url <url>] [--app-url <url>]
+ opencomputer template build [directory] [--output <path>]
+ opencomputer template deploy <repository-url> [--project-name <name>] [--directory <path>]
+ opencomputer template clone <repository-url> --commit <sha> --project <id> [--directory <path>]
+ opencomputer project clone <project-id> [--directory <path>]
opencomputer link (--project <id|slug> | --create-project <name>)
opencomputer doctor
opencomputer deploy --watch [--project <id|slug> | --create-project <name>]
diff --git a/cli/src/project-local.test.ts b/cli/src/project-local.test.ts
new file mode 100644
index 00000000..f336cb29
--- /dev/null
+++ b/cli/src/project-local.test.ts
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { resolve } from "node:path";
+import test from "node:test";
+import { promisify } from "node:util";
+
+import { materializeProjectArchive } from "./project-local.js";
+
+const exec = promisify(execFile);
+
+test("project archive materialization creates a new local checkout", async () => {
+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-project-local-test-"));
+ try {
+ const source = resolve(root, "source");
+ const target = resolve(root, "hello-world");
+ const archive = resolve(root, "project.tar.gz");
+ await mkdir(resolve(source, "opencomputer"), { recursive: true });
+ await writeFile(
+ resolve(source, "opencomputer", "project.ts"),
+ 'export default { name: "Hello World" }\n',
+ );
+ await exec("tar", ["-czf", archive, "-C", source, "."]);
+
+ const result = await materializeProjectArchive({
+ response: new Response(await readFile(archive)),
+ directory: target,
+ });
+
+ assert.equal(result.directory, target);
+ assert.equal(
+ await readFile(resolve(target, "opencomputer", "project.ts"), "utf8"),
+ 'export default { name: "Hello World" }\n',
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/cli/src/project-local.ts b/cli/src/project-local.ts
new file mode 100644
index 00000000..ca97577c
--- /dev/null
+++ b/cli/src/project-local.ts
@@ -0,0 +1,114 @@
+import { spawn } from "node:child_process";
+import { access, mkdir, mkdtemp, open, rename, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { isAbsolute, posix, resolve } from "node:path";
+
+const MAX_PROJECT_ARCHIVE_BYTES = 512 * 1024 * 1024;
+const MAX_ARCHIVE_LIST_BYTES = 8 * 1024 * 1024;
+
+async function pathDoesNotExist(path: string): Promise<void> {
+ await access(path)
+ .then(() => {
+ throw new Error(`Refusing to replace existing path: ${path}`);
+ })
+ .catch((error: unknown) => {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
+ return;
+ }
+ throw error;
+ });
+}
+
+function listArchive(path: string): Promise<string[]> {
+ return new Promise((resolvePromise, reject) => {
+ const child = spawn("tar", ["-tzf", path], {
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ let stdout = "";
+ child.stdout.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ if (Buffer.byteLength(stdout, "utf8") > MAX_ARCHIVE_LIST_BYTES) {
+ child.kill();
+ reject(new Error("Project archive contains too many paths"));
+ }
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => {
+ if (code !== 0) {
+ reject(new Error(`Could not inspect project archive (tar exited ${code})`));
+ return;
+ }
+ resolvePromise(stdout.split("\n").filter(Boolean));
+ });
+ });
+}
+
+function validateArchivePaths(paths: string[]): void {
+ if (!paths.length) throw new Error("Project archive is empty");
+ for (const path of paths) {
+ const normalized = posix.normalize(path.replace(/^\.\//, ""));
+ if (
+ path.includes("\0") ||
+ isAbsolute(path) ||
+ normalized === ".." ||
+ normalized.startsWith("../")
+ ) {
+ throw new Error("Project archive contains an unsafe path");
+ }
+ }
+}
+
+function extractArchive(path: string, directory: string): Promise<void> {
+ return new Promise((resolvePromise, reject) => {
+ const child = spawn(
+ "tar",
+ ["-xzf", path, "-C", directory, "--no-same-owner", "--no-same-permissions"],
+ { stdio: "inherit" },
+ );
+ child.once("error", reject);
+ child.once("exit", (code) => {
+ if (code === 0) resolvePromise();
+ else reject(new Error(`Could not extract project archive (tar exited ${code})`));
+ });
+ });
+}
+
+export async function materializeProjectArchive(input: {
+ response: Response;
+ directory: string;
+}): Promise<{ directory: string; bytes: number }> {
+ const target = resolve(input.directory);
+ await pathDoesNotExist(target);
+ if (!input.response.body) throw new Error("Project archive response was empty");
+
+ const temporary = await mkdtemp(resolve(tmpdir(), "opencomputer-project-"));
+ const archivePath = resolve(temporary, "project.tar.gz");
+ const extractPath = resolve(temporary, "project");
+ let bytes = 0;
+ try {
+ const archive = await open(archivePath, "wx", 0o600);
+ try {
+ const reader = input.response.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.byteLength;
+ if (bytes > MAX_PROJECT_ARCHIVE_BYTES) {
+ await reader.cancel();
+ throw new Error("Project archive exceeds the 512 MB download limit");
+ }
+ await archive.write(value);
+ }
+ } finally {
+ await archive.close();
+ }
+ validateArchivePaths(await listArchive(archivePath));
+ await mkdir(extractPath);
+ await extractArchive(archivePath, extractPath);
+ await mkdir(resolve(target, ".."), { recursive: true });
+ await rename(extractPath, target);
+ return { directory: target, bytes };
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
diff --git a/cli/src/template-local.ts b/cli/src/template-local.ts
new file mode 100644
index 00000000..b73e6477
--- /dev/null
+++ b/cli/src/template-local.ts
@@ -0,0 +1,68 @@
+import { spawn } from "node:child_process";
+import { access } from "node:fs/promises";
+import { basename, resolve } from "node:path";
+
+export interface TemplateCheckout {
+ directory: string;
+ commitSha: string;
+}
+
+export function defaultTemplateDirectory(repositoryUrl: string): string {
+ return basename(new URL(repositoryUrl).pathname);
+}
+
+function runGit(args: string[], capture = false): Promise<string> {
+ return new Promise((resolvePromise, reject) => {
+ const child = spawn("git", args, {
+ stdio: capture ? ["ignore", "pipe", "inherit"] : "inherit",
+ });
+ let stdout = "";
+ child.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ child.once("error", reject);
+ child.once("exit", (code) => {
+ if (code === 0) resolvePromise(stdout.trim());
+ else reject(new Error(`git ${args[0]} failed with exit code ${code}`));
+ });
+ });
+}
+
+export async function materializeTemplateCheckout(
+ repositoryUrl: string,
+ commitSha: string,
+ directory = defaultTemplateDirectory(repositoryUrl),
+): Promise<TemplateCheckout> {
+ if (!/^[0-9a-f]{40}$/.test(commitSha)) {
+ throw new Error("Template commit must be a full lowercase Git SHA");
+ }
+ const target = resolve(directory);
+ await access(target)
+ .then(() => {
+ throw new Error(`Refusing to replace existing path: ${target}`);
+ })
+ .catch((error: unknown) => {
+ if (
+ error instanceof Error &&
+ "code" in error &&
+ error.code === "ENOENT"
+ ) {
+ return;
+ }
+ throw error;
+ });
+ await runGit(["clone", "--no-checkout", repositoryUrl, target]);
+ await runGit([
+ "-C",
+ target,
+ "checkout",
+ "-b",
+ `opencomputer-template-${commitSha.slice(0, 8)}`,
+ commitSha,
+ ]);
+ const actual = await runGit(["-C", target, "rev-parse", "HEAD"], true);
+ if (actual !== commitSha) {
+ throw new Error(`Cloned commit ${actual || "unknown"} did not match ${commitSha}`);
+ }
+ return { directory: target, commitSha };
+}
diff --git a/cli/src/template.test.ts b/cli/src/template.test.ts
new file mode 100644
index 00000000..65650198
--- /dev/null
+++ b/cli/src/template.test.ts
@@ -0,0 +1,158 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { resolve } from "node:path";
+import test from "node:test";
+
+import {
+ buildTemplateProject,
+ normalizeTemplateRepositoryUrl,
+ parseTemplateManifest,
+ templateDeployUrl,
+} from "./template.js";
+import { initializeAgentProject } from "./project.js";
+
+const example = `schema = 1
+
+[template]
+name = "GitHub Actions Triage"
+description = "Investigate failed workflows."
+documentation = "https://github.com/diggerhq/example"
+default_project_name = "github-actions-triage"
+
+[template.first_run]
+agent = "triage"
+prompt = "Inspect the latest failed workflow."
+
+[template.secrets.GITHUB_TOKEN]
+description = "Fine-grained token."
+
+[template.runtime_variables.GITHUB_REPOSITORY]
+description = "Repository in owner/name form."
+required = true
+example = "diggerhq/opencomputer"
+
+[template.connections.github]
+description = "Connect GitHub."
+`;
+
+test("parses the v1 template contract", () => {
+ assert.deepEqual(parseTemplateManifest(example), {
+ schema: 1,
+ template: {
+ name: "GitHub Actions Triage",
+ description: "Investigate failed workflows.",
+ documentation: "https://github.com/diggerhq/example",
+ defaultProjectName: "github-actions-triage",
+ firstRun: {
+ agent: "triage",
+ prompt: "Inspect the latest failed workflow.",
+ },
+ secrets: { GITHUB_TOKEN: { description: "Fine-grained token." } },
+ runtimeVariables: {
+ GITHUB_REPOSITORY: {
+ description: "Repository in owner/name form.",
+ required: true,
+ example: "diggerhq/opencomputer",
+ },
+ },
+ connections: { github: { description: "Connect GitHub." } },
+ },
+ });
+});
+
+test("rejects unknown fields and incomplete first-run metadata", () => {
+ assert.throws(
+ () => parseTemplateManifest(`${example}\n[template.unsafe]\n`),
+ /unknown table template\.unsafe/,
+ );
+ assert.throws(
+ () =>
+ parseTemplateManifest(
+ example.replace(
+ 'description = "Investigate failed workflows."',
+ 'description = "Investigate failed workflows."\nunsafe = "yes"',
+ ),
+ ),
+ /unknown field template\.unsafe/,
+ );
+ assert.throws(
+ () =>
+ parseTemplateManifest(
+ `schema = 1\n[template]\nname = "A"\ndescription = "B"\n[template.first_run]\nagent = "a"\n`,
+ ),
+ /must be provided together/,
+ );
+});
+
+test("requires HTTPS documentation URLs", () => {
+ assert.throws(
+ () =>
+ parseTemplateManifest(
+ example.replace("https://github.com", "http://github.com"),
+ ),
+ /must be an HTTPS URL/,
+ );
+});
+
+test("normalizes only root GitHub repository URLs", () => {
+ assert.equal(
+ normalizeTemplateRepositoryUrl("https://github.com/diggerhq/opencomputer"),
+ "https://github.com/diggerhq/opencomputer",
+ );
+ for (const invalid of [
+ "https://gitlab.com/diggerhq/opencomputer",
+ "https://github.com/diggerhq/opencomputer/tree/main",
+ "https://github.com/diggerhq/opencomputer.git",
+ "https://github.com/diggerhq/opencomputer?ref=main",
+ ]) {
+ assert.throws(
+ () => normalizeTemplateRepositoryUrl(invalid),
+ /Repository URL/,
+ );
+ }
+});
+
+test("builds the canonical dashboard handoff without a ref", () => {
+ assert.equal(
+ templateDeployUrl("https://github.com/diggerhq/opencomputer"),
+ "https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer",
+ );
+});
+
+test("builds reusable project artifacts without customer configuration", async () => {
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-template-build-"),
+ );
+ try {
+ const initialized = await initializeAgentProject(resolve(parent, "app"));
+ await writeFile(
+ resolve(initialized.root, "oc-template.toml"),
+ `schema = 1
+[template]
+name = "Hello template"
+description = "A reusable hello-world project."
+default_project_name = "hello-template"
+[template.first_run]
+agent = "hello-world"
+prompt = "Say hello."
+`,
+ );
+ const bundle = await buildTemplateProject(initialized.root);
+ assert.equal(bundle.schema, 1);
+ assert.equal(bundle.template.name, "Hello template");
+ assert.deepEqual(bundle.agents, [
+ { id: "hello-world", name: "Hello World" },
+ ]);
+ assert.equal(bundle.artifacts.length, 1);
+ assert.match(bundle.artifacts[0]!.digest, /^[0-9a-f]{64}$/);
+ assert.ok(bundle.artifacts[0]!.size > 0);
+ assert.deepEqual(bundle.requirements, {
+ secrets: [],
+ runtimeVariables: [],
+ connections: [],
+ });
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
diff --git a/cli/src/template.ts b/cli/src/template.ts
new file mode 100644
index 00000000..7ebe9d1e
--- /dev/null
+++ b/cli/src/template.ts
@@ -0,0 +1,458 @@
+import { readFile, stat } from "node:fs/promises";
+import { resolve } from "node:path";
+import {
+ buildAgentArtifact,
+ readProjectAgents,
+ readProjectResources,
+ type HttpConnectionManifest,
+ type ProjectResourceManifest,
+} from "./project.js";
+
+const TEMPLATE_FILE = "oc-template.toml";
+const MAX_TEMPLATE_BYTES = 64 * 1024;
+const PROJECT_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const REQUIREMENT_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,127}$/;
+
+export interface TemplateRequirementAnnotation {
+ description?: string;
+ documentation?: string;
+ required?: boolean;
+}
+
+export interface TemplateRuntimeVariable extends TemplateRequirementAnnotation {
+ required?: boolean;
+ example?: string;
+}
+
+export interface TemplateManifest {
+ schema: 1;
+ template: {
+ name: string;
+ description: string;
+ documentation?: string;
+ defaultProjectName?: string;
+ firstRun?: { agent: string; prompt: string };
+ secrets: Record<string, TemplateRequirementAnnotation>;
+ runtimeVariables: Record<string, TemplateRuntimeVariable>;
+ connections: Record<string, TemplateRequirementAnnotation>;
+ };
+}
+
+export interface TemplateBuildArtifact {
+ localAgentId: string;
+ name: string;
+ digest: string;
+ size: number;
+ contentType: "application/vnd.opencomputer.agent+json";
+ body: string;
+ connections: string[];
+ httpConnections: HttpConnectionManifest[];
+}
+
+export interface TemplateBuildBundle {
+ schema: 1;
+ template: TemplateManifest["template"];
+ agents: Array<{ id: string; name: string }>;
+ artifacts: TemplateBuildArtifact[];
+ resources: ProjectResourceManifest;
+ requirements: {
+ secrets: Array<{
+ name: string;
+ description?: string;
+ documentation?: string;
+ required: boolean;
+ localAgentId: string;
+ allowedOrigins: string[];
+ }>;
+ runtimeVariables: Array<{
+ name: string;
+ description?: string;
+ documentation?: string;
+ required: boolean;
+ example?: string;
+ }>;
+ connections: Array<{
+ id: string;
+ description?: string;
+ }>;
+ };
+}
+
+type Scalar = string | boolean | number;
+
+function fail(message: string, line?: number): never {
+ throw new Error(`${TEMPLATE_FILE}${line ? `:${line}` : ""}: ${message}`);
+}
+
+function parseString(value: string, line: number): string {
+ if (!value.startsWith('"')) fail("values must be strings or booleans", line);
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (typeof parsed !== "string") fail("expected a string", line);
+ return parsed;
+ } catch (error) {
+ if (error instanceof Error && error.message.startsWith(TEMPLATE_FILE)) {
+ throw error;
+ }
+ return fail("invalid quoted string", line);
+ }
+}
+
+function parseScalar(value: string, line: number): Scalar {
+ if (value === "true") return true;
+ if (value === "false") return false;
+ if (/^[0-9]+$/.test(value)) return Number(value);
+ return parseString(value, line);
+}
+
+function parseFlatToml(
+ source: string,
+): Map<string, { value: Scalar; line: number }> {
+ const values = new Map<string, { value: Scalar; line: number }>();
+ const sections = new Set<string>();
+ let section = "";
+ for (const [index, original] of source.split(/\r?\n/).entries()) {
+ const line = index + 1;
+ const trimmed = original.trim();
+ if (!trimmed || trimmed.startsWith("#")) continue;
+ const sectionMatch = trimmed.match(/^\[([^\]]+)\]$/);
+ if (sectionMatch) {
+ section = sectionMatch[1]!.trim();
+ if (!section) fail("empty table name", line);
+ const dynamicSection = section.match(
+ /^template\.(secrets|runtime_variables|connections)\.([A-Za-z][A-Za-z0-9_]{0,127})$/,
+ );
+ if (
+ section !== "template" &&
+ section !== "template.first_run" &&
+ !dynamicSection
+ ) {
+ fail(`unknown table ${section}`, line);
+ }
+ if (sections.has(section)) fail(`duplicate table ${section}`, line);
+ sections.add(section);
+ continue;
+ }
+ const assignment = trimmed.match(/^([A-Za-z0-9_-]+)\s*=\s*(.+)$/);
+ if (!assignment) fail("unsupported TOML syntax", line);
+ const key = section ? `${section}.${assignment[1]}` : assignment[1]!;
+ if (values.has(key)) fail(`duplicate field ${key}`, line);
+ values.set(key, { value: parseScalar(assignment[2]!.trim(), line), line });
+ }
+ return values;
+}
+
+function stringField(
+ values: Map<string, { value: Scalar; line: number }>,
+ key: string,
+ required = false,
+): string | undefined {
+ const entry = values.get(key);
+ if (!entry) {
+ if (required) fail(`missing required field ${key}`);
+ return undefined;
+ }
+ if (typeof entry.value !== "string" || !entry.value.trim()) {
+ fail(`${key} must be a non-empty string`, entry.line);
+ }
+ return entry.value;
+}
+
+function httpsField(
+ values: Map<string, { value: Scalar; line: number }>,
+ key: string,
+): string | undefined {
+ const value = stringField(values, key);
+ if (!value) return undefined;
+ let parsed: URL;
+ try {
+ parsed = new URL(value);
+ } catch {
+ return fail(`${key} must be an HTTPS URL`, values.get(key)?.line);
+ }
+ if (parsed.protocol !== "https:") {
+ fail(`${key} must be an HTTPS URL`, values.get(key)?.line);
+ }
+ return value;
+}
+
+function annotations(
+ values: Map<string, { value: Scalar; line: number }>,
+ prefix: string,
+ runtimeVariable: boolean,
+): Record<string, TemplateRuntimeVariable> {
+ const result: Record<string, TemplateRuntimeVariable> = {};
+ for (const [key, entry] of values) {
+ if (!key.startsWith(`${prefix}.`)) continue;
+ const remainder = key.slice(prefix.length + 1);
+ const separator = remainder.lastIndexOf(".");
+ if (separator < 1) fail(`invalid requirement field ${key}`, entry.line);
+ const name = remainder.slice(0, separator);
+ const field = remainder.slice(separator + 1);
+ if (!REQUIREMENT_NAME_PATTERN.test(name)) {
+ fail(`invalid requirement name ${name}`, entry.line);
+ }
+ const allowed = runtimeVariable
+ ? ["description", "documentation", "required", "example"]
+ : ["description", "documentation", "required"];
+ if (!allowed.includes(field)) fail(`unknown field ${key}`, entry.line);
+ const target = (result[name] ??= {});
+ if (field === "required") {
+ if (typeof entry.value !== "boolean") {
+ fail(`${key} must be a boolean`, entry.line);
+ }
+ target.required = entry.value;
+ } else {
+ if (typeof entry.value !== "string" || !entry.value.trim()) {
+ fail(`${key} must be a non-empty string`, entry.line);
+ }
+ if (field === "documentation") {
+ httpsField(values, key);
+ }
+ target[field as "description" | "documentation" | "example"] =
+ entry.value;
+ }
+ }
+ return result;
+}
+
+export function parseTemplateManifest(source: string): TemplateManifest {
+ if (Buffer.byteLength(source, "utf8") > MAX_TEMPLATE_BYTES) {
+ fail(`file exceeds ${MAX_TEMPLATE_BYTES} bytes`);
+ }
+ const values = parseFlatToml(source);
+ const knownExact = new Set([
+ "schema",
+ "template.name",
+ "template.description",
+ "template.documentation",
+ "template.default_project_name",
+ "template.first_run.agent",
+ "template.first_run.prompt",
+ ]);
+ const knownPrefixes = [
+ "template.secrets.",
+ "template.runtime_variables.",
+ "template.connections.",
+ ];
+ for (const [key, entry] of values) {
+ if (
+ !knownExact.has(key) &&
+ !knownPrefixes.some((prefix) => key.startsWith(prefix))
+ ) {
+ fail(`unknown field ${key}`, entry.line);
+ }
+ }
+ const schema = values.get("schema");
+ if (schema?.value !== 1) fail("schema must be 1", schema?.line);
+ const name = stringField(values, "template.name", true)!;
+ const description = stringField(values, "template.description", true)!;
+ const documentation = httpsField(values, "template.documentation");
+ const defaultProjectName = stringField(
+ values,
+ "template.default_project_name",
+ );
+ if (defaultProjectName && !PROJECT_NAME_PATTERN.test(defaultProjectName)) {
+ fail(
+ "template.default_project_name must use lowercase letters, numbers, and single hyphens",
+ values.get("template.default_project_name")?.line,
+ );
+ }
+ const firstRunAgent = stringField(values, "template.first_run.agent");
+ const firstRunPrompt = stringField(values, "template.first_run.prompt");
+ if (Boolean(firstRunAgent) !== Boolean(firstRunPrompt)) {
+ fail(
+ "template.first_run.agent and template.first_run.prompt must be provided together",
+ );
+ }
+ return {
+ schema: 1,
+ template: {
+ name,
+ description,
+ ...(documentation ? { documentation } : {}),
+ ...(defaultProjectName ? { defaultProjectName } : {}),
+ ...(firstRunAgent && firstRunPrompt
+ ? { firstRun: { agent: firstRunAgent, prompt: firstRunPrompt } }
+ : {}),
+ secrets: annotations(values, "template.secrets", false),
+ runtimeVariables: annotations(values, "template.runtime_variables", true),
+ connections: annotations(values, "template.connections", false),
+ },
+ };
+}
+
+export async function readTemplateManifest(
+ root = process.cwd(),
+): Promise<TemplateManifest> {
+ const path = resolve(root, TEMPLATE_FILE);
+ const metadata = await stat(path).catch(() => undefined);
+ if (!metadata?.isFile()) fail(`expected a regular file at ${path}`);
+ if (metadata.size > MAX_TEMPLATE_BYTES)
+ fail(`file exceeds ${MAX_TEMPLATE_BYTES} bytes`);
+ return parseTemplateManifest(await readFile(path, "utf8"));
+}
+
+export async function buildTemplateProject(
+ root = process.cwd(),
+): Promise<TemplateBuildBundle> {
+ const template = await readTemplateManifest(root);
+ const sources = await readProjectAgents(root);
+ const projectResources = await readProjectResources(root);
+ const artifacts: TemplateBuildArtifact[] = [];
+ const secretRequirements = new Map<
+ string,
+ {
+ name: string;
+ description?: string;
+ documentation?: string;
+ required: boolean;
+ localAgentId: string;
+ allowedOrigins: Set<string>;
+ }
+ >();
+ const compiledConnections = new Set<string>();
+ for (const source of sources) {
+ const built = await buildAgentArtifact(source.root);
+ artifacts.push({
+ localAgentId: source.localId,
+ name: built.name,
+ digest: built.digest,
+ size: built.body.byteLength,
+ contentType: "application/vnd.opencomputer.agent+json",
+ body: built.body.toString("utf8"),
+ connections: built.connections,
+ httpConnections: built.httpConnections,
+ });
+ for (const connection of built.connections)
+ compiledConnections.add(connection);
+ for (const connection of built.httpConnections) {
+ compiledConnections.add(connection.id);
+ for (const header of Object.values(connection.headers)) {
+ if (typeof header === "string") continue;
+ const key = `${source.localId}:${header.name}`;
+ const annotation = template.template.secrets[header.name];
+ const requirement = secretRequirements.get(key) ?? {
+ name: header.name,
+ ...(annotation?.description
+ ? { description: annotation.description }
+ : {}),
+ ...(annotation?.documentation
+ ? { documentation: annotation.documentation }
+ : {}),
+ required: annotation?.required ?? true,
+ localAgentId: source.localId,
+ allowedOrigins: new Set<string>(),
+ };
+ requirement.allowedOrigins.add(connection.origin);
+ secretRequirements.set(key, requirement);
+ }
+ }
+ }
+ const compiledSecretNames = new Set(
+ [...secretRequirements.values()].map((requirement) => requirement.name),
+ );
+ for (const name of Object.keys(template.template.secrets)) {
+ if (!compiledSecretNames.has(name)) {
+ throw new Error(
+ `${TEMPLATE_FILE}: template.secrets.${name} is not referenced by a compiled connection`,
+ );
+ }
+ }
+ for (const id of Object.keys(template.template.connections)) {
+ if (!compiledConnections.has(id)) {
+ throw new Error(
+ `${TEMPLATE_FILE}: template.connections.${id} is not present in the compiled project`,
+ );
+ }
+ }
+ if (
+ template.template.firstRun &&
+ !sources.some(
+ (source) => source.localId === template.template.firstRun?.agent,
+ )
+ ) {
+ throw new Error(
+ `${TEMPLATE_FILE}: template.first_run.agent does not name a project agent`,
+ );
+ }
+ return {
+ schema: 1,
+ template: template.template,
+ agents: sources.map((source) => ({
+ id: source.localId,
+ name: source.manifest.name,
+ })),
+ artifacts,
+ resources: projectResources.manifest,
+ requirements: {
+ secrets: [...secretRequirements.values()].map((requirement) => ({
+ ...requirement,
+ allowedOrigins: [...requirement.allowedOrigins].sort(),
+ })),
+ runtimeVariables: Object.entries(template.template.runtimeVariables).map(
+ ([name, requirement]) => ({
+ name,
+ ...(requirement.description
+ ? { description: requirement.description }
+ : {}),
+ ...(requirement.documentation
+ ? { documentation: requirement.documentation }
+ : {}),
+ required: requirement.required ?? false,
+ ...(requirement.example ? { example: requirement.example } : {}),
+ }),
+ ),
+ connections: Object.entries(template.template.connections).map(
+ ([id, requirement]) => ({
+ id,
+ ...(requirement.description
+ ? { description: requirement.description }
+ : {}),
+ }),
+ ),
+ },
+ };
+}
+
+export function normalizeTemplateRepositoryUrl(value: string): string {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error(
+ "Repository URL must be https://github.com/<owner>/<repository>",
+ );
+ }
+ const parts = url.pathname.split("/").filter(Boolean);
+ if (
+ url.protocol !== "https:" ||
+ url.hostname.toLowerCase() !== "github.com" ||
+ url.username ||
+ url.password ||
+ url.port ||
+ url.search ||
+ url.hash ||
+ parts.length !== 2 ||
+ !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(parts[0]!) ||
+ !/^[A-Za-z0-9._-]+$/.test(parts[1]!) ||
+ parts[1]!.endsWith(".git")
+ ) {
+ throw new Error(
+ "Repository URL must be https://github.com/<owner>/<repository> without a ref or query",
+ );
+ }
+ return `https://github.com/${parts[0]}/${parts[1]}`;
+}
+
+export function templateDeployUrl(
+ repositoryUrl: string,
+ appUrl = "https://app.opencomputer.dev",
+): string {
+ const target = new URL("/new", appUrl);
+ target.searchParams.set(
+ "repository-url",
+ normalizeTemplateRepositoryUrl(repositoryUrl),
+ );
+ return target.toString();
+}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 7e8cca50..d52d6614 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -63,6 +63,40 @@ describe("managed agents proxy", () => {
).resolves.toBe(true);
});
+ it("streams project source without exposing upstream headers", async () => {
+ const fetchSpy = vi.fn(async (target: RequestInfo | URL) => {
+ expect(String(target)).toBe(
+ "https://managedagents.test/v1/projects/prj_test/source-archive",
+ );
+ return new Response("project archive", {
+ headers: {
+ "content-type": "application/gzip",
+ "content-disposition": 'attachment; filename="project.tar.gz"',
+ "x-storage-provider": "private",
+ },
+ });
+ });
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/projects/prj_test/source-archive",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test", role: "admin" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe("project archive");
+ expect(response.headers.get("content-type")).toBe("application/gzip");
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ expect(response.headers.get("x-storage-provider")).toBeNull();
+ });
+
it("reads BYOK eligibility from an active Autumn subscription", async () => {
vi.stubGlobal(
"fetch",
@@ -554,6 +588,162 @@ describe("managed agents proxy", () => {
expect(JSON.stringify(body)).not.toContain("private-account");
});
+ it("exposes public template provenance on a project overview", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json({
+ project: {
+ id: "prj_test",
+ slug: "example",
+ name: "Example",
+ environments: [],
+ agents: [{ id: "reviewer", name: "Reviewer" }],
+ createdAt: "2026-09-02",
+ updatedAt: "2026-09-02",
+ },
+ templateSource: {
+ repositoryUrl: "https://github.com/diggerhq/example",
+ commitSha: "a".repeat(40),
+ cloneReady: true,
+ mirrorRepoId: "must-not-leak",
+ },
+ sessions: [],
+ deployments: [],
+ connections: [],
+ channels: [],
+ schedules: [],
+ files: [],
+ schema: {},
+ }),
+ ),
+ );
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_test",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ const body = await response.json();
+ expect(body).toMatchObject({
+ templateSource: {
+ repositoryUrl: "https://github.com/diggerhq/example",
+ commitSha: "a".repeat(40),
+ cloneReady: true,
+ },
+ });
+ expect(JSON.stringify(body)).not.toContain("mirrorRepoId");
+ });
+
+ it("proxies template inspection through the authenticated managed-agent boundary", async () => {
+ const fetchSpy = vi.fn(
+ async (_request: URL | RequestInfo, init?: RequestInit) => {
+ expect(
+ new Headers(init?.headers).get("x-opencomputer-agent-token"),
+ ).toBeTruthy();
+ return Response.json({
+ id: "tin_test",
+ repository: {
+ url: "https://github.com/diggerhq/example",
+ fullName: "diggerhq/example",
+ defaultBranch: "main",
+ commitSha: "a".repeat(40),
+ },
+ template: { name: "Example", description: "Example agent" },
+ agents: [{ id: "example", name: "Example" }],
+ requirements: {
+ secrets: [],
+ runtimeVariables: [],
+ connections: [],
+ },
+ expiresAt: "2026-09-01T01:00:00.000Z",
+ builderCredential: "must-not-leak",
+ });
+ },
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/template-inspections",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ repositoryUrl: "https://github.com/diggerhq/example",
+ }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(200);
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ expect(JSON.stringify(await response.json())).not.toContain(
+ "builderCredential",
+ );
+ });
+
+ it("reports a missing root template manifest without leaking builder details", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ {
+ error: {
+ code: "template_sync_failed",
+ message:
+ "/usr/local/bin/node failed: opencomputer: oc-template.toml: expected a regular file at /tmp/template/source/oc-template.toml",
+ },
+ },
+ { status: 422 },
+ ),
+ ),
+ );
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/template-inspections",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ repositoryUrl: "https://github.com/diggerhq/not-a-template",
+ }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(422);
+ const body = await response.json();
+ expect(body).toEqual({
+ error: {
+ code: "template_manifest_missing",
+ message:
+ "This is not a valid template: oc-template.toml is missing from the repository root.",
+ },
+ });
+ expect(JSON.stringify(body)).not.toMatch(/\/tmp\/|\/usr\/local|trigger/i);
+ });
+
it("exposes a sanitized active deployment for agent details", async () => {
vi.stubGlobal(
"fetch",
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index e0652274..5d1f868f 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -132,15 +132,29 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
typeof (body as { error: unknown }).error === "object"
? (body as { error: Record<string, unknown> }).error
: null;
- const backendCode =
- typeof backendError?.code === "string" &&
- /^[a-z][a-z0-9_]{0,63}$/.test(backendError.code)
+ const backendErrorType =
+ typeof backendError?.code === "string"
? backendError.code
- : "agent_request_failed";
+ : typeof backendError?.type === "string"
+ ? backendError.type
+ : "";
+ const backendCode = /^[a-z][a-z0-9_]{0,63}$/.test(backendErrorType)
+ ? backendErrorType
+ : "agent_request_failed";
const backendMessage =
typeof backendError?.message === "string" ? backendError.message : "";
+ const missingTemplateManifest =
+ backendCode === "template_sync_failed" &&
+ backendMessage.includes("oc-template.toml") &&
+ backendMessage.includes("expected a regular file");
+ const publicCode = missingTemplateManifest
+ ? "template_manifest_missing"
+ : backendCode;
let message = "The agent request could not be completed.";
- if (upstream.status === 400) {
+ if (missingTemplateManifest) {
+ message =
+ "This is not a valid template: oc-template.toml is missing from the repository root.";
+ } else if (upstream.status === 400) {
message =
backendCode === "invalid_agent_name"
? "Agent names must use lowercase letters, numbers, and hyphens."
@@ -184,7 +198,7 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
const retryAfter = upstream.headers.get("retry-after");
if (retryAfter) headers.set("retry-after", retryAfter);
return new Response(
- JSON.stringify({ error: { code: backendCode, message } }),
+ JSON.stringify({ error: { code: publicCode, message } }),
{ status: upstream.status, headers },
);
}
@@ -530,6 +544,106 @@ function publicEventData(
);
}
+function publicTemplateInspection(value: unknown): Record<string, unknown> {
+ const inspection = record(value) ?? {};
+ if (inspection.status === "preparing") {
+ return {
+ id: inspection.id,
+ status: "preparing",
+ repositoryUrl: inspection.repositoryUrl,
+ retryAfterMs: inspection.retryAfterMs,
+ };
+ }
+ const repository = record(inspection.repository) ?? {};
+ const template = record(inspection.template) ?? {};
+ const firstRun = record(template.firstRun);
+ const requirements = record(inspection.requirements) ?? {};
+ return {
+ id: inspection.id,
+ repository: {
+ url: repository.url,
+ fullName: repository.fullName,
+ defaultBranch: repository.defaultBranch,
+ commitSha: repository.commitSha,
+ },
+ template: {
+ name: template.name,
+ description: template.description,
+ ...(template.documentation
+ ? { documentation: template.documentation }
+ : {}),
+ ...(template.defaultProjectName
+ ? { defaultProjectName: template.defaultProjectName }
+ : {}),
+ ...(firstRun
+ ? { firstRun: { agent: firstRun.agent, prompt: firstRun.prompt } }
+ : {}),
+ },
+ agents: Array.isArray(inspection.agents)
+ ? inspection.agents.map((value) => {
+ const agent = record(value) ?? {};
+ return { id: agent.id, name: agent.name };
+ })
+ : [],
+ requirements: {
+ secrets: Array.isArray(requirements.secrets)
+ ? requirements.secrets.map((value) => {
+ const requirement = record(value) ?? {};
+ return {
+ name: requirement.name,
+ description: requirement.description,
+ documentation: requirement.documentation,
+ ...(typeof requirement.required === "boolean"
+ ? { required: requirement.required }
+ : {}),
+ agentId: requirement.agentId,
+ allowedOrigins: strings(requirement.allowedOrigins),
+ };
+ })
+ : [],
+ runtimeVariables: Array.isArray(requirements.runtimeVariables)
+ ? requirements.runtimeVariables.map((value) => {
+ const requirement = record(value) ?? {};
+ return {
+ name: requirement.name,
+ description: requirement.description,
+ documentation: requirement.documentation,
+ required: requirement.required === true,
+ example: requirement.example,
+ agentId: requirement.agentId,
+ };
+ })
+ : [],
+ connections: Array.isArray(requirements.connections)
+ ? requirements.connections.map((value) => {
+ const requirement = record(value) ?? {};
+ return {
+ id: requirement.id,
+ description: requirement.description,
+ provider: requirement.provider,
+ permissions: strings(requirement.permissions),
+ };
+ })
+ : [],
+ },
+ expiresAt: inspection.expiresAt,
+ };
+}
+
+function publicTemplateInstallation(value: unknown): Record<string, unknown> {
+ const installation = record(value) ?? {};
+ const error = record(installation.error);
+ return {
+ id: installation.id,
+ inspectionId: installation.inspectionId,
+ projectId: installation.projectId,
+ projectAgentId: installation.projectAgentId,
+ projectUrl: installation.projectUrl,
+ state: installation.state,
+ ...(error ? { error: { stage: error.stage, message: error.message } } : {}),
+ };
+}
+
function publicSuccessBody(
method: string,
suffix: string,
@@ -611,8 +725,20 @@ function publicSuccessBody(
}
if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) {
const project = publicProject(body.project);
+ const templateSource = record(body.templateSource);
return {
project,
+ ...(templateSource &&
+ typeof templateSource.repositoryUrl === "string" &&
+ typeof templateSource.commitSha === "string"
+ ? {
+ templateSource: {
+ repositoryUrl: templateSource.repositoryUrl,
+ commitSha: templateSource.commitSha,
+ cloneReady: templateSource.cloneReady === true,
+ },
+ }
+ : {}),
sessions: stripPrivateValues(body.sessions ?? []),
deployments: Array.isArray(body.deployments)
? body.deployments.map(publicDeployment)
@@ -631,6 +757,17 @@ function publicSuccessBody(
if (method === "GET" && suffix === "/me") {
return stripPrivateValues(body);
}
+ if (method === "POST" && suffix === "/template-inspections") {
+ return publicTemplateInspection(body);
+ }
+ if (
+ (method === "POST" && suffix === "/template-installations") ||
+ (method === "GET" && /^\/template-installations\/[^/]+$/.test(suffix)) ||
+ (method === "POST" &&
+ /^\/template-installations\/[^/]+\/finalize$/.test(suffix))
+ ) {
+ return publicTemplateInstallation(body);
+ }
if (method === "GET" && suffix === "/model-access/connections") {
return {
data: Array.isArray(body.data)
@@ -969,12 +1106,26 @@ async function deploySourceAgent(
}
function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
+ if (method === "POST" && suffix === "/template-inspections") return true;
+ if (method === "POST" && suffix === "/template-installations") return true;
+ if (method === "GET" && /^\/template-installations\/[^/]+$/.test(suffix)) {
+ return true;
+ }
+ if (
+ method === "POST" &&
+ /^\/template-installations\/[^/]+\/finalize$/.test(suffix)
+ ) {
+ return true;
+ }
if (method === "GET" && suffix === "/agents") return true;
if (method === "GET" && suffix === "/me") return true;
if ((method === "GET" || method === "POST") && suffix === "/projects") {
return true;
}
if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) return true;
+ if (method === "GET" && /^\/projects\/[^/]+\/source-archive$/.test(suffix)) {
+ return true;
+ }
if (
(method === "GET" || method === "PUT" || method === "DELETE") &&
/^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)
@@ -1446,6 +1597,24 @@ export async function proxyManagedAgents(
const upstream = await fetch(target, init);
if (!upstream.ok) return publicErrorResponse(upstream);
if (upstream.status === 204) return new Response(null, { status: 204 });
+ if (/^\/projects\/[^/]+\/source-archive$/.test(suffix)) {
+ const responseHeaders = new Headers();
+ for (const name of [
+ "content-type",
+ "content-length",
+ "content-disposition",
+ "etag",
+ ]) {
+ const value = upstream.headers.get(name);
+ if (value) responseHeaders.set(name, value);
+ }
+ responseHeaders.set("cache-control", "private, no-store");
+ return new Response(upstream.body, {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers: responseHeaders,
+ });
+ }
if (suffix.startsWith("/openrouter/")) {
return upstream;
}
diff --git a/create-start/package.json b/create-start/package.json
index de0f4541..9134d84a 100644
--- a/create-start/package.json
+++ b/create-start/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/create-start",
- "version": "0.6.6",
+ "version": "0.6.7",
"description": "Create a hello-world OpenComputer agent application.",
"type": "module",
"bin": {
@@ -18,7 +18,7 @@
"node": ">=22.0.0"
},
"dependencies": {
- "@opencomputer/cli": "0.6.6"
+ "@opencomputer/cli": "0.6.7"
},
"publishConfig": {
"access": "public"
diff --git a/docs/agents/examples/feature-flag-hygiene.mdx b/docs/agents/examples/feature-flag-hygiene.mdx
index 52ba00df..dfe2589b 100644
--- a/docs/agents/examples/feature-flag-hygiene.mdx
+++ b/docs/agents/examples/feature-flag-hygiene.mdx
@@ -9,13 +9,16 @@ combines an interactive agent, remote MCP servers, code-defined tools, and a
schedule in one project.
<Card
- title="OpenComputer × Unleash feature flag hygiene"
- icon="github"
- href="https://github.com/diggerhq/opencomputer-example-unleash"
+ title="Deploy to OpenComputer"
+ icon="rocket"
+ href="https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-unleash"
>
- Clone the complete agent, schedule, and fixture application from GitHub.
+ Configure the GitHub and Unleash credentials, then deploy the complete agent
+ and schedule to Development.
</Card>
+[Browse the source on GitHub](https://github.com/diggerhq/opencomputer-example-unleash).
+
## How it works
```mermaid
diff --git a/docs/agents/examples/github-actions-triage.mdx b/docs/agents/examples/github-actions-triage.mdx
index f6c480d5..b19bb728 100644
--- a/docs/agents/examples/github-actions-triage.mdx
+++ b/docs/agents/examples/github-actions-triage.mdx
@@ -33,13 +33,16 @@ cannot rerun workflows, modify the repository, or call Slack directly.
## Start with the example
<Card
- title="GitHub Actions triage agent"
- icon="github"
- href="https://github.com/diggerhq/opencomputer-example-actions-triage"
+ title="Deploy to OpenComputer"
+ icon="rocket"
+ href="https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-actions-triage"
>
- Clone the complete agent project and GitHub Actions workflows from GitHub.
+ Deploy the project to Development, then configure its Slack channel and
+ webhook.
</Card>
+[Browse the source on GitHub](https://github.com/diggerhq/opencomputer-example-actions-triage).
+
```bash
git clone https://github.com/diggerhq/opencomputer-example-actions-triage.git
cd opencomputer-example-actions-triage
diff --git a/docs/agents/examples/gtm-engineer.mdx b/docs/agents/examples/gtm-engineer.mdx
index 39b3fdf1..5f23f6d4 100644
--- a/docs/agents/examples/gtm-engineer.mdx
+++ b/docs/agents/examples/gtm-engineer.mdx
@@ -33,12 +33,15 @@ cadences and skip overlapping runs.
## Start with the example
<Card
- title="OpenComputer GTM engineer"
- icon="github"
- href="https://github.com/diggerhq/opencomputer-example-gtm"
+ title="Deploy to OpenComputer"
+ icon="rocket"
+ href="https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-gtm"
>
- Clone the complete GTM agent and its schedule definitions from GitHub.
+ Configure research credentials and deploy the agent and schedules to
+ Development.
</Card>
+[Browse the source on GitHub](https://github.com/diggerhq/opencomputer-example-gtm).
+
The repository README covers installation, setting the Exa secret, testing in
the debug playground, running schedule payloads, and deploying the agent.
diff --git a/docs/agents/examples/pr-review.mdx b/docs/agents/examples/pr-review.mdx
index d8e585d9..4650cc98 100644
--- a/docs/agents/examples/pr-review.mdx
+++ b/docs/agents/examples/pr-review.mdx
@@ -96,13 +96,15 @@ flowchart LR
## Run it
<Card
- title="OpenComputer Pull Request Reviewer"
- icon="github"
- href="https://github.com/diggerhq/opencomputer-example-pr-review"
+ title="Deploy to OpenComputer"
+ icon="rocket"
+ href="https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-pr-review"
>
- Clone the complete agent, tools, and tests from GitHub.
+ Configure the GitHub credential and deploy the agent to Development.
</Card>
+[Browse the source on GitHub](https://github.com/diggerhq/opencomputer-example-pr-review).
+
```bash
git clone https://github.com/diggerhq/opencomputer-example-pr-review.git
cd opencomputer-example-pr-review
diff --git a/docs/agents/examples/test-coverage.mdx b/docs/agents/examples/test-coverage.mdx
index 71bed9a7..2759890b 100644
--- a/docs/agents/examples/test-coverage.mdx
+++ b/docs/agents/examples/test-coverage.mdx
@@ -45,13 +45,15 @@ before it can write to GitHub.
## Start with the example
<Card
- title="Test coverage agent"
- icon="github"
- href="https://github.com/diggerhq/opencomputer-example-test-coverage"
+ title="Deploy to OpenComputer"
+ icon="rocket"
+ href="https://app.opencomputer.dev/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-test-coverage"
>
- Clone the complete agent, publishing policy, and policy tests from GitHub.
+ Review the GitHub credential boundary and deploy the agent to Development.
</Card>
+[Browse the source on GitHub](https://github.com/diggerhq/opencomputer-example-test-coverage).
+
```bash
git clone https://github.com/diggerhq/opencomputer-example-test-coverage.git
cd opencomputer-example-test-coverage
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 83f5a9ec..2ba734fe 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -31,6 +31,7 @@ const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))
const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))
const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))
const ManagedAgentChannels = lazy(() => import('./managed-agents/Channels'))
+const ManagedTemplateNew = lazy(() => import('./managed-agents/TemplateNew'))
const ModelAccessCallback = lazy(
() => import('./managed-agents/ModelAccessCallback'),
)
@@ -80,6 +81,7 @@ export default function App() {
path="managed-agents/new"
element={<Navigate to="/" replace />}
/>
+ <Route path="new" element={<ManagedTemplateNew />} />
<Route
path="projects/:projectId"
element={<ManagedProjectDetail />}
diff --git a/web/src/api/client-errors.test.ts b/web/src/api/client-errors.test.ts
index c101c4ca..665aadf6 100644
--- a/web/src/api/client-errors.test.ts
+++ b/web/src/api/client-errors.test.ts
@@ -37,4 +37,32 @@ describe('api errors', () => {
},
})
})
+
+ it('accepts code as the typed discriminator for edge API errors', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() =>
+ Promise.resolve(
+ Response.json(
+ {
+ error: {
+ code: 'template_manifest_missing',
+ message: 'The root manifest is missing.',
+ },
+ },
+ { status: 422 },
+ ),
+ ),
+ ),
+ )
+
+ const error = await apiFetch('/managed-agents/template-inspections').catch(
+ (caught: unknown) => caught,
+ )
+ expect(error).toMatchObject({
+ status: 422,
+ type: 'template_manifest_missing',
+ message: 'The root manifest is missing.',
+ })
+ })
})
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index dfbf6943..3e04a332 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -109,17 +109,15 @@ function errorMessage(body: unknown, status: number): string {
return `Request failed: ${status}`
}
-// The typed discriminator sessions-api puts on `{error:{type,…}}` (e.g.
-// "insufficient_credits"), so callers can branch on the reason, not the status alone.
+// The typed discriminator APIs put on `{error:{type,…}}` or
+// `{error:{code,…}}`, so callers can branch on the reason, not the status alone.
function errorType(body: unknown): string | undefined {
if (body && typeof body === 'object') {
const err = (body as Record<string, unknown>).error
- if (
- err &&
- typeof err === 'object' &&
- typeof (err as Record<string, unknown>).type === 'string'
- ) {
- return (err as Record<string, unknown>).type as string
+ if (err && typeof err === 'object') {
+ const structured = err as Record<string, unknown>
+ if (typeof structured.type === 'string') return structured.type
+ if (typeof structured.code === 'string') return structured.code
}
}
return undefined
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 577bdae7..5d6a39a4 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -1,4 +1,4 @@
-import { useLayoutEffect, useMemo, useRef, useState } from 'react'
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useChat } from '@ai-sdk/react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { isDynamicToolUIPart, type DynamicToolUIPart, type UIMessage } from 'ai'
@@ -35,6 +35,14 @@ import {
import { ResourceTable, type Column } from '@/components/resource-table'
import { StatusBadge } from '@/components/status-badge'
import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog'
import { notifyError } from '@/lib/errors'
import { cn } from '@/lib/utils'
import {
@@ -69,6 +77,10 @@ import { ManagedAgentSchedules } from './Schedules'
import { ManagedAgentWebhooks } from './Webhooks'
import { ManagedProjectBYOK } from './BYOK'
import { AgentMarkdown } from './AgentMarkdown'
+import {
+ projectCloneCommand,
+ templateFirstRunPrompt,
+} from './template-continuation'
type DetailTab =
| 'playground'
@@ -189,11 +201,15 @@ function PlaygroundChat({
agentId,
session,
events,
+ initialPrompt,
+ onInitialPromptConsumed,
onSessionFinished,
}: {
agentId: string
session?: ManagedAgentSession
events: ManagedAgentEvent[]
+ initialPrompt?: string
+ onInitialPromptConsumed?: () => void
onSessionFinished?: (sessionId: string) => void
}) {
const queryClient = useQueryClient()
@@ -207,6 +223,7 @@ function PlaygroundChat({
const composerRef = useRef<HTMLDivElement>(null)
const followOutputRef = useRef(true)
const initializedScrollRef = useRef(false)
+ const initialPromptSentRef = useRef(false)
const initialMessages = useMemo(
() => historicalMessages(session, events),
[events, session],
@@ -250,6 +267,14 @@ function PlaygroundChat({
session?.status === 'running' ||
session?.status === 'waiting_runtime'
+ useEffect(() => {
+ if (!initialPrompt || session || initialPromptSentRef.current) return
+ initialPromptSentRef.current = true
+ onInitialPromptConsumed?.()
+ followOutputRef.current = true
+ void sendMessage({ text: initialPrompt })
+ }, [initialPrompt, onInitialPromptConsumed, sendMessage, session])
+
useLayoutEffect(() => {
const timeline = timelineRef.current
if (!timeline) return
@@ -475,6 +500,7 @@ export default function ManagedAgentDetail({
const agentId = agentIdOverride ?? params.agentId ?? ''
const [standaloneTab, setStandaloneTab] = useState<DetailTab>('playground')
const [starterCopied, setStarterCopied] = useState(false)
+ const [continuationCopied, setContinuationCopied] = useState(false)
const routeTab = params.tab as DetailTab | undefined
const projectTabs = new Set<DetailTab>([
'playground',
@@ -497,6 +523,7 @@ export default function ManagedAgentDetail({
? 'production'
: 'development'
const requestedPlaygroundId = playgroundSessionIdFromSearch(location.search)
+ const firstRunPrompt = templateFirstRunPrompt(location.state)
const [newSessionKey, setNewSessionKey] = useState(() => crypto.randomUUID())
const agents = useQuery({
@@ -566,6 +593,11 @@ export default function ManagedAgentDetail({
queryFn: () => getManagedAgentSessionEvents(selectedPlaygroundId!),
enabled: Boolean(selectedPlaygroundId),
})
+ const continuationCommand =
+ project?.templateSource?.cloneReady &&
+ projectCloneCommand(project.project.id)
+ const continuationPreparing =
+ project?.templateSource && !project.templateSource.cloneReady
const selectPlaygroundSession = (sessionId?: string) => {
void navigate({
@@ -679,11 +711,54 @@ export default function ManagedAgentDetail({
: 'Loading active deployment…'
}
actions={
- project ? undefined : (
+ project && continuationCommand ? (
+ <Dialog
+ onOpenChange={(open) => {
+ if (!open) setContinuationCopied(false)
+ }}
+ >
+ <DialogTrigger asChild>
+ <Button variant="outline" size="sm">
+ <TerminalSquare /> Continue locally
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>Continue locally</DialogTitle>
+ <DialogDescription>
+ Clone the exact source deployed here and link it to this
+ existing project.
+ </DialogDescription>
+ </DialogHeader>
+ <pre className="overflow-x-auto rounded-md border p-3 text-xs leading-5">
+ <code>{continuationCommand}</code>
+ </pre>
+ <div className="flex justify-end">
+ <Button
+ onClick={() => {
+ void navigator.clipboard
+ .writeText(continuationCommand)
+ .then(() => setContinuationCopied(true))
+ .catch((error) =>
+ notifyError("Couldn't copy the command.", error),
+ )
+ }}
+ >
+ {continuationCopied ? <Check /> : <Clipboard />}
+ {continuationCopied ? 'Copied' : 'Copy command'}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ ) : project && continuationPreparing ? (
+ <Button variant="outline" size="sm" disabled>
+ <Loader2 className="animate-spin" /> Preparing local checkout
+ </Button>
+ ) : !project ? (
<Button asChild variant="outline" size="sm">
<Link to="/">All projects</Link>
</Button>
- )
+ ) : undefined
}
className={activeTab === 'playground' ? 'mb-0 shrink-0' : undefined}
/>
@@ -862,6 +937,13 @@ export default function ManagedAgentDetail({
agentId={project ? `${agentId}@${environment}` : agentId}
session={selectedPlayground}
events={selectedPlaygroundEvents.data ?? []}
+ initialPrompt={firstRunPrompt}
+ onInitialPromptConsumed={() => {
+ void navigate(
+ { pathname: location.pathname, search: location.search },
+ { replace: true, state: null },
+ )
+ }}
onSessionFinished={selectPlaygroundSession}
/>
)}
diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsx
index f178baa7..02308295 100644
--- a/web/src/managed-agents/Home.tsx
+++ b/web/src/managed-agents/Home.tsx
@@ -1,16 +1,16 @@
import { FormEvent, useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { Link, useNavigate } from 'react-router-dom'
import {
- Check,
+ ChevronLeft,
ChevronRight,
- Clipboard,
+ FolderGit2,
FolderKanban,
Loader2,
Plus,
+ Rocket,
Sparkles,
} from 'lucide-react'
-import { toast } from 'sonner'
import { EmptyState } from '@/components/empty-state'
import { PageHeader } from '@/components/page-header'
import { Panel, PanelContent } from '@/components/panel'
@@ -23,46 +23,41 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
-import { notifyError } from '@/lib/errors'
-import { createManagedProject, getManagedProjects } from './api'
-import { starterCommandBlock, starterCopyCommand } from './onboarding'
+import { getManagedProjects } from './api'
+import {
+ CURATED_TEMPLATES,
+ HELLO_WORLD_TEMPLATE_REPOSITORY,
+ templateDeployPath,
+} from './templates'
+
+type CreateStep = 'choose' | 'templates'
export default function ProjectsHome() {
const navigate = useNavigate()
- const queryClient = useQueryClient()
const [dialogOpen, setDialogOpen] = useState(false)
- const [name, setName] = useState('')
- const [copied, setCopied] = useState(false)
+ const [createStep, setCreateStep] = useState<CreateStep>('choose')
+ const [repositoryUrl, setRepositoryUrl] = useState('')
const projects = useQuery({
queryKey: ['managed-projects'],
queryFn: getManagedProjects,
})
- const createProject = useMutation({
- mutationFn: createManagedProject,
- onSuccess: async (project) => {
- await queryClient.invalidateQueries({ queryKey: ['managed-projects'] })
- setDialogOpen(false)
- setName('')
- navigate(`/projects/${encodeURIComponent(project.id)}`)
- },
- onError: (error) => notifyError("Couldn't create the project.", error),
- })
const items = projects.data ?? []
- function submit(event: FormEvent) {
- event.preventDefault()
- const value = name.trim()
- if (value) createProject.mutate(value)
+ function openCreate() {
+ setCreateStep('choose')
+ setRepositoryUrl('')
+ setDialogOpen(true)
}
- async function copyCommand() {
- try {
- await navigator.clipboard.writeText(starterCopyCommand('hello-world'))
- setCopied(true)
- toast.success('Command copied')
- } catch (error) {
- notifyError("Couldn't copy the command.", error)
- }
+ function openTemplate(url: string) {
+ setDialogOpen(false)
+ void navigate(templateDeployPath(url))
+ }
+
+ function submitRepository(event: FormEvent) {
+ event.preventDefault()
+ const url = repositoryUrl.trim()
+ if (url) openTemplate(url)
}
return (
@@ -72,7 +67,7 @@ export default function ProjectsHome() {
description="Choose a project to open its agent playground, deployments, sessions, and resources."
actions={
items.length > 0 ? (
- <Button onClick={() => setDialogOpen(true)}>
+ <Button onClick={openCreate}>
<Plus /> New project
</Button>
) : undefined
@@ -103,23 +98,16 @@ export default function ProjectsHome() {
<Sparkles className="size-3.5" /> Your first project
</div>
<h2 className="text-3xl font-semibold tracking-tight">
- Create your first project
+ Create your first agent
</h2>
<p className="text-muted-foreground mt-3 max-w-xl text-sm leading-6">
- Start with one hello-world agent. Your OpenComputer project is
- ready for more agents as it grows.
+ Start from a ready-to-run Hello World or choose an example. We’ll
+ deploy it and open its first Debug session.
</p>
- <pre className="bg-foreground text-background mt-5 overflow-x-auto rounded-lg px-4 py-3 text-sm leading-7">
- <code>{starterCommandBlock('hello-world')}</code>
- </pre>
- <div className="mt-6 flex flex-wrap gap-3">
- <Button onClick={() => setDialogOpen(true)}>
+ <div className="mt-6">
+ <Button onClick={openCreate}>
<Plus /> Create project
</Button>
- <Button variant="outline" onClick={() => void copyCommand()}>
- {copied ? <Check /> : <Clipboard />}
- {copied ? 'Copied' : 'Copy command'}
- </Button>
</div>
</div>
</div>
@@ -157,43 +145,99 @@ export default function ProjectsHome() {
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
- <DialogContent className="sm:max-w-md">
+ <DialogContent className="sm:max-w-2xl">
<DialogHeader>
- <DialogTitle>Create project</DialogTitle>
+ <DialogTitle>
+ {createStep === 'choose'
+ ? 'Create project'
+ : 'Start from a template'}
+ </DialogTitle>
<DialogDescription>
- Projects can contain multiple agents and share channels, files,
- and schedules.
+ {createStep === 'choose'
+ ? 'Deploy a working first agent now. You can add more agents later.'
+ : 'Choose an example or deploy another public GitHub repository.'}
</DialogDescription>
</DialogHeader>
- <form className="space-y-4" onSubmit={submit}>
- <Input
- autoFocus
- value={name}
- onChange={(event) => setName(event.target.value)}
- placeholder="My first project"
- aria-label="Project name"
- />
- <div className="flex justify-end gap-2">
- <Button
+
+ {createStep === 'choose' ? (
+ <div className="grid gap-3 sm:grid-cols-2">
+ <button
type="button"
- variant="outline"
- onClick={() => setDialogOpen(false)}
+ autoFocus
+ className="hover:bg-muted/40 focus-visible:ring-ring/50 rounded-lg border p-5 text-left outline-none focus-visible:ring-3"
+ onClick={() => {
+ setDialogOpen(false)
+ void navigate(
+ templateDeployPath(HELLO_WORLD_TEMPLATE_REPOSITORY, true),
+ )
+ }}
>
- Cancel
- </Button>
+ <Rocket className="text-primary mb-4 size-5" />
+ <p className="font-medium">From scratch</p>
+ <p className="text-muted-foreground mt-1 text-sm leading-5">
+ Deploy a minimal Hello World and start its first Debug
+ session.
+ </p>
+ <span className="text-primary mt-4 inline-flex items-center gap-1 text-sm font-medium">
+ Quick start <ChevronRight className="size-4" />
+ </span>
+ </button>
+ <button
+ type="button"
+ className="hover:bg-muted/40 focus-visible:ring-ring/50 rounded-lg border p-5 text-left outline-none focus-visible:ring-3"
+ onClick={() => setCreateStep('templates')}
+ >
+ <FolderGit2 className="text-primary mb-4 size-5" />
+ <p className="font-medium">Start from a template</p>
+ <p className="text-muted-foreground mt-1 text-sm leading-5">
+ Begin with a complete example and configure its integrations.
+ </p>
+ <span className="text-primary mt-4 inline-flex items-center gap-1 text-sm font-medium">
+ Browse templates <ChevronRight className="size-4" />
+ </span>
+ </button>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <div className="grid max-h-[45vh] gap-2 overflow-y-auto pr-1 sm:grid-cols-2">
+ {CURATED_TEMPLATES.map((template) => (
+ <button
+ key={template.repositoryUrl}
+ type="button"
+ className="hover:bg-muted/40 focus-visible:ring-ring/50 rounded-lg border p-4 text-left outline-none focus-visible:ring-3"
+ onClick={() => openTemplate(template.repositoryUrl)}
+ >
+ <p className="text-sm font-medium">{template.name}</p>
+ <p className="text-muted-foreground mt-1 text-xs leading-5">
+ {template.description}
+ </p>
+ </button>
+ ))}
+ </div>
+ <form
+ className="flex gap-2 border-t pt-4"
+ onSubmit={submitRepository}
+ >
+ <Input
+ value={repositoryUrl}
+ onChange={(event) => setRepositoryUrl(event.target.value)}
+ placeholder="https://github.com/owner/repository"
+ aria-label="Template repository URL"
+ />
+ <Button type="submit" disabled={!repositoryUrl.trim()}>
+ Continue
+ </Button>
+ </form>
<Button
- type="submit"
- disabled={!name.trim() || createProject.isPending}
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setCreateStep('choose')}
>
- {createProject.isPending ? (
- <Loader2 className="animate-spin" />
- ) : (
- <Plus />
- )}
- Create project
+ <ChevronLeft /> Back
</Button>
</div>
- </form>
+ )}
</DialogContent>
</Dialog>
</div>
diff --git a/web/src/managed-agents/TemplateNew.test.ts b/web/src/managed-agents/TemplateNew.test.ts
new file mode 100644
index 00000000..c453098e
--- /dev/null
+++ b/web/src/managed-agents/TemplateNew.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { ApiError } from '@/api/client'
+import { templateInspectionError } from './template-inspection-error'
+
+describe('template inspection errors', () => {
+ it('presents a missing root manifest as an invalid template', () => {
+ expect(
+ templateInspectionError(
+ new ApiError(
+ 'This is not a valid template: oc-template.toml is missing from the repository root.',
+ 422,
+ 'template_manifest_missing',
+ ),
+ ),
+ ).toEqual({
+ title: 'Not a valid template',
+ description:
+ 'This repository does not contain oc-template.toml at its root.',
+ })
+ })
+
+ it('keeps a safe fallback for other inspection failures', () => {
+ expect(templateInspectionError(new Error('Service unavailable'))).toEqual({
+ title: 'This template could not be inspected',
+ description: 'Service unavailable',
+ })
+ })
+})
diff --git a/web/src/managed-agents/TemplateNew.tsx b/web/src/managed-agents/TemplateNew.tsx
new file mode 100644
index 00000000..52cc5906
--- /dev/null
+++ b/web/src/managed-agents/TemplateNew.tsx
@@ -0,0 +1,353 @@
+import { FormEvent, useEffect, useRef, useState } from 'react'
+import { useMutation, useQuery } from '@tanstack/react-query'
+import { ExternalLink, FolderGit2, Loader2, Rocket } from 'lucide-react'
+import { useNavigate, useSearchParams } from 'react-router-dom'
+import { EmptyState } from '@/components/empty-state'
+import { PageHeader } from '@/components/page-header'
+import {
+ Panel,
+ PanelContent,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { notifyError } from '@/lib/errors'
+import {
+ createManagedTemplateInstallation,
+ finalizeManagedTemplateInstallation,
+ getManagedTemplateInstallation,
+ inspectManagedTemplate,
+ putAgentRuntimeVariable,
+ putManagedProjectSecret,
+} from './api'
+import { templateInspectionError } from './template-inspection-error'
+import {
+ installedTemplateAgentId,
+ templatePlaygroundPath,
+} from './template-continuation'
+
+const GITHUB_REPOSITORY =
+ /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]+$/
+
+async function waitForInstallation(id: string) {
+ const deadline = Date.now() + 10 * 60_000
+ let installation = await getManagedTemplateInstallation(id)
+ while (
+ installation.state !== 'ready' &&
+ installation.state !== 'failed' &&
+ Date.now() < deadline
+ ) {
+ await new Promise((resolve) => setTimeout(resolve, 1_000))
+ installation = await getManagedTemplateInstallation(id)
+ }
+ return installation
+}
+
+export default function TemplateNew() {
+ const navigate = useNavigate()
+ const [searchParams] = useSearchParams()
+ const repositoryUrl = searchParams.get('repository-url')?.trim() ?? ''
+ const quickStart = searchParams.get('quick-start') === '1'
+ const validRepository = GITHUB_REPOSITORY.test(repositoryUrl)
+ const commandKey = useRef(crypto.randomUUID())
+ const [projectName, setProjectName] = useState('')
+ const [secrets, setSecrets] = useState<Record<string, string>>({})
+ const [variables, setVariables] = useState<Record<string, string>>({})
+ const inspection = useQuery({
+ queryKey: ['managed-template-inspection', repositoryUrl],
+ queryFn: () => inspectManagedTemplate(repositoryUrl),
+ enabled: validRepository,
+ retry: false,
+ })
+
+ useEffect(() => {
+ if (!inspection.data || projectName) return
+ setProjectName(
+ quickStart
+ ? 'My agent'
+ : (inspection.data.template.defaultProjectName ??
+ inspection.data.template.name),
+ )
+ setVariables(
+ Object.fromEntries(
+ inspection.data.requirements.runtimeVariables
+ .filter((requirement) => requirement.example)
+ .map((requirement) => [requirement.name, requirement.example!]),
+ ),
+ )
+ }, [inspection.data, projectName, quickStart])
+
+ const install = useMutation({
+ mutationFn: async () => {
+ const reviewed = inspection.data
+ if (!reviewed) throw new Error('Review the template first.')
+ const installation = await createManagedTemplateInstallation({
+ inspectionId: reviewed.id,
+ projectName: projectName.trim(),
+ idempotencyKey: commandKey.current,
+ })
+ const installationAgentId = (localAgentId?: string) =>
+ installedTemplateAgentId({
+ projectAgentId: installation.projectAgentId,
+ localAgentId,
+ primaryLocalAgentId: reviewed.agents[0]?.id,
+ })
+ for (const requirement of reviewed.requirements.secrets) {
+ const value = secrets[requirement.name]
+ if (!value && !requirement.required) continue
+ await putManagedProjectSecret({
+ projectId: installation.projectId,
+ environment: 'development',
+ agentId: installationAgentId(requirement.agentId),
+ name: requirement.name,
+ value: value ?? '',
+ allowedOrigins: requirement.allowedOrigins,
+ })
+ setSecrets((current) => ({ ...current, [requirement.name]: '' }))
+ }
+ for (const requirement of reviewed.requirements.runtimeVariables) {
+ const value = variables[requirement.name]?.trim()
+ if (!value) continue
+ await putAgentRuntimeVariable({
+ projectId: installation.projectId,
+ environment: 'development',
+ agentId: installationAgentId(requirement.agentId),
+ name: requirement.name,
+ value,
+ })
+ }
+ const finalized = await finalizeManagedTemplateInstallation(
+ installation.id,
+ )
+ return finalized.state === 'ready'
+ ? finalized
+ : waitForInstallation(finalized.id)
+ },
+ onSuccess: (result) => {
+ if (result.state === 'failed') {
+ notifyError(
+ "Couldn't deploy the template.",
+ new Error(result.error?.message ?? 'Template installation failed.'),
+ )
+ return
+ }
+ if (result.state !== 'ready') {
+ notifyError(
+ 'Template deployment is still running.',
+ new Error('Open the draft project to continue.'),
+ )
+ void navigate(result.projectUrl)
+ return
+ }
+ const firstRun = inspection.data?.template.firstRun
+ const projectAgentId = installedTemplateAgentId({
+ projectAgentId: result.projectAgentId,
+ localAgentId: firstRun?.agent,
+ primaryLocalAgentId: inspection.data?.agents[0]?.id,
+ })
+ void navigate(
+ templatePlaygroundPath({ projectId: result.projectId, projectAgentId }),
+ {
+ state: firstRun
+ ? { templateFirstRunPrompt: firstRun.prompt }
+ : undefined,
+ },
+ )
+ },
+ onError: (error) => notifyError("Couldn't deploy the template.", error),
+ })
+
+ function submit(event: FormEvent) {
+ event.preventDefault()
+ install.mutate()
+ }
+
+ if (!validRepository) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={FolderGit2}
+ title="Invalid template repository"
+ description="Use a root GitHub repository URL without a branch, path, query, or .git suffix. V1 resolves the repository's main branch server-side."
+ />
+ </Panel>
+ )
+ }
+
+ if (inspection.isLoading) {
+ return (
+ <div className="flex min-h-64 items-center justify-center">
+ <Loader2 className="text-muted-foreground size-5 animate-spin" />
+ </div>
+ )
+ }
+
+ if (quickStart && install.isPending) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={Rocket}
+ title="Deploying Hello World"
+ description="Creating your project and opening its first Debug session…"
+ />
+ </Panel>
+ )
+ }
+
+ if (inspection.isError || !inspection.data) {
+ const error = templateInspectionError(inspection.error)
+ return (
+ <Panel>
+ <EmptyState
+ icon={FolderGit2}
+ title={error.title}
+ description={error.description}
+ action={
+ <Button variant="outline" onClick={() => void inspection.refetch()}>
+ Try again
+ </Button>
+ }
+ />
+ </Panel>
+ )
+ }
+
+ const reviewed = inspection.data
+ const missingRequiredVariable = reviewed.requirements.runtimeVariables.some(
+ (requirement) =>
+ requirement.required && !variables[requirement.name]?.trim(),
+ )
+ const missingSecret = reviewed.requirements.secrets.some(
+ (requirement) => requirement.required && !secrets[requirement.name],
+ )
+
+ return (
+ <form className="space-y-6" onSubmit={submit}>
+ <PageHeader
+ title={quickStart ? 'Create your first agent' : reviewed.template.name}
+ description={
+ quickStart
+ ? 'Choose a name, then start its first Debug session.'
+ : reviewed.template.description
+ }
+ />
+ {!quickStart ? (
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>Source and deployment</PanelTitle>
+ </PanelHeader>
+ <PanelContent className="space-y-3 text-sm">
+ <a
+ className="inline-flex items-center gap-2 underline underline-offset-4"
+ href={reviewed.repository.url}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {reviewed.repository.fullName}
+ <ExternalLink className="size-3.5" />
+ </a>
+ <p className="text-muted-foreground font-mono text-xs">
+ main @ {reviewed.repository.commitSha.slice(0, 12)}
+ </p>
+ <p>
+ {reviewed.agents.length} agent
+ {reviewed.agents.length === 1 ? '' : 's'} · Development only
+ </p>
+ </PanelContent>
+ </Panel>
+ ) : null}
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>
+ {quickStart ? 'Name your agent' : 'Configure project'}
+ </PanelTitle>
+ </PanelHeader>
+ <PanelContent className="space-y-4">
+ <label className="block space-y-1.5 text-sm">
+ <span>{quickStart ? 'Agent name' : 'Project name'}</span>
+ <Input
+ value={projectName}
+ onChange={(event) => setProjectName(event.target.value)}
+ autoFocus={quickStart}
+ onFocus={(event) => {
+ if (quickStart) event.currentTarget.select()
+ }}
+ required
+ />
+ </label>
+ {reviewed.requirements.secrets.map((requirement) => (
+ <label key={requirement.name} className="block space-y-1.5 text-sm">
+ <span>
+ {requirement.name}
+ {requirement.required ? '' : ' (optional)'}
+ </span>
+ {requirement.description ? (
+ <span className="text-muted-foreground block text-xs">
+ {requirement.description} Stored write-only for Development.
+ </span>
+ ) : null}
+ <Input
+ type="password"
+ autoComplete="off"
+ value={secrets[requirement.name] ?? ''}
+ onChange={(event) =>
+ setSecrets((current) => ({
+ ...current,
+ [requirement.name]: event.target.value,
+ }))
+ }
+ required={requirement.required}
+ />
+ </label>
+ ))}
+ {reviewed.requirements.runtimeVariables.map((requirement) => (
+ <label key={requirement.name} className="block space-y-1.5 text-sm">
+ <span>{requirement.name}</span>
+ {requirement.description ? (
+ <span className="text-muted-foreground block text-xs">
+ {requirement.description} Visible to the agent runtime.
+ </span>
+ ) : null}
+ <Input
+ value={variables[requirement.name] ?? ''}
+ placeholder={requirement.example}
+ required={requirement.required}
+ onChange={(event) =>
+ setVariables((current) => ({
+ ...current,
+ [requirement.name]: event.target.value,
+ }))
+ }
+ />
+ </label>
+ ))}
+ </PanelContent>
+ </Panel>
+ <div className="flex justify-end">
+ <Button
+ type="submit"
+ disabled={
+ !projectName.trim() ||
+ missingSecret ||
+ missingRequiredVariable ||
+ install.isPending
+ }
+ >
+ {install.isPending ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <Rocket />
+ )}
+ {install.isPending
+ ? quickStart
+ ? 'Creating…'
+ : 'Deploying…'
+ : quickStart
+ ? 'Create agent'
+ : 'Deploy to Development'}
+ </Button>
+ </div>
+ </form>
+ )
+}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index c286b64a..c8385ad5 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -87,6 +87,79 @@ const projectSchema = z.object({
const projectsResponseSchema = z.object({ projects: z.array(projectSchema) })
+const templateInspectionSchema = z.object({
+ id: z.string(),
+ repository: z.object({
+ url: z.string().url(),
+ fullName: z.string(),
+ defaultBranch: z.literal('main'),
+ commitSha: z.string().regex(/^[0-9a-f]{40}$/),
+ }),
+ template: z.object({
+ name: z.string(),
+ description: z.string(),
+ documentation: z.string().url().optional(),
+ defaultProjectName: z.string().optional(),
+ firstRun: z.object({ agent: z.string(), prompt: z.string() }).optional(),
+ }),
+ agents: z.array(z.object({ id: z.string(), name: z.string() })),
+ requirements: z.object({
+ secrets: z.array(
+ z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ documentation: z.string().url().optional(),
+ required: z.boolean().default(true),
+ agentId: z.string().optional(),
+ allowedOrigins: z.array(z.string().url()),
+ }),
+ ),
+ runtimeVariables: z.array(
+ z.object({
+ name: z.string(),
+ description: z.string().optional(),
+ documentation: z.string().url().optional(),
+ required: z.boolean(),
+ example: z.string().optional(),
+ agentId: z.string().optional(),
+ }),
+ ),
+ connections: z.array(
+ z.object({
+ id: z.string(),
+ description: z.string().optional(),
+ provider: z.string(),
+ permissions: z.array(z.string()),
+ }),
+ ),
+ }),
+ expiresAt: z.string(),
+})
+
+const templateInspectionPreparingSchema = z.object({
+ id: z.string(),
+ status: z.literal('preparing'),
+ repositoryUrl: z.string().url(),
+ retryAfterMs: z.number().positive(),
+})
+
+const templateInstallationSchema = z.object({
+ id: z.string(),
+ inspectionId: z.string(),
+ projectId: z.string(),
+ projectAgentId: z.string(),
+ projectUrl: z.string(),
+ state: z.enum([
+ 'awaiting_configuration',
+ 'creating_project',
+ 'building',
+ 'deploying',
+ 'ready',
+ 'failed',
+ ]),
+ error: z.object({ stage: z.string(), message: z.string() }).optional(),
+})
+
const secretSchema = z.object({
name: z.string(),
projectId: z.string(),
@@ -417,6 +490,13 @@ const sessionsResponseSchema = z.object({ sessions: z.array(sessionSchema) })
const projectOverviewSchema = z.object({
project: projectSchema,
+ templateSource: z
+ .object({
+ repositoryUrl: z.string().url(),
+ commitSha: z.string().regex(/^[0-9a-f]{40}$/),
+ cloneReady: z.boolean().optional().default(false),
+ })
+ .optional(),
sessions: z.array(sessionSchema),
deployments: z.array(deploymentSchema),
connections: z.array(connectionSchema),
@@ -447,6 +527,8 @@ export type ManagedModelAccessConnection = z.infer<
typeof modelAccessConnectionSchema
>
export type ManagedModelAccessBinding = z.infer<typeof modelAccessBindingSchema>
+export type TemplateInspection = z.infer<typeof templateInspectionSchema>
+export type TemplateInstallation = z.infer<typeof templateInstallationSchema>
const UUID_NAME =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
@@ -482,6 +564,61 @@ export async function createManagedProject(name: string) {
)
}
+export async function inspectManagedTemplate(
+ repositoryUrl: string,
+): Promise<z.infer<typeof templateInspectionSchema>> {
+ const deadline = Date.now() + 10 * 60_000
+ for (;;) {
+ const result = await apiFetch(
+ '/managed-agents/template-inspections',
+ { method: 'POST', body: JSON.stringify({ repositoryUrl }) },
+ z.union([templateInspectionSchema, templateInspectionPreparingSchema]),
+ )
+ if ((result as { status?: string }).status !== 'preparing') {
+ return result as z.infer<typeof templateInspectionSchema>
+ }
+ const preparing = result as z.infer<
+ typeof templateInspectionPreparingSchema
+ >
+ if (Date.now() >= deadline) {
+ throw new Error(
+ 'Template preparation is still running; try again shortly',
+ )
+ }
+ await new Promise((resolve) =>
+ setTimeout(resolve, Math.max(500, preparing.retryAfterMs)),
+ )
+ }
+}
+
+export async function createManagedTemplateInstallation(input: {
+ inspectionId: string
+ projectName: string
+ idempotencyKey: string
+}) {
+ return apiFetch(
+ '/managed-agents/template-installations',
+ { method: 'POST', body: JSON.stringify(input) },
+ templateInstallationSchema,
+ )
+}
+
+export async function finalizeManagedTemplateInstallation(id: string) {
+ return apiFetch(
+ `/managed-agents/template-installations/${encodeURIComponent(id)}/finalize`,
+ { method: 'POST' },
+ templateInstallationSchema,
+ )
+}
+
+export async function getManagedTemplateInstallation(id: string) {
+ return apiFetch(
+ `/managed-agents/template-installations/${encodeURIComponent(id)}`,
+ undefined,
+ templateInstallationSchema,
+ )
+}
+
export async function getManagedProject(projectId: string) {
return apiFetch(
`/managed-agents/projects/${encodeURIComponent(projectId)}`,
diff --git a/web/src/managed-agents/template-continuation.test.ts b/web/src/managed-agents/template-continuation.test.ts
new file mode 100644
index 00000000..f2ac519a
--- /dev/null
+++ b/web/src/managed-agents/template-continuation.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest'
+import {
+ projectCloneCommand,
+ installedTemplateAgentId,
+ templateFirstRunPrompt,
+ templatePlaygroundPath,
+} from './template-continuation'
+
+describe('template local continuation', () => {
+ it('clones the existing OpenComputer project', () => {
+ expect(projectCloneCommand('prj_example')).toBe(
+ "npx --package @opencomputer/cli opencomputer project clone 'prj_example'",
+ )
+ })
+
+ it('opens the installed agent in its project Debug playground', () => {
+ expect(
+ templatePlaygroundPath({
+ projectId: 'prj/example',
+ projectAgentId: 'review agent',
+ }),
+ ).toBe('/projects/prj%2Fexample/playground/review%20agent')
+ })
+
+ it('maps the template first-run agent to its installed project agent', () => {
+ expect(
+ installedTemplateAgentId({
+ projectAgentId: 'cloud-primary',
+ localAgentId: 'reviewer',
+ primaryLocalAgentId: 'triage',
+ }),
+ ).toBe('cloud-primary--reviewer')
+ expect(
+ installedTemplateAgentId({
+ projectAgentId: 'cloud-primary',
+ localAgentId: 'triage',
+ primaryLocalAgentId: 'triage',
+ }),
+ ).toBe('cloud-primary')
+ })
+
+ it('only consumes a non-empty first-run prompt from navigation state', () => {
+ expect(
+ templateFirstRunPrompt({ templateFirstRunPrompt: 'Review this PR' }),
+ ).toBe('Review this PR')
+ expect(
+ templateFirstRunPrompt({ templateFirstRunPrompt: '' }),
+ ).toBeUndefined()
+ expect(templateFirstRunPrompt(null)).toBeUndefined()
+ })
+})
diff --git a/web/src/managed-agents/template-continuation.ts b/web/src/managed-agents/template-continuation.ts
new file mode 100644
index 00000000..66e8e3a0
--- /dev/null
+++ b/web/src/managed-agents/template-continuation.ts
@@ -0,0 +1,33 @@
+function shellQuote(value: string): string {
+ return `'${value.split("'").join(`'"'"'`)}'`
+}
+
+export function projectCloneCommand(projectId: string): string {
+ return [
+ 'npx --package @opencomputer/cli opencomputer project clone',
+ shellQuote(projectId),
+ ].join(' ')
+}
+
+export function templatePlaygroundPath(input: {
+ projectId: string
+ projectAgentId: string
+}): string {
+ return `/projects/${encodeURIComponent(input.projectId)}/playground/${encodeURIComponent(input.projectAgentId)}`
+}
+
+export function installedTemplateAgentId(input: {
+ projectAgentId: string
+ localAgentId?: string
+ primaryLocalAgentId?: string
+}): string {
+ return !input.localAgentId || input.localAgentId === input.primaryLocalAgentId
+ ? input.projectAgentId
+ : `${input.projectAgentId}--${input.localAgentId}`
+}
+
+export function templateFirstRunPrompt(state: unknown): string | undefined {
+ if (!state || typeof state !== 'object') return undefined
+ const prompt = (state as Record<string, unknown>).templateFirstRunPrompt
+ return typeof prompt === 'string' && prompt.trim() ? prompt : undefined
+}
diff --git a/web/src/managed-agents/template-inspection-error.ts b/web/src/managed-agents/template-inspection-error.ts
new file mode 100644
index 00000000..d3838fe0
--- /dev/null
+++ b/web/src/managed-agents/template-inspection-error.ts
@@ -0,0 +1,18 @@
+import { ApiError } from '@/api/client'
+
+export function templateInspectionError(error: unknown) {
+ if (error instanceof ApiError && error.type === 'template_manifest_missing') {
+ return {
+ title: 'Not a valid template',
+ description:
+ 'This repository does not contain oc-template.toml at its root.',
+ }
+ }
+ return {
+ title: 'This template could not be inspected',
+ description:
+ error instanceof Error
+ ? error.message
+ : 'Check the repository and try again.',
+ }
+}
diff --git a/web/src/managed-agents/templates.test.ts b/web/src/managed-agents/templates.test.ts
new file mode 100644
index 00000000..c0775b4e
--- /dev/null
+++ b/web/src/managed-agents/templates.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import {
+ CURATED_TEMPLATES,
+ HELLO_WORLD_TEMPLATE_REPOSITORY,
+ templateDeployPath,
+} from './templates'
+
+describe('project creation templates', () => {
+ it('keeps Hello World on the ordinary main-branch template path', () => {
+ expect(templateDeployPath(HELLO_WORLD_TEMPLATE_REPOSITORY, true)).toBe(
+ '/new?repository-url=https%3A%2F%2Fgithub.com%2Fdiggerhq%2Fopencomputer-example-hello-world&quick-start=1',
+ )
+ })
+
+ it('includes each documented example once', () => {
+ expect(CURATED_TEMPLATES.map((template) => template.name)).toEqual([
+ 'Pull Request Reviewer',
+ 'Test Coverage',
+ 'GitHub Actions Triage',
+ 'Feature Flag Hygiene',
+ 'GTM Engineer',
+ ])
+ expect(
+ new Set(CURATED_TEMPLATES.map((template) => template.repositoryUrl)).size,
+ ).toBe(CURATED_TEMPLATES.length)
+ })
+})
diff --git a/web/src/managed-agents/templates.ts b/web/src/managed-agents/templates.ts
new file mode 100644
index 00000000..e76bad98
--- /dev/null
+++ b/web/src/managed-agents/templates.ts
@@ -0,0 +1,39 @@
+export const HELLO_WORLD_TEMPLATE_REPOSITORY =
+ 'https://github.com/diggerhq/opencomputer-example-hello-world'
+
+export const CURATED_TEMPLATES = [
+ {
+ name: 'Pull Request Reviewer',
+ description:
+ 'Review a pull request and return focused, actionable feedback.',
+ repositoryUrl: 'https://github.com/diggerhq/opencomputer-example-pr-review',
+ },
+ {
+ name: 'Test Coverage',
+ description: 'Find meaningful gaps in a repository’s automated tests.',
+ repositoryUrl:
+ 'https://github.com/diggerhq/opencomputer-example-test-coverage',
+ },
+ {
+ name: 'GitHub Actions Triage',
+ description: 'Investigate failed CI runs and explain the likely fix.',
+ repositoryUrl:
+ 'https://github.com/diggerhq/opencomputer-example-actions-triage',
+ },
+ {
+ name: 'Feature Flag Hygiene',
+ description: 'Audit stale feature flags across GitHub and Unleash.',
+ repositoryUrl: 'https://github.com/diggerhq/opencomputer-example-unleash',
+ },
+ {
+ name: 'GTM Engineer',
+ description: 'Turn product context into practical go-to-market work.',
+ repositoryUrl: 'https://github.com/diggerhq/opencomputer-example-gtm',
+ },
+] as const
+
+export function templateDeployPath(repositoryUrl: string, quickStart = false) {
+ const query = new URLSearchParams({ 'repository-url': repositoryUrl })
+ if (quickStart) query.set('quick-start', '1')
+ return `/new?${query.toString()}`
+}