An open-source, faster Devin alternative
TypeScript
feat: simplify agent starter development flow (#622)
Mohamed Habib3f64bfce7e41
diff --git a/.github/workflows/publish-opencomputer-packages.yml b/.github/workflows/publish-opencomputer-packages.ymlindex b4704966..13116798 100644--- a/.github/workflows/publish-opencomputer-packages.yml+++ b/.github/workflows/publish-opencomputer-packages.yml@@ -3,17 +3,19 @@ name: Publish OpenComputer packageson:pull_request:paths:- - 'agent/**'- - 'cli/**'- - 'create-start/**'- - '.github/workflows/publish-opencomputer-packages.yml'+ - "agent/**"+ - "react/**"+ - "cli/**"+ - "create-start/**"+ - ".github/workflows/publish-opencomputer-packages.yml"push:branches: [main]paths:- - 'agent/**'- - 'cli/**'- - 'create-start/**'- - '.github/workflows/publish-opencomputer-packages.yml'+ - "agent/**"+ - "react/**"+ - "cli/**"+ - "create-start/**"+ - ".github/workflows/publish-opencomputer-packages.yml"workflow_dispatch:concurrency:@@ -32,11 +34,12 @@ jobs:- uses: actions/setup-node@v4with:- node-version: '22'- registry-url: 'https://registry.npmjs.org'+ node-version: "22"+ registry-url: "https://registry.npmjs.org"cache: npmcache-dependency-path: |agent/package-lock.json+ react/package-lock.jsoncli/package-lock.jsoncreate-start/package-lock.json@@ -52,6 +55,12 @@ jobs:npm cinpm test+ - name: Install and build React package+ working-directory: react+ run: |+ npm ci+ npm run build+- name: Install and test starter packageworking-directory: create-startrun: |@@ -86,5 +95,6 @@ jobs:}publish_if_needed agent @opencomputer/agent+ publish_if_needed react @opencomputer/reactpublish_if_needed cli @opencomputer/clipublish_if_needed create-start @opencomputer/create-startdiff --git a/cli/README.md b/cli/README.mdindex d402201b..6c259e9a 100644--- a/cli/README.md+++ b/cli/README.md@@ -1,7 +1,7 @@# @opencomputer/cli-The agent-focused OpenComputer CLI creates, develops, and deploys projects that-contain agent code and a React application.+The agent-focused OpenComputer CLI creates, develops, and deploys agent+projects with an optional React application.```bashnpm create @opencomputer/start@latest my-agent@@ -11,18 +11,14 @@ npx opencomputer loginnpx opencomputer link```-The npm initializer delegates to `opencomputer init` and creates the same-hello-world app. Agent definitions live-under `opencomputer/agents/`; the generated React app lives under `src/`.+The npm initializer asks whether to include a React SPA, then delegates to+`opencomputer init`. Agent definitions live under `opencomputer/agents/`; the+optional React app lives under `src/`.-Use two terminals during development:+Start cloud sync and the optional React app together:```bash-# terminal 1 — sync agents to Development (Cloud)npm run dev--# terminal 2 — Vite React app-npm run dev:web````opencomputer link` asks whether to create a project or select an existing@@ -34,8 +30,9 @@ Use `opencomputer dev --project <id|slug>` for non-interactive selection orThe production cloud API (`https://app.opencomputer.dev`) is the default.Override it only with `--api-url` or `OPENCOMPUTER_API_URL`.-The React app uses the generated `useAgent` hook. Vite proxies agent requests-through the CLI's authenticated bridge; agent execution remains in the cloud.+The command prints the cloud dashboard URL. A React app imports `useAgent`+from `@opencomputer/react`; Vite proxies requests through the CLI's+authenticated bridge, while agent execution remains in the cloud.Deploy the same agent source when it is ready:diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 4fdf65a5..1cddef1c 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.4.9",+ "version": "0.4.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.4.9",+ "version": "0.4.10","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex 38d263d4..774bb47c 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.4.9",+ "version": "0.4.10","description": "Build, test, connect, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 13bd284d..388ffae0 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -511,13 +511,20 @@ export async function runCommand(}if (command === "init") {+ const spa = flag(args, "--spa");+ const agentOnly = flag(args, "--agent-only");+ if (spa && agentOnly) {+ throw new Error("Choose either --spa or --agent-only");+ }const directory = args.shift();if (!directory) {throw new Error("Usage: opencomputer init <directory|.>");}if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);await assertStarterTarget(directory);- const initialized = await initializeAgentProject(directory);+ const initialized = await initializeAgentProject(directory, undefined, {+ spa: !agentOnly,+ });if (globals.json) printJSON(initialized);else {const enterDirectory = directory === "." ? "" : ` cd ${directory}\n`;@@ -526,12 +533,11 @@ export async function runCommand(`Directory: ${initialized.root}\n` +`Project: choose or create one on the first npm run dev\n` +`Agents: opencomputer/\n` +- `React: src/\n\n` ++ (agentOnly ? `App: agent only\n\n` : `React: src/\n\n`) +`Next:\n` +enterDirectory +` npm install\n` +- ` npm run dev # terminal 1: cloud agent sync\n` +- ` npm run dev:web # terminal 2: React app\n`,+ ` npm run dev # cloud sync${agentOnly ? "" : " + React app"}\n`,);}return;diff --git a/cli/src/dev.test.ts b/cli/src/dev.test.tsindex fdb0dde6..305f3696 100644--- a/cli/src/dev.test.ts+++ b/cli/src/dev.test.ts@@ -4,9 +4,37 @@ import { tmpdir } from "node:os";import { resolve } from "node:path";import test from "node:test";-import { publishDevelopment, publishProjectDevelopment } from "./dev.js";+import {+ hasReactSpa,+ projectDashboardURL,+ publishDevelopment,+ publishProjectDevelopment,+} from "./dev.js";import { initializeAgentProject } from "./project.js";+test("development derives the cloud dashboard project URL", () => {+ assert.equal(+ projectDashboardURL("https://mo-oc-dev.com/", "prj_hello/world"),+ "https://mo-oc-dev.com/projects/prj_hello%2Fworld",+ );+});++test("development detects whether the starter includes a React SPA", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-shape-"));+ try {+ const withSpa = await initializeAgentProject(resolve(parent, "with-spa"));+ const agentOnly = await initializeAgentProject(+ resolve(parent, "agent-only"),+ undefined,+ { spa: false },+ );+ assert.equal(await hasReactSpa(withSpa.root), true);+ assert.equal(await hasReactSpa(agentOnly.root), false);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("development publish builds an immutable artifact under the development alias", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-"));try {diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex 472c6c56..92d93eb9 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -1,5 +1,6 @@+import { spawn, type ChildProcess } from "node:child_process";import { watch, type FSWatcher } from "node:fs";-import { mkdir, rm, writeFile } from "node:fs/promises";+import { access, mkdir, rm, writeFile } from "node:fs/promises";import { resolve } from "node:path";import type { OpenComputerClient } from "./api.js";@@ -72,15 +73,58 @@ function sourceChange(filename: string | Buffer | null): boolean {return !normalized.split("/").includes(".opencomputer");}-function waitForShutdown(): Promise<void> {+function waitForShutdown(web?: ChildProcess): Promise<void> {return new Promise((done) => {- const stop = () => {+ const cleanup = () => {process.off("SIGINT", stop);process.off("SIGTERM", stop);+ web?.off("exit", webStopped);+ };+ const stop = () => {+ cleanup();+ done();+ };+ const webStopped = (code: number | null, signal: NodeJS.Signals | null) => {+ cleanup();+ process.stderr.write(+ `React dev server stopped${signal ? ` (${signal})` : ` (${String(code)})`}.\n`,+ );done();};process.on("SIGINT", stop);process.on("SIGTERM", stop);+ web?.once("exit", webStopped);+ });+}++export function projectDashboardURL(apiUrl: string, projectId: string): string {+ return `${apiUrl.replace(/\/+$/, "")}/projects/${encodeURIComponent(projectId)}`;+}++export async function hasReactSpa(projectRoot: string): Promise<boolean> {+ try {+ await Promise.all([+ access(resolve(projectRoot, "vite.config.ts")),+ access(resolve(projectRoot, "src", "main.tsx")),+ ]);+ return true;+ } catch {+ return false;+ }+}++async function startReactDevServer(projectRoot: string): Promise<ChildProcess> {+ const vite = resolve(projectRoot, "node_modules", "vite", "bin", "vite.js");+ try {+ await access(vite);+ } catch {+ throw new Error(+ "This project includes a React SPA, but Vite is not installed. Run npm install first.",+ );+ }+ return spawn(process.execPath, [vite], {+ cwd: projectRoot,+ stdio: "inherit",});}@@ -98,7 +142,7 @@ export async function runCloudDevelopment(options,);const gateway = await startGateway(config);- const stateDirectory = resolve(root, ".opencomputer");+ const stateDirectory = resolve(projectRoot, ".opencomputer");const stateFile = resolve(stateDirectory, "dev.json");await mkdir(stateDirectory, { recursive: true });await writeFile(@@ -114,6 +158,7 @@ export async function runCloudDevelopment();let watcher: FSWatcher | undefined;+ let web: ChildProcess | undefined;let timer: NodeJS.Timeout | undefined;let publishing = false;let pending = false;@@ -164,23 +209,33 @@ export async function runCloudDevelopment(for (const result of initial) {lastDigests.set(result.deployment.agentId, result.built.digest);}+ const spa = await hasReactSpa(projectRoot);process.stdout.write(`Development (Cloud)\n` +`Project: ${binding.projectName} (${binding.projectId})\n` ++ `Dashboard: ${projectDashboardURL(config.apiUrl, binding.projectId)}\n` +`Agents: ${initial.map((result) => `${result.deployment.agentId}@development`).join(", ")}\n` +`Deployments:${initial.map((result) => ` ${result.deployment.id}`).join("\n ")}\n` +`Watching: ${projectRoot}\n` +- `React: run npm run dev:web in another terminal\n`,+ (spa+ ? `React: starting local Vite app\n`+ : `React: not included\n`),+ );+ if (spa) web = await startReactDevServer(projectRoot);+ watcher = watch(+ resolve(projectRoot, "opencomputer"),+ { recursive: true },+ (_event, filename) => {+ if (!sourceChange(filename)) return;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => void publish(), DEBOUNCE_MS);+ },);- watcher = watch(projectRoot, { recursive: true }, (_event, filename) => {- if (!sourceChange(filename)) return;- if (timer) clearTimeout(timer);- timer = setTimeout(() => void publish(), DEBOUNCE_MS);- });- await waitForShutdown();+ await waitForShutdown(web);} finally {if (timer) clearTimeout(timer);watcher?.close();+ if (web?.exitCode === null && web.signalCode === null) web.kill("SIGTERM");await rm(stateFile, { force: true });await gateway.close();}diff --git a/cli/src/index.ts b/cli/src/index.tsindex 65be5286..b2460ce5 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -47,7 +47,7 @@ Usage:opencomputer logout [--local]opencomputer whoamiopencomputer agents- opencomputer init <directory|.>+ opencomputer init <directory|.> [--spa|--agent-only]opencomputer linkopencomputer dev [--project <id|slug> | --create-project <name>]opencomputer session [prompt]diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex 30dde48d..849a6fb3 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -41,9 +41,10 @@ test("init creates a multi-agent-ready project and React hello world app", asyncawait readFile(resolve(root, "opencomputer", "project.ts"), "utf8"),/id:/,);+ await assert.rejects(stat(resolve(root, "src", "use-agent.ts")));assert.match(- await readFile(resolve(root, "src", "use-agent.ts"), "utf8"),- /const AGENT = __OPENCOMPUTER_AGENT__[\s\S]*export function useAgent/,+ await readFile(resolve(root, "src", "App.tsx"), "utf8"),+ /import \{ useAgent \} from "@opencomputer\/react"[\s\S]*useAgent\(__OPENCOMPUTER_AGENT__\)/,);const packageJSON = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"),@@ -53,9 +54,10 @@ test("init creates a multi-agent-ready project and React hello world app", asyncdevDependencies: Record<string, string>;};assert.equal(packageJSON.scripts.dev, "opencomputer dev");- assert.equal(packageJSON.scripts["dev:web"], "vite");+ assert.equal(packageJSON.scripts["dev:web"], undefined);assert.equal(packageJSON.dependencies["@opencomputer/agent"], "^0.3.1");- assert.equal(packageJSON.devDependencies["@opencomputer/cli"], "^0.4.8");+ assert.equal(packageJSON.dependencies["@opencomputer/react"], "^0.1.0");+ assert.equal(packageJSON.devDependencies["@opencomputer/cli"], "^0.4.10");assert.ok(packageJSON.devDependencies["@types/node"]);const viteConfig = await readFile(resolve(root, "vite.config.ts"), "utf8");assert.match(viteConfig, /command === "serve"/);@@ -105,7 +107,45 @@ test("init creates a multi-agent-ready project and React hello world app", async"src/App.tsx","src/main.tsx","src/styles.css",- "src/use-agent.ts",+ ]);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("init can create an agent-only project", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-agent-only-"));+ const root = resolve(parent, "hello-agent");+ try {+ const initialized = await initializeAgentProject(root, undefined, {+ spa: false,+ });+ await stat(+ resolve(root, "opencomputer", "agents", "hello-world", "agent.ts"),+ );+ await assert.rejects(stat(resolve(root, "src")));+ await assert.rejects(stat(resolve(root, "vite.config.ts")));+ const packageJSON = JSON.parse(+ await readFile(resolve(root, "package.json"), "utf8"),+ ) as {+ scripts: Record<string, string>;+ dependencies: Record<string, string>;+ devDependencies: Record<string, string>;+ };+ assert.deepEqual(packageJSON.scripts, {+ dev: "opencomputer dev",+ session: "opencomputer session",+ deploy: "opencomputer deploy",+ });+ assert.equal(packageJSON.dependencies["@opencomputer/react"], undefined);+ assert.equal(packageJSON.dependencies.react, undefined);+ assert.equal(packageJSON.devDependencies.vite, undefined);+ assert.deepEqual(initialized.files, [+ "opencomputer/project.ts",+ "opencomputer/agents/hello-world/agent.ts",+ "package.json",+ "README.md",+ ".gitignore",]);} finally {await rm(parent, { recursive: true, force: true });@@ -256,7 +296,9 @@ export default function Agent() {});test("the compiler rejects hard-coded sensitive connection headers", async () => {- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-secret-"));+ const parent = await mkdtemp(+ resolve(tmpdir(), "opencomputer-egress-secret-"),+ );const root = resolve(parent, "app");try {const initialized = await initializeAgentProject(root);@@ -323,7 +365,10 @@ export default function Agent() {const runtime = await prepareAgent(initialized.agentRoot);const manifest = JSON.parse(- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),+ await readFile(+ resolve(runtime, ".opencomputer", "reactive.json"),+ "utf8",+ ),) as { tools: string[]; toolModules: string[] };assert.ok(manifest.tools.includes("hacker_news"));assert.ok(manifest.toolModules.includes("../tools/hacker-news.js"));diff --git a/cli/src/project.ts b/cli/src/project.tsindex 22617076..15d579d9 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -428,6 +428,7 @@ export async function assertStarterTarget(directory: string): Promise<void> {export async function initializeAgentProject(directory: string,project?: { id: string; name: string; agentId: string },+ options: { spa?: boolean } = {},): Promise<{root: string;agentRoot: string;@@ -435,6 +436,7 @@ export async function initializeAgentProject(files: string[];}> {const root = resolve(directory);+ const spa = options.spa ?? true;const agentRoot = resolve(root, "opencomputer", "agents", "hello-world");await assertStarterTarget(root);await mkdir(agentRoot, { recursive: true });@@ -475,7 +477,7 @@ export default function Agent() {`,);await updateGitignore(root);- await mkdir(resolve(root, "src"), { recursive: true });+ if (spa) await mkdir(resolve(root, "src"), { recursive: true });await writeFile(resolve(root, "opencomputer", "project.ts"),`export default {@@ -495,33 +497,42 @@ export default function Agent() {type: "module",scripts: {dev: "opencomputer dev",- "dev:web": "vite",- build: "tsc -b && vite build",+ ...(spa ? { build: "tsc -b && vite build" } : {}),session: "opencomputer session",deploy: "opencomputer deploy",},dependencies: {"@opencomputer/agent": "^0.3.1",- react: "^19.2.0",- "react-dom": "^19.2.0",+ ...(spa+ ? {+ "@opencomputer/react": "^0.1.0",+ react: "^19.2.0",+ "react-dom": "^19.2.0",+ }+ : {}),},devDependencies: {- "@opencomputer/cli": "^0.4.8",- "@types/node": "^24.0.0",- "@types/react": "^19.2.0",- "@types/react-dom": "^19.2.0",- "@vitejs/plugin-react": "^6.0.0",- typescript: "^5.9.0",- vite: "^8.0.0",+ "@opencomputer/cli": "^0.4.10",+ ...(spa+ ? {+ "@types/node": "^24.0.0",+ "@types/react": "^19.2.0",+ "@types/react-dom": "^19.2.0",+ "@vitejs/plugin-react": "^6.0.0",+ typescript: "^5.9.0",+ vite: "^8.0.0",+ }+ : {}),},},null,2,)}\n`,);- await writeFile(- resolve(root, "vite.config.ts"),- `import { readFileSync } from "node:fs";+ if (spa)+ await writeFile(+ resolve(root, "vite.config.ts"),+ `import { readFileSync } from "node:fs";import { resolve } from "node:path";import react from "@vitejs/plugin-react";import { defineConfig } from "vite";@@ -533,7 +544,7 @@ function openComputerDev() {) as { url: string; token: string; agent: string };} catch {throw new Error(- "OpenComputer is not running. Start npm run dev in another terminal first.",+ "OpenComputer is not running. Start npm run dev first.",);}}@@ -573,38 +584,40 @@ export default defineConfig(({ command }) => {};});`,- );- await writeFile(- resolve(root, "tsconfig.json"),- `${JSON.stringify(- {- compilerOptions: {- target: "ES2022",- useDefineForClassFields: true,- lib: ["ES2022", "DOM", "DOM.Iterable"],- allowJs: false,- skipLibCheck: true,- esModuleInterop: true,- allowSyntheticDefaultImports: true,- strict: true,- forceConsistentCasingInFileNames: true,- module: "ESNext",- moduleResolution: "Bundler",- resolveJsonModule: true,- isolatedModules: true,- noEmit: true,- jsx: "react-jsx",- types: ["node", "vite/client"],+ );+ if (spa)+ await writeFile(+ resolve(root, "tsconfig.json"),+ `${JSON.stringify(+ {+ compilerOptions: {+ target: "ES2022",+ useDefineForClassFields: true,+ lib: ["ES2022", "DOM", "DOM.Iterable"],+ allowJs: false,+ skipLibCheck: true,+ esModuleInterop: true,+ allowSyntheticDefaultImports: true,+ strict: true,+ forceConsistentCasingInFileNames: true,+ module: "ESNext",+ moduleResolution: "Bundler",+ resolveJsonModule: true,+ isolatedModules: true,+ noEmit: true,+ jsx: "react-jsx",+ types: ["node", "vite/client"],+ },+ include: ["src", "vite.config.ts"],},- include: ["src", "vite.config.ts"],- },- null,- 2,- )}\n`,- );- await writeFile(- resolve(root, "index.html"),- `<!doctype html>+ null,+ 2,+ )}\n`,+ );+ if (spa)+ await writeFile(+ resolve(root, "index.html"),+ `<!doctype html><html lang="en"><head><meta charset="UTF-8" />@@ -618,148 +631,18 @@ export default defineConfig(({ command }) => {</body></html>`,- );- await writeFile(- resolve(root, "src", "use-agent.ts"),- `import { useCallback, useRef, useState } from "react";--export interface AgentMessage {- id: string;- role: "user" | "assistant";- text: string;-}--interface AgentEvent {- seq: number;- type: string;- data: Record<string, unknown>;-}+ );+ if (spa)+ await writeFile(+ resolve(root, "src", "App.tsx"),+ `import { useAgent } from "@opencomputer/react";+import { FormEvent, useState } from "react";declare const __OPENCOMPUTER_AGENT__: string;-const AGENT = __OPENCOMPUTER_AGENT__;--async function request<T>(path: string, init?: RequestInit): Promise<T> {- const response = await fetch(\`/api/opencomputer/managed-agents\${path}\`, {- ...init,- headers: { "content-type": "application/json", ...init?.headers },- });- const body = await response.json();- if (!response.ok) {- throw new Error(body?.error?.message ?? \`Agent request failed (\${response.status})\`);- }- return body as T;-}--export function useAgent() {- const [messages, setMessages] = useState<AgentMessage[]>([]);- const [sessionId, setSessionId] = useState<string>();- const sessionRef = useRef<string | undefined>(undefined);- const cursorRef = useRef(0);- const [isRunning, setIsRunning] = useState(false);- const [error, setError] = useState<string>();-- const send = useCallback(async (value: string) => {- const prompt = value.trim();- if (!prompt || isRunning) return;- const userMessage: AgentMessage = {- id: crypto.randomUUID(),- role: "user",- text: prompt,- };- const assistantId = crypto.randomUUID();- setMessages((current) => [- ...current,- userMessage,- { id: assistantId, role: "assistant", text: "" },- ]);- setIsRunning(true);- setError(undefined);- try {- let activeSession = sessionRef.current;- if (!activeSession) {- const created = await request<{ session: { id: string } }>("/sessions", {- method: "POST",- body: JSON.stringify({ agentId: AGENT, source: "local-react" }),- });- activeSession = created.session.id;- sessionRef.current = activeSession;- setSessionId(activeSession);- } else {- await request(\`/sessions/\${encodeURIComponent(activeSession)}/resume\`, {- method: "POST",- });- }- let streamed = "";- const waitFor = async (terminal: (event: AgentEvent) => boolean) => {- for (;;) {- const result = await request<{ events: AgentEvent[] }>(- \`/sessions/\${encodeURIComponent(activeSession!)}/events?after=\${cursorRef.current}\`,- );- for (const event of result.events) {- cursorRef.current = Math.max(cursorRef.current, event.seq);- if (event.type === "message.delta") {- streamed += String(event.data.text ?? "");- setMessages((current) =>- current.map((message) =>- message.id === assistantId- ? { ...message, text: streamed }- : message,- ),- );- } else if (event.type === "message.completed" && !streamed) {- const text = String(event.data.text ?? "");- setMessages((current) =>- current.map((message) =>- message.id === assistantId ? { ...message, text } : message,- ),- );- }- if (terminal(event)) return event;- }- await new Promise((done) => setTimeout(done, 500));- }- };- await waitFor((event) => event.type === "runtime.connected");- await request(\`/sessions/\${encodeURIComponent(activeSession)}/turns\`, {- method: "POST",- body: JSON.stringify({ input: prompt, idempotencyKey: crypto.randomUUID() }),- });- const completed = await waitFor((event) =>- event.type === "turn.completed" || event.type === "turn.failed",- );- if (completed.type === "turn.failed") {- throw new Error(String(completed.data.message ?? "Agent failed"));- }- await request(\`/sessions/\${encodeURIComponent(activeSession)}/suspend\`, {- method: "POST",- });- } catch (cause) {- const message = cause instanceof Error ? cause.message : String(cause);- setError(message);- setMessages((current) =>- current.map((item) =>- item.id === assistantId && !item.text- ? { ...item, text: "I couldn't complete that request." }- : item,- ),- );- } finally {- setIsRunning(false);- }- }, [isRunning]);-- return { messages, send, isRunning, error };-}-`,- );- await writeFile(- resolve(root, "src", "App.tsx"),- `import { FormEvent, useState } from "react";-import { useAgent } from "./use-agent";export default function App() {const [input, setInput] = useState("");- const { messages, send, isRunning, error } = useAgent();+ const { messages, send, isRunning, error } = useAgent(__OPENCOMPUTER_AGENT__);function submit(event: FormEvent) {event.preventDefault();@@ -808,10 +691,11 @@ export default function App() {);}`,- );- await writeFile(- resolve(root, "src", "main.tsx"),- `import { StrictMode } from "react";+ );+ if (spa)+ await writeFile(+ resolve(root, "src", "main.tsx"),+ `import { StrictMode } from "react";import { createRoot } from "react-dom/client";import App from "./App";import "./styles.css";@@ -822,10 +706,11 @@ createRoot(document.getElementById("root")!).render(</StrictMode>,);`,- );- await writeFile(- resolve(root, "src", "styles.css"),- `@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=DM+Serif+Display&display=swap");+ );+ if (spa)+ await writeFile(+ resolve(root, "src", "styles.css"),+ `@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=DM+Serif+Display&display=swap");:root { color: #1d1c19; background: #f4f1e9; font-family: "DM Sans", sans-serif; }* { box-sizing: border-box; }@@ -852,15 +737,16 @@ input { min-width: 0; flex: 1; border: 0; outline: 0; padding: 10px; background:form button { border: 0; border-radius: 10px; background: #d85b35; color: white; padding: 10px 18px; font-weight: 600; cursor: pointer; }form button:disabled { cursor: default; opacity: .45; }`,- );+ );await writeFile(resolve(root, "README.md"),- `# Hello World OpenComputer app+ spa+ ? `# Hello World OpenComputer appThis project keeps agent definitions in \`opencomputer/\` and the React app in\`src/\`.-Sync agent code to Development (Cloud) in one terminal:+Sync agent code to Development (Cloud) and start the React app:\`\`\`bashnpm run dev@@ -868,27 +754,35 @@ npm run devThe first run asks you to create a cloud project or select an existing one.That choice is saved for later development runs.+`+ : `# Hello World OpenComputer agent++This project keeps agent definitions in \`opencomputer/\`.-Then start the React app in another:+Sync agent code to Development (Cloud):\`\`\`bash-npm run dev:web+npm run dev\`\`\`++The first run asks you to create a cloud project or select an existing one.+That choice is saved for later development runs.`,);- const appFiles = [- "package.json",- "vite.config.ts",- "tsconfig.json",- "index.html",- "README.md",- ".gitignore",- "src/App.tsx",- "src/main.tsx",- "src/styles.css",- "src/use-agent.ts",- ];+ const appFiles = spa+ ? [+ "package.json",+ "vite.config.ts",+ "tsconfig.json",+ "index.html",+ "README.md",+ ".gitignore",+ "src/App.tsx",+ "src/main.tsx",+ "src/styles.css",+ ]+ : ["package.json", "README.md", ".gitignore"];return {root,agentRoot,@@ -954,7 +848,10 @@ function connectionHeaderValue(expression: ts.Expression,): HttpConnectionManifest["headers"][string] {if (ts.isStringLiteralLike(expression)) return expression.text;- if (!ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression)) {+ if (+ !ts.isCallExpression(expression) ||+ !ts.isIdentifier(expression.expression)+ ) {throw new Error("Connection headers must be string literals, bearer(useSecret()), or secretHeader(useSecret())",);@@ -985,8 +882,10 @@ function connectionHeaderValue(}const prefix = objectProperty(options, "prefix");const suffix = objectProperty(options, "suffix");- if (prefix) result.prefix = literalStringValue(prefix, "secretHeader prefix");- if (suffix) result.suffix = literalStringValue(suffix, "secretHeader suffix");+ if (prefix)+ result.prefix = literalStringValue(prefix, "secretHeader prefix");+ if (suffix)+ result.suffix = literalStringValue(suffix, "secretHeader suffix");}return result;}@@ -1009,14 +908,19 @@ function definedHttpConnections(if (!input || !ts.isObjectLiteralExpression(input)) {throw new Error("defineConnection() requires an object literal");}- const id = literalStringValue(objectProperty(input, "id"), "connection id");+ const id = literalStringValue(+ objectProperty(input, "id"),+ "connection id",+ );const originValue = literalStringValue(objectProperty(input, "origin"),`connection ${id} origin`,);const origin = new URL(originValue);if (origin.protocol !== "https:" || origin.pathname !== "/") {- throw new Error(`Connection ${id} must use an HTTPS origin without a path`);+ throw new Error(+ `Connection ${id} must use an HTTPS origin without a path`,+ );}const headers: HttpConnectionManifest["headers"] = {};const headerExpression = objectProperty(input, "headers");@@ -1028,18 +932,26 @@ function definedHttpConnections(if (!ts.isPropertyAssignment(property)) {throw new Error(`Connection ${id} headers cannot use spreads`);}- const name = ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)- ? property.name.text- : undefined;- if (!name) throw new Error(`Connection ${id} has an invalid header name`);+ const name =+ ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)+ ? property.name.text+ : undefined;+ if (!name)+ throw new Error(`Connection ${id} has an invalid header name`);const value = connectionHeaderValue(property.initializer);if (- ["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(- name.toLowerCase(),- ) &&+ [+ "api-key",+ "authorization",+ "cookie",+ "proxy-authorization",+ "x-api-key",+ ].includes(name.toLowerCase()) &&typeof value === "string") {- throw new Error(`Connection ${id} header ${name} must use useSecret()`);+ throw new Error(+ `Connection ${id} header ${name} must use useSecret()`,+ );}headers[name] = value;}@@ -1307,8 +1219,7 @@ the product or support surface presented to users.const ids = definedToolIds(candidate.source);const calls = [...candidate.source.matchAll(/\bdefineTool(?:<[^>]+>)?\s*\(/g),- ]- .length;+ ].length;if (ids.length !== calls) {throw new Error(`${candidate.filename} must give every defineTool() a literal string name`,@@ -1348,16 +1259,25 @@ the product or support surface presented to users.`Tool id ${JSON.stringify(duplicateTool)} is defined more than once`,);}- const httpConnections = [agentSource, ...toolSources.map((item) => item.source)]- .flatMap((source, index) =>- definedHttpConnections(source, index === 0 ? "agent.ts" : toolSources[index - 1]!.filename),- );+ const httpConnections = [+ agentSource,+ ...toolSources.map((item) => item.source),+ ].flatMap((source, index) =>+ definedHttpConnections(+ source,+ index === 0 ? "agent.ts" : toolSources[index - 1]!.filename,+ ),+ );const duplicateConnection = httpConnections.find((connection, index) =>- httpConnections.findIndex((candidate) => candidate.id === connection.id) !== index,+ httpConnections.findIndex(+ (candidate) => candidate.id === connection.id,+ ) !== index,);if (duplicateConnection) {- throw new Error(`Connection id ${JSON.stringify(duplicateConnection.id)} is defined more than once`);+ throw new Error(+ `Connection id ${JSON.stringify(duplicateConnection.id)} is defined more than once`,+ );}await mkdir(resolve(runtime, ".opencomputer"), { recursive: true });await writeFile(diff --git a/create-start/README.md b/create-start/README.mdindex 7fcdf365..d3e97bd4 100644--- a/create-start/README.md+++ b/create-start/README.md@@ -10,9 +10,11 @@ npx opencomputer loginnpm run dev```-The generated project contains reactive agent definitions under-`opencomputer/` and a React application under `src/`. The first development-run lets you select an existing cloud project or create a new one.+The initializer asks whether to create agent code only or include a React SPA.+The optional app imports its hooks from `@opencomputer/react`. A single+`npm run dev` syncs agents to Development (Cloud), prints the dashboard URL,+and starts Vite when the SPA is included. The first run lets you select an+existing cloud project or create a new one.Use `.` to initialize the current directory:diff --git a/create-start/index.js b/create-start/index.jsindex ed1c880b..782ff505 100644--- a/create-start/index.js+++ b/create-start/index.js@@ -1,13 +1,14 @@#!/usr/bin/env nodeimport { spawnSync } from "node:child_process";+import { createInterface } from "node:readline/promises";import { fileURLToPath } from "node:url";function usage() {process.stdout.write(`Create a hello-world OpenComputer application.Usage:- npm create @opencomputer/start@latest [directory|.]+ npm create @opencomputer/start@latest [directory|.] [--spa|--agent-only]`);}@@ -16,18 +17,54 @@ if (args.includes("--help") || args.includes("-h")) {usage();process.exit(0);}+const spaFlag = args.indexOf("--spa");+const agentOnlyFlag = args.indexOf("--agent-only");+if (spaFlag >= 0) args.splice(spaFlag, 1);+if (agentOnlyFlag >= 0) args.splice(agentOnlyFlag, 1);+if (spaFlag >= 0 && agentOnlyFlag >= 0) {+ process.stderr.write("create-start: choose either --spa or --agent-only\n");+ process.exit(1);+}if (args.length > 1 || args[0]?.startsWith("-")) {usage();process.exit(1);}const directory = args[0] ?? ".";+let includeSpa = spaFlag >= 0;+if (spaFlag < 0 && agentOnlyFlag < 0) {+ if (process.stdin.isTTY) {+ const prompt = createInterface({+ input: process.stdin,+ output: process.stdout,+ });+ try {+ process.stdout.write(+ "\nWhat would you like to create?\n\n" ++ " 1) Agent only\n" ++ " 2) Agent + React SPA\n\n",+ );+ const answer = await prompt.question("Select [1]: ");+ includeSpa = ["2", "y", "yes", "spa"].includes(+ answer.trim().toLowerCase(),+ );+ } finally {+ prompt.close();+ }+ } else {+ includeSpa = false;+ }+}const cliPath = process.env.OPENCOMPUTER_CREATE_START_CLI_PATH? process.env.OPENCOMPUTER_CREATE_START_CLI_PATH: fileURLToPath(import.meta.resolve("@opencomputer/cli/dist/index.js"));-const result = spawnSync(process.execPath, [cliPath, "init", directory], {- stdio: "inherit",-});+const result = spawnSync(+ process.execPath,+ [cliPath, "init", directory, includeSpa ? "--spa" : "--agent-only"],+ {+ stdio: "inherit",+ },+);if (result.error) {process.stderr.write(`create-start: ${result.error.message}\n`);diff --git a/create-start/package-lock.json b/create-start/package-lock.jsonindex 8b9351fc..57303c78 100644--- a/create-start/package-lock.json+++ b/create-start/package-lock.json@@ -1,14 +1,14 @@{"name": "@opencomputer/create-start",- "version": "0.1.3",+ "version": "0.1.4","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/create-start",- "version": "0.1.3",+ "version": "0.1.4","dependencies": {- "@opencomputer/cli": "^0.4.7"+ "@opencomputer/cli": "^0.4.9"},"bin": {"create-start": "index.js"@@ -75,9 +75,9 @@}},"node_modules/@opencomputer/cli": {- "version": "0.4.7",- "resolved": "https://registry.npmjs.org/@opencomputer/cli/-/cli-0.4.7.tgz",- "integrity": "sha512-Fp2iOo8QZmEq6np/18n70wyPoK1Kv5NAK2NHLXMMqFWgFARpDKCJqMmc3yzEVR13FBA6jhGauvDX7bxIA+qFDA==",+ "version": "0.4.9",+ "resolved": "https://registry.npmjs.org/@opencomputer/cli/-/cli-0.4.9.tgz",+ "integrity": "sha512-o0LPTKIgMPFq3ykG4pmfLmYzByWf8KTGGjO40XiR7AImZmIffhDHZh4d6LdehjiXWBgjrkcXNAaov3U1osh8zg==","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/create-start/package.json b/create-start/package.jsonindex c905b67b..07a916bd 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.1.3",+ "version": "0.1.4","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "^0.4.7"+ "@opencomputer/cli": "^0.4.9"},"publishConfig": {"access": "public"diff --git a/create-start/test/create-start.test.js b/create-start/test/create-start.test.jsindex 3d42d72c..0f57a0a0 100644--- a/create-start/test/create-start.test.js+++ b/create-start/test/create-start.test.js@@ -5,7 +5,7 @@ import { resolve } from "node:path";import { spawnSync } from "node:child_process";import test from "node:test";-test("delegates the requested directory to opencomputer init", async () => {+test("defaults to an agent-only project", async () => {const root = await mkdtemp(resolve(tmpdir(), "create-opencomputer-start-"));const capture = resolve(root, "args.json");const cli = resolve(root, "cli.mjs");@@ -16,18 +16,23 @@ test("delegates the requested directory to opencomputer init", async () => {writeFileSync(process.env.CAPTURE_PATH, JSON.stringify(process.argv.slice(2)));`,);- const result = spawnSync(process.execPath, [resolve("index.js"), "my-agent"], {- cwd: resolve(import.meta.dirname, ".."),- env: {- ...process.env,- CAPTURE_PATH: capture,- OPENCOMPUTER_CREATE_START_CLI_PATH: cli,+ const result = spawnSync(+ process.execPath,+ [resolve("index.js"), "my-agent"],+ {+ cwd: resolve(import.meta.dirname, ".."),+ env: {+ ...process.env,+ CAPTURE_PATH: capture,+ OPENCOMPUTER_CREATE_START_CLI_PATH: cli,+ },},- });+ );assert.equal(result.status, 0, result.stderr.toString());assert.deepEqual(JSON.parse(await readFile(capture, "utf8")), ["init","my-agent",+ "--agent-only",]);} finally {await rm(root, { recursive: true, force: true });@@ -54,7 +59,45 @@ writeFileSync(process.env.CAPTURE_PATH, JSON.stringify(process.argv.slice(2)));},});assert.equal(result.status, 0, result.stderr.toString());- assert.deepEqual(JSON.parse(await readFile(capture, "utf8")), ["init", "."]);+ assert.deepEqual(JSON.parse(await readFile(capture, "utf8")), [+ "init",+ ".",+ "--agent-only",+ ]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("passes the agent-only choice to the CLI", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "create-opencomputer-start-"));+ const capture = resolve(root, "args.json");+ const cli = resolve(root, "cli.mjs");+ try {+ await writeFile(+ cli,+ `import { writeFileSync } from "node:fs";+writeFileSync(process.env.CAPTURE_PATH, JSON.stringify(process.argv.slice(2)));+`,+ );+ const result = spawnSync(+ process.execPath,+ [resolve("index.js"), "my-agent", "--agent-only"],+ {+ cwd: resolve(import.meta.dirname, ".."),+ env: {+ ...process.env,+ CAPTURE_PATH: capture,+ OPENCOMPUTER_CREATE_START_CLI_PATH: cli,+ },+ },+ );+ assert.equal(result.status, 0, result.stderr.toString());+ assert.deepEqual(JSON.parse(await readFile(capture, "utf8")), [+ "init",+ "my-agent",+ "--agent-only",+ ]);} finally {await rm(root, { recursive: true, force: true });}@@ -63,10 +106,26 @@ writeFileSync(process.env.CAPTURE_PATH, JSON.stringify(process.argv.slice(2)));test("creates the published CLI hello-world application", async () => {const root = await mkdtemp(resolve(tmpdir(), "create-opencomputer-start-"));const app = resolve(root, "hello-agent");+ const localCli = resolve(+ import.meta.dirname,+ "..",+ "..",+ "cli",+ "dist",+ "index.js",+ );try {- const result = spawnSync(process.execPath, [resolve("index.js"), app], {- cwd: resolve(import.meta.dirname, ".."),- });+ const result = spawnSync(+ process.execPath,+ [resolve("index.js"), app, "--spa"],+ {+ cwd: resolve(import.meta.dirname, ".."),+ env: {+ ...process.env,+ OPENCOMPUTER_CREATE_START_CLI_PATH: localCli,+ },+ },+ );assert.equal(result.status, 0, result.stderr.toString());assert.equal((diff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdxindex b49dea57..4e15f19a 100644--- a/docs/agents/overview.mdx+++ b/docs/agents/overview.mdx@@ -4,7 +4,7 @@ description: "Define reactive agents in TypeScript and run them in the OpenCompu---OpenComputer is a managed runtime for agents defined as code. A project can-contain several agents and a React application that talks to them. You write+contain several agents and optionally a React application that talks to them. You writethe behavior; OpenComputer manages development deployments, model execution,tools, durable sessions, streaming, and production versions.@@ -57,13 +57,14 @@ npx opencomputer loginnpm run dev```-The first `npm run dev` lets you create a cloud project or select an existing-one. OpenComputer stores the local project binding under `.opencomputer/` and-syncs every configured agent to the project's `development` environment.+The initializer asks whether to include a React SPA. The first `npm run dev`+lets you create a cloud project or select an existing one, prints its dashboard+URL, and syncs every configured agent to `development`. When a SPA exists, the+same command also starts it locally.<Note>-There is no local agent server. The React app runs locally, while agent code-runs in OpenComputer's managed development cloud.+ There is no local agent server. An optional React app runs locally, while+ agent code runs in OpenComputer's managed development cloud.</Note>## What is available today@@ -72,7 +73,8 @@ runs in OpenComputer's managed development cloud.- reactive instructions, model selection, tools, subagents, connections, MCPservers, input metadata, and session data reads- cloud development with file watching and automatic synchronization-- a generated React client with streaming and multi-turn session reuse+- an optional React client using `@opencomputer/react` for streaming and+ multi-turn session reuse- dashboard and CLI playground sessions- immutable deployments promoted through aliases such as `production`- user-scoped Gmail, Calendar, and GitHub connectionsdiff --git a/docs/agents/quickstart.mdx b/docs/agents/quickstart.mdxindex 14a87c65..577dbed1 100644--- a/docs/agents/quickstart.mdx+++ b/docs/agents/quickstart.mdx@@ -17,6 +17,7 @@ npm install```Use `.` instead of `my-agent` to initialize an empty current directory.+The initializer asks whether to create agent code only or include a React SPA.## 2. Log in@@ -29,35 +30,22 @@ The production API at `https://app.opencomputer.dev` is used by default.## 3. Start cloud development-In the first terminal:-```bashnpm run dev```On the first run, choose an existing cloud project or create a new one. The-process then stays open, watches `opencomputer/`, and syncs changes to-`development`.--## 4. Start React--In a second terminal:--```bash-npm run dev:web-```--Open the Vite URL and send a message. The generated React hook creates a-durable session, streams response events, and reuses that session for follow-up-messages.+process prints the project dashboard URL, watches `opencomputer/`, and syncs+changes to `development`. If you included the SPA, the same command starts+Vite; open its URL and send a message.<Warning>-Keep `npm run dev` running while using `npm run dev:web`. Vite reads temporary-bridge details from `.opencomputer/dev.json`; those details are intentionally-not bundled into browser code.+ Keep `npm run dev` running while using the React app. Vite reads temporary+ bridge details from `.opencomputer/dev.json`; they are intentionally not+ bundled into browser code.</Warning>-## 5. Change the agent+## 4. Change the agentEdit `opencomputer/agents/hello-world/agent.ts`:@@ -75,7 +63,7 @@ export default function Agent() {Saving the file publishes a new development deployment. Refreshing orrestarting the React app is not required for agent-only changes.-## 6. Deploy to production+## 5. Deploy to production```bashnpm run deploy -- --alias productiondiff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex 36842c2a..0408d726 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -9,15 +9,16 @@ conversation without rebuilding its history locally.## React-The starter includes `src/use-agent.ts`. Its `useAgent()` hook exposes:+When you select the React SPA, the starter imports `useAgent()` from+`@opencomputer/react`. The hook exposes:- `messages` — accumulated user and assistant messages- `send(text)` — create a session if necessary and stream the next turn- `isRunning` — whether a turn is active- `error` — the latest request error-The generated hook is ordinary application code. Extend it, replace its UI, or-build additional hooks around the same session endpoints.+The hook accepts an agent selector such as `hello-world@development`. Build+additional UI and application hooks around its session state as needed.## Agent playgrounddiff --git a/react/README.md b/react/README.mdnew file mode 100644index 00000000..d08978d1--- /dev/null+++ b/react/README.md@@ -0,0 +1,12 @@+# @opencomputer/react++React hooks for applications that interact with OpenComputer agents.++```tsx+import { useAgent } from "@opencomputer/react";++const agent = useAgent("support@development");+```++The generated OpenComputer starter configures the local authenticated bridge+automatically during `npm run dev`.diff --git a/react/package-lock.json b/react/package-lock.jsonnew file mode 100644index 00000000..5769f116--- /dev/null+++ b/react/package-lock.json@@ -0,0 +1,64 @@+{+ "name": "@opencomputer/react",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@opencomputer/react",+ "version": "0.1.0",+ "devDependencies": {+ "@types/react": "^19.2.18",+ "react": "^19.2.8",+ "typescript": "^5.9.0"+ },+ "engines": {+ "node": ">=22.0.0"+ },+ "peerDependencies": {+ "react": ">=19.0.0"+ }+ },+ "node_modules/@types/react": {+ "version": "19.2.18",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",+ "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "csstype": "^3.2.2"+ }+ },+ "node_modules/csstype": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/react": {+ "version": "19.2.8",+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",+ "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ }+ }+}diff --git a/react/package.json b/react/package.jsonnew file mode 100644index 00000000..92269e86--- /dev/null+++ b/react/package.json@@ -0,0 +1,48 @@+{+ "name": "@opencomputer/react",+ "version": "0.1.0",+ "description": "React hooks for OpenComputer agents.",+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "build": "tsc -p tsconfig.json",+ "prepack": "npm run build"+ },+ "engines": {+ "node": ">=22.0.0"+ },+ "peerDependencies": {+ "react": ">=19.0.0"+ },+ "devDependencies": {+ "@types/react": "^19.2.18",+ "react": "^19.2.8",+ "typescript": "^5.9.0"+ },+ "publishConfig": {+ "access": "public"+ },+ "repository": {+ "type": "git",+ "url": "git+https://github.com/diggerhq/opencomputer.git",+ "directory": "react"+ },+ "keywords": [+ "agents",+ "ai",+ "opencomputer",+ "react",+ "hooks"+ ]+}diff --git a/react/src/index.ts b/react/src/index.tsnew file mode 100644index 00000000..d8eee42b--- /dev/null+++ b/react/src/index.ts@@ -0,0 +1,165 @@+import { useCallback, useRef, useState } from "react";++export interface AgentMessage {+ id: string;+ role: "user" | "assistant";+ text: string;+}++export interface UseAgentOptions {+ agent: string;+ source?: string;+ basePath?: string;+ fetch?: typeof globalThis.fetch;+}++interface AgentEvent {+ seq: number;+ type: string;+ data: Record<string, unknown>;+}++export function useAgent(agentOrOptions: string | UseAgentOptions) {+ const options =+ typeof agentOrOptions === "string"+ ? { agent: agentOrOptions }+ : agentOrOptions;+ const basePath = options.basePath ?? "/api/opencomputer/managed-agents";+ const requestFetch = options.fetch ?? globalThis.fetch;+ const [messages, setMessages] = useState<AgentMessage[]>([]);+ const [sessionId, setSessionId] = useState<string>();+ const sessionRef = useRef<string | undefined>(undefined);+ const cursorRef = useRef(0);+ const [isRunning, setIsRunning] = useState(false);+ const [error, setError] = useState<string>();++ const request = useCallback(+ async <T>(path: string, init?: RequestInit): Promise<T> => {+ const response = await requestFetch(`${basePath}${path}`, {+ ...init,+ headers: { "content-type": "application/json", ...init?.headers },+ });+ const body: unknown = await response.json();+ if (!response.ok) {+ const problem = body as { error?: { message?: string } };+ throw new Error(+ problem?.error?.message ??+ `Agent request failed (${String(response.status)})`,+ );+ }+ return body as T;+ },+ [basePath, requestFetch],+ );++ const send = useCallback(+ async (value: string) => {+ const prompt = value.trim();+ if (!prompt || isRunning) return;+ const userMessage: AgentMessage = {+ id: crypto.randomUUID(),+ role: "user",+ text: prompt,+ };+ const assistantId = crypto.randomUUID();+ setMessages((current) => [+ ...current,+ userMessage,+ { id: assistantId, role: "assistant", text: "" },+ ]);+ setIsRunning(true);+ setError(undefined);+ try {+ let activeSession = sessionRef.current;+ if (!activeSession) {+ const created = await request<{ session: { id: string } }>(+ "/sessions",+ {+ method: "POST",+ body: JSON.stringify({+ agentId: options.agent,+ source: options.source ?? "local-react",+ }),+ },+ );+ activeSession = created.session.id;+ sessionRef.current = activeSession;+ setSessionId(activeSession);+ } else {+ await request(+ `/sessions/${encodeURIComponent(activeSession)}/resume`,+ {+ method: "POST",+ },+ );+ }+ let streamed = "";+ const waitFor = async (terminal: (event: AgentEvent) => boolean) => {+ for (;;) {+ const result = await request<{ events: AgentEvent[] }>(+ `/sessions/${encodeURIComponent(activeSession!)}/events?after=${String(cursorRef.current)}`,+ );+ for (const event of result.events) {+ cursorRef.current = Math.max(cursorRef.current, event.seq);+ if (event.type === "message.delta") {+ streamed += String(event.data.text ?? "");+ setMessages((current) =>+ current.map((message) =>+ message.id === assistantId+ ? { ...message, text: streamed }+ : message,+ ),+ );+ } else if (event.type === "message.completed" && !streamed) {+ const text = String(event.data.text ?? "");+ setMessages((current) =>+ current.map((message) =>+ message.id === assistantId ? { ...message, text } : message,+ ),+ );+ }+ if (terminal(event)) return event;+ }+ await new Promise((done) => setTimeout(done, 500));+ }+ };+ await waitFor((event) => event.type === "runtime.connected");+ await request(`/sessions/${encodeURIComponent(activeSession)}/turns`, {+ method: "POST",+ body: JSON.stringify({+ input: prompt,+ idempotencyKey: crypto.randomUUID(),+ }),+ });+ const completed = await waitFor(+ (event) =>+ event.type === "turn.completed" || event.type === "turn.failed",+ );+ if (completed.type === "turn.failed") {+ throw new Error(String(completed.data.message ?? "Agent failed"));+ }+ await request(+ `/sessions/${encodeURIComponent(activeSession)}/suspend`,+ {+ method: "POST",+ },+ );+ } catch (cause) {+ const message = cause instanceof Error ? cause.message : String(cause);+ setError(message);+ setMessages((current) =>+ current.map((item) =>+ item.id === assistantId && !item.text+ ? { ...item, text: "I couldn't complete that request." }+ : item,+ ),+ );+ } finally {+ setIsRunning(false);+ }+ },+ [isRunning, options.agent, options.source, request],+ );++ return { messages, send, sessionId, isRunning, error };+}diff --git a/react/tsconfig.json b/react/tsconfig.jsonnew file mode 100644index 00000000..e694b1f6--- /dev/null+++ b/react/tsconfig.json@@ -0,0 +1,12 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "declaration": true,+ "outDir": "dist",+ "strict": true,+ "skipLibCheck": true+ },+ "include": ["src/**/*.ts"]+}diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsxindex 0ef7f4ae..baa124a2 100644--- a/web/src/managed-agents/Home.tsx+++ b/web/src/managed-agents/Home.tsx@@ -107,7 +107,7 @@ export default function ProjectsHome() {Create your first project</h2><p className="text-muted-foreground mt-3 max-w-xl text-sm leading-6">- Start with one hello-world agent and a React app. Your+ Start with one hello-world agent, with an optional React SPA. YourOpenComputer project is ready for more agents as it grows.</p><pre className="bg-foreground text-background mt-5 overflow-x-auto rounded-lg px-4 py-3 text-sm leading-7">@@ -172,8 +172,8 @@ export default function ProjectsHome() {<p className="text-muted-foreground mt-2 text-xs leading-5">Then run <code>cd my-agent</code>, <code>npm install</code>, and{' '}<code>npm run dev</code>. The project contains an{' '}- <code>opencomputer/</code> agent backend and a <code>src/</code>{' '}- React app.+ <code>opencomputer/</code> agent backend and can include a{' '}+ <code>src/</code> React app.</p></div></PanelContent>