An open-source, faster Devin alternative
TypeScript
feat(cli): make commands agent-first (#705)
Mohamed Habib59d8e55670de
diff --git a/cli/README.md b/cli/README.mdindex 5c61d943..4624b7c2 100644--- a/cli/README.md+++ b/cli/README.md@@ -7,7 +7,7 @@ npx @opencomputer/cli init my-agentcd my-agentnpm installnpx --package @opencomputer/cli opencomputer login-npx --package @opencomputer/cli opencomputer link+npx --package @opencomputer/cli opencomputer link --project <id-or-slug>```Agent definitions live under `opencomputer/agents/`. The default initializer@@ -19,12 +19,10 @@ Watch source and deploy changes to Development (Cloud):npm run deploy -- --watch```-`opencomputer link` asks whether to create a project or select an existing-project from the authenticated account. Later commands reuse that local binding.-If you skip this step, the first project-scoped command prompts you to link.-Use `opencomputer deploy --watch --project <id|slug>` for non-interactive-selection or `opencomputer deploy --watch --create-project <name>` to create-one explicitly.+`opencomputer link --project <id|slug>` links an existing project;+`opencomputer link --create-project <name>` creates and links one. Later+commands reuse that local binding without prompting. An unlinked command fails+with the exact link command needed to proceed.The production cloud API (`https://app.opencomputer.dev`) is the default.Override it only with `--api-url` or `OPENCOMPUTER_API_URL`.@@ -61,21 +59,21 @@ structured payload is available to agent code as `input.payload`.## Secrets and managed egress-Secret values are read from a hidden prompt, or from standard input in CI.+Secret values are accepted only from standard input with `--value-stdin`.They are write-only: list output contains names, scope, environment, and-allowed origins, never values.+allowed origins, never values or command-line arguments.-During development, put agent secrets in `opencomputer/.env.local`. The CLI-syncs only names referenced by `useSecret()` and limits each value to origins-declared by `defineConnection()`. It asks before the first upload, watches for-changes, and skips unrelated variables rather than granting wildcard access.+During development, `opencomputer doctor` checks names referenced by+`useSecret()` against `opencomputer/.env.example` and the ignored+`opencomputer/.env.local`. Upload values explicitly with `secrets set`; the CLI+infers and enforces origins declared by `defineConnection()`.```bash# Project-level development secret. Allowed origins are inferred from code.-opencomputer secrets set GITHUB_TOKEN+printf %s "$GITHUB_TOKEN" | opencomputer secrets set GITHUB_TOKEN --value-stdin# Agent-level production override.-opencomputer secrets set GITHUB_TOKEN \+printf %s "$GITHUB_TOKEN" | opencomputer secrets set GITHUB_TOKEN --value-stdin \--agent current \--environment production@@ -88,8 +86,8 @@ environment, use encrypted agent runtime variables. They require no sourcedeclaration and apply to newly started runtimes:```bash-opencomputer env set DATABASE_URL-opencomputer env set DATABASE_URL --agent current --environment production+printf %s "$DATABASE_URL" | opencomputer env set DATABASE_URL --value-stdin+printf %s "$DATABASE_URL" | opencomputer env set DATABASE_URL --value-stdin --agent current --environment productionopencomputer env list --environment developmentopencomputer env remove DATABASE_URL --environment development```@@ -109,3 +107,9 @@ opencomputer logsopencomputer logs --agent my-agent --environment development --followopencomputer logs --session <session-id> --json```++Use `opencomputer sessions tail <session-id> --json` for durable NDJSON session+events and `opencomputer channels status --json` for the last accepted event,+delivery outcome, and redacted error category. All commands accept `--json`;+mutations accept `--idempotency-key <stable-retry-key>`. Run+`opencomputer doctor --json` for the sub-second local pre-deploy scan.diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsnew file mode 100644index 00000000..18867e39--- /dev/null+++ b/cli/src/api.test.ts@@ -0,0 +1,27 @@+import assert from "node:assert/strict";+import test from "node:test";++import { OpenComputerClient } from "./api.js";++test("mutations derive stable, operation-specific idempotency headers", async (context) => {+ const requests: Request[] = [];+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ requests.push(request);+ return Response.json({ id: "project", agents: [], environments: [] });+ });+ const client = new OpenComputerClient(+ { apiUrl: "https://app.opencomputer.dev", apiKey: "test" },+ "retry-42",+ );++ await client.createProject("Agent", "agent");+ await client.createProject("Agent", "agent");+ await client.createProject("Different", "different");++ const keys = requests.map((request) => request.headers.get("idempotency-key"));+ assert.ok(keys[0]);+ assert.equal(keys[0], keys[1]);+ assert.notEqual(keys[0], keys[2]);+ assert.equal(keys[0]?.includes("retry-42"), false);+});diff --git a/cli/src/api.ts b/cli/src/api.tsindex cf800726..ca6a183b 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -1,3 +1,5 @@+import { createHash } from "node:crypto";+import type { ResolvedConfig } from "./config.js";import type { ProjectResourceManifest } from "./project.js";@@ -121,6 +123,29 @@ export interface ManagedAgentLog {data: Record<string, unknown>;}+export interface ManagedChannelStatus {+ id: string;+ channel: "slack";+ channelId?: string;+ agentId: string;+ alias: string;+ appName?: string;+ teamName?: string;+ status: string;+ verifiedAt?: string;+ lastEventAt?: string;+ lastDelivery?: {+ status: "delivered" | "failed";+ at: string;+ };+ lastError?: {+ category: string;+ at: string;+ };+ createdAt: string;+ updatedAt: string;+}+export interface ManagedSessionSnapshot {id: string;status: string;@@ -166,7 +191,10 @@ function errorMessage(body: unknown, status: number): string {}export class OpenComputerClient {- constructor(private readonly config: ResolvedConfig) {}+ constructor(+ private readonly config: ResolvedConfig,+ private readonly idempotencyKey?: string,+ ) {}private async request<T>(path: string,@@ -185,6 +213,21 @@ export class OpenComputerClient {}headers.set("x-api-key", this.config.apiKey);}+ const method = (init.method ?? "GET").toUpperCase();+ if (this.idempotencyKey && method !== "GET" && method !== "HEAD") {+ headers.set(+ "idempotency-key",+ createHash("sha256")+ .update(this.idempotencyKey)+ .update("\0")+ .update(method)+ .update("\0")+ .update(path)+ .update("\0")+ .update(typeof init.body === "string" ? init.body : "")+ .digest("hex"),+ );+ }const response = await fetch(`${this.config.apiUrl}${path}`, {...init,headers,@@ -521,6 +564,13 @@ export class OpenComputerClient {);}+ async channels(): Promise<ManagedChannelStatus[]> {+ const result = await this.request<{ channels: ManagedChannelStatus[] }>(+ "/api/managed-agents/channels",+ );+ return result.channels;+ }+registerDeployment(input: {agentId: string;name: string;@@ -588,14 +638,18 @@ export class OpenComputerClient {);}- createTurn(sessionId: string, input: string) {+ createTurn(+ sessionId: string,+ input: string,+ idempotencyKey: string = crypto.randomUUID(),+ ) {return this.request<{ turnId: string; duplicate: boolean }>(`/api/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,{method: "POST",body: JSON.stringify({input,- idempotencyKey: crypto.randomUUID(),+ idempotencyKey,}),},);diff --git a/cli/src/binding.test.ts b/cli/src/binding.test.tsindex 9604d565..1fe5fa94 100644--- a/cli/src/binding.test.ts+++ b/cli/src/binding.test.ts@@ -42,7 +42,7 @@ test("first dev can select an existing project and later reuses its binding", asclient,config,initialized.agentRoot,- { project: "existing-project", interactive: false },+ { project: "existing-project" },);assert.equal(selected.projectId, "prj_existing");assert.equal(selected.agentId, "agent-cloud");@@ -62,7 +62,7 @@ test("first dev can select an existing project and later reuses its binding", asclient,config,initialized.agentRoot,- { interactive: false },+ {},);assert.deepEqual(reused, selected);assert.equal(creates, 0);@@ -87,7 +87,7 @@ test("non-interactive commands direct an unlinked app to link", async () => {},{ apiUrl: "https://app.opencomputer.dev" },initialized.agentRoot,- { interactive: false },+ {},),/opencomputer link/,);@@ -95,3 +95,29 @@ test("non-interactive commands direct an unlinked app to link", async () => {await rm(root, { recursive: true, force: true });}});++test("explicit project creation reuses the existing slug on retry", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-binding-"));+ try {+ const initialized = await initializeAgentProject(root);+ let creates = 0;+ const binding = await ensureProjectBinding(+ {+ async projects() {+ return [project()];+ },+ async createProject() {+ creates += 1;+ return project();+ },+ },+ { apiUrl: "https://app.opencomputer.dev" },+ initialized.agentRoot,+ { createProjectName: "Existing Project" },+ );+ assert.equal(binding.projectId, "prj_existing");+ assert.equal(creates, 0);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/binding.ts b/cli/src/binding.tsindex b4ef632d..7bcf260e 100644--- a/cli/src/binding.ts+++ b/cli/src/binding.ts@@ -1,6 +1,5 @@-import { createInterface } from "node:readline/promises";import { access, mkdir, readFile, writeFile } from "node:fs/promises";-import { basename, dirname, resolve } from "node:path";+import { dirname, resolve } from "node:path";import type { ManagedProject, OpenComputerClient } from "./api.js";import type { ResolvedConfig } from "./config.js";@@ -19,8 +18,6 @@ export interface ProjectBinding {export interface ProjectBindingOptions {project?: string;createProjectName?: string;- interactive?: boolean;- select?: boolean;}async function exists(path: string): Promise<boolean> {@@ -73,30 +70,6 @@ async function readBinding(}}-async function chooseProject(- projects: ManagedProject[],- defaultName: string,-): Promise<{ project?: ManagedProject; createName?: string }> {- const terminal = createInterface({ input: process.stdin, output: process.stdout });- try {- process.stdout.write("\nConnect this app to a Development (Cloud) project:\n\n");- process.stdout.write(` 1) Create a new project\n`);- projects.forEach((project, index) => {- process.stdout.write(` ${String(index + 2)}) ${project.name} (${project.slug})\n`);- });- const answer = (await terminal.question("\nSelect [1]: ")).trim() || "1";- const selected = Number.parseInt(answer, 10);- if (!Number.isInteger(selected) || selected < 1 || selected > projects.length + 1) {- throw new Error("Choose one of the numbered project options.");- }- if (selected > 1) return { project: projects[selected - 2] };- const name = (await terminal.question(`Project name [${defaultName}]: `)).trim();- return { createName: name || defaultName };- } finally {- terminal.close();- }-}-async function persistBinding(projectRoot: string,config: ResolvedConfig,@@ -132,7 +105,7 @@ export async function ensureProjectBinding(}const projectRoot = await findOpenComputerProjectRoot(agentRoot);const projects = await client.projects();- if (!options.project && !options.createProjectName && !options.select) {+ if (!options.project && !options.createProjectName) {const existing = await readBinding(projectRoot, config.apiUrl);if (existing &&@@ -156,15 +129,14 @@ export async function ensureProjectBinding(throw new Error(`Project ${options.project} was not found in this account.`);}let createName = options.createProjectName;+ if (!project && createName) {+ const slug = agentIdFromName(createName);+ project = projects.find((candidate) => candidate.slug === slug);+ }if (!project && !createName) {- if (options.interactive === false || !process.stdin.isTTY || !process.stdout.isTTY) {- throw new Error(- "This app is not connected to a cloud project. Run `opencomputer link`.",- );- }- const choice = await chooseProject(projects, basename(projectRoot));- project = choice.project;- createName = choice.createName;+ throw new Error(+ "This app is not connected to a cloud project. Run `opencomputer link --project <id|slug>` or `opencomputer link --create-project <name>`.",+ );}project ??= await client.createProject(createName!,diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 625f6137..4f490a33 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -28,12 +28,15 @@ import {resolveProjectAgent,} from "./session-command.js";import { formatSessionEvent } from "./session-prompt.js";+import { doctorProject, type DoctorResult } from "./doctor.js";+import { CLIError } from "./errors.js";export interface GlobalOptions {apiUrl?: string;apiKey?: string;json: boolean;verbose?: boolean;+ idempotencyKey?: string;}export function deploymentAlias(requestedAlias?: string): string {@@ -51,6 +54,10 @@ function printJSON(value: unknown): void {process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);}+function printJSONLine(value: unknown): void {+ process.stdout.write(`${JSON.stringify(value)}\n`);+}+function flag(args: string[], name: string): boolean {const index = args.indexOf(name);if (index < 0) return false;@@ -93,49 +100,48 @@ function consumeModelAccessProvider(args: string[]): "claude" | "codex" {return "codex";}-async function readSecretValue(): 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;+async function readStdinValue(enabled: boolean): Promise<string> {+ if (!enabled) {+ throw new CLIError(+ "value_stdin_required",+ "A value must be supplied through standard input.",+ "Pipe the value into this command and add `--value-stdin`.",+ );}- 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);- });+ if (process.stdin.isTTY) {+ throw new CLIError(+ "value_stdin_required",+ "--value-stdin requires piped standard input.",+ "Use `printf %s \"$VALUE\" | opencomputer ... --value-stdin`.",+ );+ }+ 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("Standard-input value was empty");+ return value;+}++function printDoctor(result: DoctorResult, json: boolean): void {+ if (json) return printJSON(result);+ for (const item of result.diagnostics) {+ process.stdout.write(+ `${item.severity.toUpperCase()} ${item.code} ${item.file}${item.line ? `:${item.line}` : ""}\n` ++ ` ${item.message}\n fix: ${item.hint}\n`,+ );+ }+ process.stdout.write(+ `${result.ok ? "Doctor passed" : "Doctor failed"}: ${result.summary.errors} errors, ` ++ `${result.summary.warnings} warnings in ${result.durationMs}ms.\n`,+ );}async function selectedProject(client: OpenComputerClient,config: Awaited<ReturnType<typeof resolveConfig>>,reference?: string,- interactive = true,): Promise<{ projectId: string; agentId: string }> {if (reference) {const project = (await client.projects()).find(@@ -147,9 +153,7 @@ async function selectedProject(return { projectId: project.id, agentId: agent.id };}const root = await findOpenComputerProjectRoot(process.cwd());- const binding = await ensureProjectBinding(client, config, root, {- interactive,- });+ const binding = await ensureProjectBinding(client, config, root);return { projectId: binding.projectId, agentId: binding.agentId };}@@ -271,6 +275,7 @@ async function sendAgentTurn(prompt: string,keep: boolean,json: boolean,+ idempotencyKey?: string,): Promise<{ turnId: string; output?: string }> {const existing = await client.events(sessionId, 0);let cursor = existing.at(-1)?.seq ?? 0;@@ -288,7 +293,7 @@ async function sendAgentTurn();cursor = connected.cursor;}- const turn = await client.createTurn(sessionId, prompt);+ const turn = await client.createTurn(sessionId, prompt, idempotencyKey);let streamedText = "";let completedText = "";const completed = await waitForEvent(@@ -362,6 +367,40 @@ async function attachSession(}}+async function tailSession(+ client: OpenComputerClient,+ sessionId: string,+ after: number,+ follow: boolean,+ json: boolean,+): Promise<void> {+ let cursor = after;+ let stopped = false;+ const stop = (): void => {+ stopped = true;+ };+ process.once("SIGINT", stop);+ try {+ do {+ const events = await client.events(sessionId, cursor);+ for (const event of events) {+ cursor = Math.max(cursor, event.seq);+ if (json) printJSONLine({ sessionId, cursor: event.seq, ...event });+ else {+ process.stdout.write(+ `${event.seq} ${event.type} ${JSON.stringify(event.data)}\n`,+ );+ }+ }+ if (follow && !stopped) {+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ } while (follow && !stopped);+ } finally {+ process.off("SIGINT", stop);+ }+}+export function nextAgentEventDeadline(deadline: number,timeoutMs: number,@@ -411,6 +450,7 @@ async function runAgent(keep: boolean,json: boolean,verbose: boolean,+ idempotencyKey?: string,): Promise<unknown> {const created = await client.createSession(agent);process.stderr.write(`Starting ${agent}…\n`);@@ -422,7 +462,7 @@ async function runAgent((event) => printSessionProgress(event, json, verbose),90_000,);- const turn = await client.createTurn(created.session.id, prompt);+ const turn = await client.createTurn(created.session.id, prompt, idempotencyKey);let streamed = false;let streamedText = "";let completedText = "";@@ -477,7 +517,7 @@ export async function runCommand(): Promise<void> {const args = [...rawArgs];const config = await resolveConfig(globals);- const client = new OpenComputerClient(config);+ const client = new OpenComputerClient(config, globals.idempotencyKey);if (command === "login") {const identity = await login(config, {@@ -542,7 +582,7 @@ export async function runCommand(process.stdout.write(`Created the ${initialized.manifest.name} OpenComputer app\n` +`Directory: ${initialized.root}\n` +- `Project: choose or create one on the first watched deployment\n` ++ `Project: link explicitly with --project or --create-project\n` +`Agents: opencomputer/\n` +(spa? `Web app: src/ (separate lifecycle)\n\n`@@ -580,12 +620,31 @@ export async function runCommand(return;}+ if (command === "doctor") {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const root = await findOpenComputerProjectRoot(process.cwd());+ const result = await doctorProject(root);+ if (!result.ok) {+ if (!globals.json) printDoctor(result, false);+ throw new CLIError(+ "doctor_failed",+ "Local project diagnostics failed.",+ "Fix the reported errors and rerun `opencomputer doctor --json`.",+ result,+ );+ }+ printDoctor(result, globals.json);+ return;+ }+if (command === "link") {+ const project = option(args, "--project");+ const createProjectName = option(args, "--create-project");if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);const root = await findOpenComputerProjectRoot(process.cwd());const binding = await ensureProjectBinding(client, config, root, {- interactive: !globals.json,- select: true,+ project,+ createProjectName,});if (globals.json) printJSON(binding);else {@@ -608,6 +667,15 @@ export async function runCommand("No OpenComputer project found. Run `opencomputer init <directory>` first.",);}+ const diagnosis = await doctorProject(root);+ if (!diagnosis.ok) {+ throw new CLIError(+ "doctor_failed",+ "Deploy stopped because local project diagnostics failed.",+ "Run `opencomputer doctor --json`, fix the errors, and deploy again.",+ diagnosis,+ );+ }if (watch) {if (requestedAlias && requestedAlias !== "development") {throw new Error(@@ -617,7 +685,6 @@ export async function runCommand(await runDeploymentWatch(client, config, root, {project,createProjectName,- interactive: !globals.json,});return;}@@ -625,10 +692,7 @@ export async function runCommand(throw new Error("--project and --create-project require --watch");}const alias = deploymentAlias(requestedAlias);- const binding = await ensureProjectBinding(client, config, root, {- interactive: !globals.json,- select: true,- });+ const binding = await ensureProjectBinding(client, config, root);const results = await publishProjectDeployment(client,root,@@ -667,6 +731,7 @@ export async function runCommand(keep,globals.json,globals.verbose === true,+ globals.idempotencyKey,);if (globals.json) printJSON(result);return;@@ -679,14 +744,23 @@ export async function runCommand(process.stderr.write("`opencomputer dev` is deprecated. Use `opencomputer deploy --watch`; start any web app separately.\n",);+ const root = await findOpenComputerProjectRoot(process.cwd());+ const diagnosis = await doctorProject(root);+ if (!diagnosis.ok) {+ throw new CLIError(+ "doctor_failed",+ "Deploy stopped because local project diagnostics failed.",+ "Run `opencomputer doctor --json`, fix the errors, and deploy again.",+ diagnosis,+ );+ }await runCloudDevelopment(client,config,- await findOpenComputerProjectRoot(process.cwd()),+ root,{project,createProjectName,- interactive: !globals.json,},);return;@@ -701,7 +775,6 @@ export async function runCommand(client,config,projectReference,- !globals.json,);const agentId = agentOption? agentOption === "current"@@ -734,6 +807,7 @@ export async function runCommand(}if (action === "set") {const explicitOrigins = options(args, "--allow-origin");+ const valueStdin = flag(args, "--value-stdin");if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);let allowedOrigins = explicitOrigins;if (!allowedOrigins.length) {@@ -760,7 +834,7 @@ export async function runCommand(const secret = await client.putSecret({projectId: project.projectId,name,- value: await readSecretValue(),+ value: await readStdinValue(valueStdin),environment,...(agentId ? { agentId } : {}),allowedOrigins,@@ -815,7 +889,7 @@ export async function runCommand(const currentAgentRoot = projectReference ? null : await findAgentRoot();const project =shouldBindModelAccessProject(projectReference, currentAgentRoot)- ? await selectedProject(client, config, projectReference, false)+ ? await selectedProject(client, config, projectReference): undefined;const environments = project? (["development", "production"] as const)@@ -902,7 +976,6 @@ export async function runCommand(client,config,projectReference,- !globals.json,);const agentId = agentOption? agentOption === "current"@@ -934,11 +1007,12 @@ export async function runCommand(throw new Error("Use `opencomputer env set|list|remove <name>`.");}if (action === "set") {+ const valueStdin = flag(args, "--value-stdin");if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);const variable = await client.putRuntimeVariable({projectId: project.projectId,name,- value: await readSecretValue(),+ value: await readStdinValue(valueStdin),environment,...(agentId ? { agentId } : {}),});@@ -976,7 +1050,6 @@ export async function runCommand(client,config,projectReference,- !globals.json,);const agentId = await selectedSessionAgent(client,@@ -1007,19 +1080,27 @@ export async function runCommand(if (!name || args.length) {throw new Error("Use `opencomputer webhooks create <name>`.");}- const webhook = await client.createWebhook({+ const existing = (await client.webhooks({projectId: project.projectId,- name,environment,agentId,- });- if (globals.json) printJSON(webhook);+ })).find((candidate) => candidate.name === name);+ const webhook =+ existing ??+ (await client.createWebhook({+ projectId: project.projectId,+ name,+ environment,+ agentId,+ }));+ if (globals.json) printJSON({ ...webhook, reused: Boolean(existing) });else {process.stdout.write(- `Created ${webhook.name} (${webhook.id}) for ${agentId}@${environment}.\n` ++ `${existing ? "Reused" : "Created"} ${webhook.name} (${webhook.id}) for ${agentId}@${environment}.\n` +`URL: ${webhook.invocationUrl}\n` +- `Token: ${webhook.token ?? "unavailable"}\n` +- "Save this token now. It will not be shown again.\n",+ (existing+ ? "The existing token remains unchanged.\n"+ : `Token: ${webhook.token ?? "unavailable"}\nSave this token now. It will not be shown again.\n`),);}return;@@ -1092,7 +1173,7 @@ export async function runCommand(}if (insideProject) {agentId = (- await selectedProject(client, config, undefined, !globals.json)+ await selectedProject(client, config)).agentId;}}@@ -1123,7 +1204,58 @@ export async function runCommand(return;}- if (command === "session") {+ if (command === "channels") {+ const action = args.shift();+ if (action !== "status") {+ throw new Error("Use `opencomputer channels status`.");+ }+ const projectReference = option(args, "--project");+ const agentOption = option(args, "--agent");+ const environment = environmentOption(option(args, "--environment"));+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const project = await selectedProject(+ client,+ config,+ projectReference,+ );+ const agentId = await selectedSessionAgent(+ client,+ project,+ !agentOption || agentOption === "current" ? undefined : agentOption,+ );+ const channels = (await client.channels()).filter(+ (channel) => channel.agentId === agentId && channel.alias === environment,+ );+ if (globals.json) printJSON({ projectId: project.projectId, environment, channels });+ else if (!channels.length) process.stdout.write("No matching channels.\n");+ else {+ for (const channel of channels) {+ process.stdout.write(+ `${channel.id} ${channel.status} ${channel.channel} ${channel.agentId}@${channel.alias}\n` ++ ` last event: ${channel.lastEventAt ?? "—"}\n` ++ ` last delivery: ${channel.lastDelivery ? `${channel.lastDelivery.status} at ${channel.lastDelivery.at}` : "—"}\n` ++ ` last error: ${channel.lastError ? `${channel.lastError.category} at ${channel.lastError.at}` : "—"}\n`,+ );+ }+ }+ return;+ }++ if (command === "session" || command === "sessions") {+ if (args[0] === "tail") {+ args.shift();+ const sessionId = args.shift();+ const afterValue = option(args, "--after");+ const follow = !flag(args, "--no-follow");+ if (!sessionId) throw new Error("A session ID is required.");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const after = afterValue ? Number.parseInt(afterValue, 10) : 0;+ if (!Number.isFinite(after) || after < 0) {+ throw new Error("--after must be a non-negative event cursor");+ }+ await tailSession(client, sessionId, after, follow, globals.json);+ return;+ }const session = parseSessionCommand(args);const sessionArgs = session.args;if (session.action === "list") {@@ -1141,7 +1273,6 @@ export async function runCommand(client,config,undefined,- !globals.json,);const agentId = await selectedSessionAgent(client,@@ -1157,6 +1288,7 @@ export async function runCommand(session.keep,globals.json,globals.verbose === true,+ globals.idempotencyKey,);if (globals.json) printJSON(result);return;@@ -1214,6 +1346,7 @@ export async function runCommand(prompt,session.keep,globals.json,+ globals.idempotencyKey,);if (globals.json) {printJSON({ sessionId, ...result, status: "completed" });diff --git a/cli/src/dev.test.ts b/cli/src/dev.test.tsindex b3730541..c3ec159f 100644--- a/cli/src/dev.test.ts+++ b/cli/src/dev.test.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { resolve } from "node:path";import test from "node:test";@@ -10,7 +10,6 @@ import {projectDashboardURL,publishDevelopment,publishProjectDevelopment,- syncDevelopmentSecrets,} from "./dev.js";import { initializeAgentProject } from "./project.js";@@ -144,149 +143,3 @@ test("development publish synchronizes every configured project agent", async ()await rm(parent, { recursive: true, force: true });}});--test("development syncs declared .env.local secrets to inferred origins", async () => {- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-dev-secrets-"));- try {- const initialized = await initializeAgentProject(- resolve(parent, "app"),- undefined,- { spa: false },- );- await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });- await writeFile(- resolve(initialized.agentRoot, "tools", "github.ts"),- `import { bearer, defineConnection, defineTool, useSecret } from "@opencomputer/agent";--const github = defineConnection({- id: "github-api",- origin: "https://api.github.com",- redirectOrigins: [{ origin: "https://codeload.github.com" }],- headers: { Authorization: bearer(useSecret("GITHUB_TOKEN")) },-});--export const repository = defineTool({- name: "github_repository",- description: "Read a GitHub repository",- async run() { return await (await github.fetch("/repos/opencomputer/example")).json(); },-});-`,- );- await writeFile(- resolve(initialized.agentRoot, "agent.ts"),- `import { useTool } from "@opencomputer/agent";-import { repository } from "./tools/github.js";-export default function Agent() { useTool(repository); return "Use GitHub."; }-`,- );- const binding = {- version: 1 as const,- apiUrl: "https://app.opencomputer.dev",- projectId: "prj_test",- projectName: "Test",- agentId: "test-agent",- };- const results = await publishProjectDevelopment(- {- async registerDeployment(value) {- return {- id: `${value.agentId}:${value.source.digest}`,- agentId: value.agentId,- alias: value.alias,- createdAt: new Date(0).toISOString(),- };- },- },- initialized.root,- binding,- );- await writeFile(- resolve(initialized.root, "opencomputer", ".env.local"),- "GITHUB_TOKEN=first-secret\n",- );- const uploads: Array<{- name: string;- value: string;- allowedOrigins: string[];- }> = [];- let confirmations = 0;- const client = {- async putSecret(input: {- projectId: string;- name: string;- value: string;- environment: "development" | "production";- agentId?: string;- allowedOrigins: string[];- }) {- uploads.push(input);- return {- name: input.name,- projectId: input.projectId,- environment: input.environment,- allowedOrigins: input.allowedOrigins,- createdAt: new Date(0).toISOString(),- updatedAt: new Date(0).toISOString(),- };- },- };- const confirm = async () => {- confirmations += 1;- return true;- };- assert.deepEqual(- await syncDevelopmentSecrets(- client,- { apiUrl: binding.apiUrl },- initialized.root,- binding,- results,- { confirm },- ),- ["GITHUB_TOKEN"],- );- assert.deepEqual(uploads, [- {- projectId: "prj_test",- name: "GITHUB_TOKEN",- value: "first-secret",- environment: "development",- allowedOrigins: [- "https://api.github.com",- "https://codeload.github.com",- ],- },- ]);- await syncDevelopmentSecrets(- client,- { apiUrl: binding.apiUrl },- initialized.root,- binding,- results,- { confirm },- );- assert.equal(uploads.length, 1);- await writeFile(- resolve(initialized.root, "opencomputer", ".env.local"),- "GITHUB_TOKEN=changed-secret\n",- );- await syncDevelopmentSecrets(- client,- { apiUrl: binding.apiUrl },- initialized.root,- binding,- results,- { confirm },- );- assert.equal(confirmations, 1);- assert.equal(uploads.length, 2);- assert.equal(uploads[1]?.value, "changed-secret");- const state = await readFile(- resolve(initialized.root, ".opencomputer", "dev-secrets.json"),- "utf8",- );- assert.doesNotMatch(state, /first-secret|changed-secret/);- } finally {- await rm(parent, { recursive: true, force: true });- }-});diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex e3683bf1..0ee5ef6b 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -1,10 +1,8 @@import { spawn, type ChildProcess } from "node:child_process";import { createHash } from "node:crypto";import { watch, type FSWatcher } from "node:fs";-import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { access, mkdir, rm, writeFile } from "node:fs/promises";import { resolve } from "node:path";-import { createInterface } from "node:readline/promises";-import { parseEnv } from "node:util";import type { OpenComputerClient } from "./api.js";import type { ResolvedConfig } from "./config.js";@@ -26,190 +24,6 @@ import {const DEVELOPMENT_ALIAS = "development";const DEBOUNCE_MS = 180;-type DevelopmentResults = Awaited<- ReturnType<typeof publishProjectDevelopment>->;--interface SecretSyncState {- version: 1;- apiUrl: string;- projectId: string;- hashes: Record<string, string>;-}--function secretSyncStatePath(projectRoot: string): string {- return resolve(projectRoot, ".opencomputer", "dev-secrets.json");-}--async function readSecretSyncState(- projectRoot: string,- config: ResolvedConfig,- binding: ProjectBinding,-): Promise<SecretSyncState> {- try {- const value = JSON.parse(- await readFile(secretSyncStatePath(projectRoot), "utf8"),- ) as Partial<SecretSyncState>;- if (- value.version === 1 &&- value.apiUrl === config.apiUrl &&- value.projectId === binding.projectId &&- value.hashes &&- typeof value.hashes === "object"- ) {- return value as SecretSyncState;- }- } catch {- // A missing or invalid state file requires fresh consent.- }- return {- version: 1,- apiUrl: config.apiUrl,- projectId: binding.projectId,- hashes: {},- };-}--function secretOrigins(results: DevelopmentResults): Map<string, string[]> {- const origins = new Map<string, Set<string>>();- for (const { built } of results) {- for (const connection of built.httpConnections) {- for (const header of Object.values(connection.headers)) {- if (typeof header === "string") continue;- const current = origins.get(header.name) ?? new Set<string>();- current.add(connection.origin);- for (const redirect of connection.redirectOrigins ?? []) {- current.add(redirect.origin);- }- origins.set(header.name, current);- }- }- }- return new Map(- [...origins].map(([name, values]) => [name, [...values].sort()]),- );-}--function secretHash(value: string, origins: string[]): string {- return createHash("sha256")- .update(JSON.stringify({ value, origins }))- .digest("hex");-}--async function confirmNewSecrets(- secrets: Array<{ name: string; origins: string[] }>,-): Promise<boolean> {- if (!process.stdin.isTTY || !process.stdout.isTTY) return false;- process.stdout.write("\nSecrets found in opencomputer/.env.local:\n\n");- for (const secret of secrets) {- process.stdout.write(- ` ${secret.name.padEnd(28)} → ${secret.origins.map((origin) => new URL(origin).host).join(", ")}\n`,- );- }- const terminal = createInterface({- input: process.stdin,- output: process.stdout,- });- try {- const answer = (- await terminal.question("\nSync these development secrets? [Y/n] ")- )- .trim()- .toLowerCase();- return answer === "" || answer === "y" || answer === "yes";- } finally {- terminal.close();- }-}--export async function syncDevelopmentSecrets(- client: Pick<OpenComputerClient, "putSecret">,- config: ResolvedConfig,- projectRoot: string,- binding: ProjectBinding,- results: DevelopmentResults,- options: {- confirm?: (- secrets: Array<{ name: string; origins: string[] }>,- ) => Promise<boolean>;- } = {},-): Promise<string[]> {- const path = resolve(projectRoot, "opencomputer", ".env.local");- let values: Record<string, string | undefined>;- try {- values = parseEnv(await readFile(path, "utf8"));- } catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];- throw error;- }-- const origins = secretOrigins(results);- const referenced = [...origins]- .filter(([name]) => typeof values[name] === "string" && values[name] !== "")- .map(([name, allowedOrigins]) => ({- name,- value: values[name]!,- origins: allowedOrigins,- }));- const unmatched = Object.keys(values)- .filter(- (name) =>- typeof values[name] === "string" &&- values[name] !== "" &&- !origins.has(name),- )- .sort();- for (const name of unmatched) {- process.stderr.write(- `Skipped ${name}: it is not referenced by a defineConnection() declaration.\n`,- );- }- if (!referenced.length) return [];-- const state = await readSecretSyncState(projectRoot, config, binding);- const pending = referenced.filter(- (secret) =>- state.hashes[secret.name] !== secretHash(secret.value, secret.origins),- );- if (!pending.length) return [];- const newSecrets = pending.filter((secret) => !(secret.name in state.hashes));- if (newSecrets.length) {- const confirmed = await (options.confirm ?? confirmNewSecrets)(newSecrets);- if (!confirmed) {- process.stderr.write(- "Development secret sync skipped. Use `opencomputer secrets set` or restart `opencomputer deploy --watch` to approve it.\n",- );- return [];- }- }-- const synced: string[] = [];- for (const secret of pending) {- await client.putSecret({- projectId: binding.projectId,- name: secret.name,- value: secret.value,- environment: "development",- allowedOrigins: secret.origins,- });- state.hashes[secret.name] = secretHash(secret.value, secret.origins);- synced.push(secret.name);- process.stdout.write(- `Synced development secret ${secret.name} for ${secret.origins.join(", ")}\n`,- );- }- await mkdir(resolve(projectRoot, ".opencomputer"), {- recursive: true,- mode: 0o700,- });- await writeFile(- secretSyncStatePath(projectRoot),- `${JSON.stringify(state, null, 2)}\n`,- { mode: 0o600 },- );- return synced;-}-export async function publishDevelopment(client: Pick<OpenComputerClient, "registerDeployment">,root: string,@@ -338,11 +152,6 @@ function sourceChange(filename: string | Buffer | null): boolean {return !normalized.split("/").includes(".opencomputer");}-function secretFileChange(filename: string | Buffer | null): boolean {- if (!filename) return false;- return filename.toString().replaceAll("\\", "/") === ".env.local";-}-function waitForShutdown(web?: ChildProcess): Promise<void> {return new Promise((done) => {const cleanup = () => {@@ -456,27 +265,6 @@ export async function runDeploymentWatch(let publishing = false;let pending = false;const lastDigests = new Map<string, string>();- let latestResults: DevelopmentResults = [];- let secretSync = Promise.resolve();-- const syncSecrets = () => {- secretSync = secretSync- .then(async () => {- await syncDevelopmentSecrets(- client,- config,- projectRoot,- binding,- latestResults,- );- })- .catch((error) => {- process.stderr.write(- `Secret sync failed: ${error instanceof Error ? error.message : String(error)}\n`,- );- });- return secretSync;- };const publish = async () => {if (publishing) {@@ -494,7 +282,6 @@ export async function runDeploymentWatch(projectRoot,binding,);- latestResults = results;let changed = false;for (const result of results) {if (@@ -511,7 +298,6 @@ export async function runDeploymentWatch(if (!changed) {process.stdout.write("✓ Development is already up to date.\n");}- await syncSecrets();} catch (error) {process.stderr.write(`✗ Deployment failed: ${error instanceof Error ? error.message : String(error)}\n` +@@ -530,11 +316,9 @@ export async function runDeploymentWatch(projectRoot,binding,);- latestResults = initial;for (const result of initial) {lastDigests.set(result.deployment.agentId, result.built.digest);}- await syncSecrets();const spa = await hasReactSpa(projectRoot);const startWebApp = behavior.startWebApp === true && spa;process.stdout.write(@@ -555,11 +339,6 @@ export async function runDeploymentWatch(resolve(projectRoot, "opencomputer"),{ recursive: true },(_event, filename) => {- if (secretFileChange(filename)) {- if (timer) clearTimeout(timer);- timer = setTimeout(() => void syncSecrets(), DEBOUNCE_MS);- return;- }if (!sourceChange(filename)) return;if (timer) clearTimeout(timer);timer = setTimeout(() => void publish(), DEBOUNCE_MS);diff --git a/cli/src/doctor.test.ts b/cli/src/doctor.test.tsnew file mode 100644index 00000000..d8a6ebba--- /dev/null+++ b/cli/src/doctor.test.ts@@ -0,0 +1,84 @@+import assert from "node:assert/strict";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { resolve } from "node:path";+import test from "node:test";++import { doctorProject } from "./doctor.js";+import { initializeAgentProject } from "./project.js";++test("doctor reports deterministic local authoring errors in under one second", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-doctor-"));+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "connections"), { recursive: true });+ await writeFile(+ resolve(initialized.agentRoot, "connections", "github.ts"),+ `import { defineConnection, defineTool, useSecret } from "@opencomputer/agent";+const origin = "https://api.github.com";+export const github = defineConnection({+ id: "github",+ origin,+ headers: { Authorization: useSecret("GITHUB_TOKEN") },+});+export const misplaced = defineTool({ name: "misplaced", execute: async () => ({ ok: true }) });+`,+ );++ const result = await doctorProject(root);+ assert.equal(result.ok, false);+ assert.ok(result.durationMs < 1_000, `doctor took ${result.durationMs}ms`);+ assert.deepEqual(+ result.diagnostics.map((diagnostic) => diagnostic.code).sort(),+ [+ "connection_origin_not_literal",+ "development_secret_missing",+ "secret_not_declared",+ "tool_location_invalid",+ ],+ );+ assert.ok(result.diagnostics.every((diagnostic) => diagnostic.hint));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("doctor accepts the initialized project without contacting the API", async (context) => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-doctor-"));+ try {+ const fetchMock = context.mock.method(globalThis, "fetch", async () => {+ throw new Error("doctor must not use the network");+ });+ await initializeAgentProject(root);+ const result = await doctorProject(root);+ assert.equal(result.ok, true);+ assert.equal(result.summary.errors, 0);+ assert.equal(fetchMock.mock.callCount(), 0);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("doctor parses single-line declarations and ignores comments", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-doctor-"));+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "connections"), {+ recursive: true,+ });+ await writeFile(+ resolve(initialized.agentRoot, "connections", "inline.ts"),+ `import { defineConnection } from "@opencomputer/agent";+// defineTool({ name: "comment-only" })+export default defineConnection({ id: "inline", origin: "https://api.example.com/path" });+`,+ );+ const result = await doctorProject(root);+ assert.deepEqual(+ result.diagnostics.map((diagnostic) => diagnostic.code),+ ["connection_origin_not_literal"],+ );+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/doctor.ts b/cli/src/doctor.tsnew file mode 100644index 00000000..6bd12a94--- /dev/null+++ b/cli/src/doctor.ts@@ -0,0 +1,255 @@+import { access, readFile, readdir } from "node:fs/promises";+import { relative, resolve } from "node:path";+import ts from "typescript";++import { readProjectAgents, readProjectResources } from "./project.js";++export interface DoctorDiagnostic {+ code: string;+ severity: "error" | "warning";+ file: string;+ line?: number;+ message: string;+ hint: string;+}++export interface DoctorResult {+ ok: boolean;+ durationMs: number;+ diagnostics: DoctorDiagnostic[];+ summary: { errors: number; warnings: number; files: number };+}++async function exists(path: string): Promise<boolean> {+ try {+ await access(path);+ return true;+ } catch {+ return false;+ }+}++async function sourceFiles(directory: string): Promise<string[]> {+ if (!(await exists(directory))) return [];+ const files: string[] = [];+ for (const entry of await readdir(directory, { withFileTypes: true })) {+ const path = resolve(directory, entry.name);+ if (entry.isDirectory()) files.push(...(await sourceFiles(path)));+ else if (entry.isFile() && /\.[cm]?[jt]sx?$/.test(entry.name)) files.push(path);+ }+ return files.sort();+}++function envNames(source: string): Set<string> {+ return new Set(+ source+ .split(/\r?\n/)+ .map((line) => line.match(/^\s*([A-Z][A-Z0-9_]*)\s*=/)?.[1])+ .filter((name): name is string => Boolean(name)),+ );+}++function isLiteralHttpsOrigin(expression: ts.Expression): boolean {+ if (!ts.isStringLiteralLike(expression)) return false;+ try {+ const value = expression.text;+ const url = new URL(value);+ return url.protocol === "https:" && url.origin === value;+ } catch {+ return false;+ }+}++function property(+ object: ts.ObjectLiteralExpression,+ name: string,+): ts.PropertyAssignment | undefined {+ return object.properties.find(+ (item): item is ts.PropertyAssignment =>+ ts.isPropertyAssignment(item) &&+ ((ts.isIdentifier(item.name) && item.name.text === name) ||+ (ts.isStringLiteralLike(item.name) && item.name.text === name)),+ );+}++function callName(node: ts.CallExpression): string | undefined {+ return ts.isIdentifier(node.expression) ? node.expression.text : undefined;+}++export async function doctorProject(projectRoot: string): Promise<DoctorResult> {+ const started = performance.now();+ const diagnostics: DoctorDiagnostic[] = [];+ const files = await sourceFiles(resolve(projectRoot, "opencomputer"));+ const requiredSecrets = new Set<string>();+ const toolNames = new Map<string, Array<{ file: string; line: number }>>();+ for (const path of files) {+ const source = await readFile(path, "utf8");+ const file = relative(projectRoot, path).split("\\").join("/");+ const syntax = ts.createSourceFile(+ path,+ source,+ ts.ScriptTarget.Latest,+ true,+ path.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ const toolCalls: Array<{ name?: string; line: number }> = [];+ const visit = (node: ts.Node): void => {+ if (ts.isCallExpression(node)) {+ const name = callName(node);+ if (+ name === "useSecret" &&+ node.arguments[0] &&+ ts.isStringLiteralLike(node.arguments[0])+ ) {+ requiredSecrets.add(node.arguments[0].text);+ }+ if (name === "defineConnection") {+ const definition = node.arguments[0];+ const origin =+ definition && ts.isObjectLiteralExpression(definition)+ ? property(definition, "origin")+ : undefined;+ const redirects =+ definition && ts.isObjectLiteralExpression(definition)+ ? property(definition, "redirectOrigins")+ : undefined;+ const redirectsValid =+ !redirects ||+ (ts.isArrayLiteralExpression(redirects.initializer) &&+ redirects.initializer.elements.every((item) => {+ if (!ts.isObjectLiteralExpression(item)) return false;+ const redirectOrigin = property(item, "origin");+ return Boolean(+ redirectOrigin &&+ isLiteralHttpsOrigin(redirectOrigin.initializer),+ );+ }));+ if (+ !origin ||+ !isLiteralHttpsOrigin(origin.initializer) ||+ !redirectsValid+ ) {+ const line =+ syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line ++ 1;+ diagnostics.push({+ code: "connection_origin_not_literal",+ severity: "error",+ file,+ line,+ message:+ "Connection and redirect origins must be literal HTTPS origins without a path.",+ hint: 'Use `origin: "https://api.example.com"`.',+ });+ }+ }+ if (name === "defineTool") {+ const definition = node.arguments[0];+ const toolName =+ definition && ts.isObjectLiteralExpression(definition)+ ? property(definition, "name")+ : undefined;+ toolCalls.push({+ ...(toolName && ts.isStringLiteralLike(toolName.initializer)+ ? { name: toolName.initializer.text }+ : {}),+ line:+ syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line ++ 1,+ });+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(syntax);+ if (toolCalls.length && !/\/agents\/[^/]+\/tools\//.test(`/${file}`)) {+ diagnostics.push({+ code: "tool_location_invalid",+ severity: "error",+ file,+ line: toolCalls[0]!.line,+ message: "Tools must be defined in an agent's tools/ directory.",+ hint: "Move the tool into opencomputer/agents/<agent>/tools/<name>.ts.",+ });+ }+ for (const tool of toolCalls) {+ if (tool.name) {+ const occurrences = toolNames.get(tool.name) ?? [];+ occurrences.push({ file, line: tool.line });+ toolNames.set(tool.name, occurrences);+ }+ }+ if (toolCalls.some((tool) => !tool.name)) {+ diagnostics.push({+ code: "tool_name_not_literal",+ severity: "error",+ file,+ message: "Every tool must declare one literal name.",+ hint: 'Use `defineTool({ name: "stable-tool-id", ... })`.',+ });+ }+ }+ for (const [name, occurrences] of [...toolNames].sort(([a], [b]) =>+ a.localeCompare(b),+ )) {+ if (occurrences.length < 2) continue;+ diagnostics.push({+ code: "tool_name_duplicate",+ severity: "error",+ file: occurrences[1]!.file,+ line: occurrences[1]!.line,+ message: `Tool name ${name} is declared more than once.`,+ hint: "Give every tool in the project a unique literal name.",+ });+ }+ try {+ await readProjectAgents(projectRoot);+ await readProjectResources(projectRoot);+ } catch (error) {+ diagnostics.push({+ code: "project_contract_invalid",+ severity: "error",+ file: "opencomputer/",+ message: error instanceof Error ? error.message : String(error),+ hint: "Fix the referenced project, channel, scope, event, or resource declaration.",+ });+ }+ const examplePath = resolve(projectRoot, "opencomputer", ".env.example");+ const localPath = resolve(projectRoot, "opencomputer", ".env.local");+ const declared = envNames(+ (await exists(examplePath)) ? await readFile(examplePath, "utf8") : "",+ );+ const local = envNames(+ (await exists(localPath)) ? await readFile(localPath, "utf8") : "",+ );+ for (const name of [...requiredSecrets].sort()) {+ if (!declared.has(name)) {+ diagnostics.push({+ code: "secret_not_declared",+ severity: "error",+ file: "opencomputer/.env.example",+ message: `${name} is referenced by source but not declared.`,+ hint: `Add ${name}= without a value to opencomputer/.env.example.`,+ });+ }+ if (!local.has(name)) {+ diagnostics.push({+ code: "development_secret_missing",+ severity: "warning",+ file: "opencomputer/.env.local",+ message: `${name} has no local Development value.`,+ hint:+ `Add ${name} to the ignored .env.local file for local development; ` ++ `upload it separately with \`opencomputer secrets set ${name} --value-stdin\`.`,+ });+ }+ }+ const errors = diagnostics.filter((item) => item.severity === "error").length;+ const warnings = diagnostics.length - errors;+ return {+ ok: errors === 0,+ durationMs: Math.round((performance.now() - started) * 100) / 100,+ diagnostics,+ summary: { errors, warnings, files: files.length },+ };+}diff --git a/cli/src/errors.test.ts b/cli/src/errors.test.tsnew file mode 100644index 00000000..b89d87ba--- /dev/null+++ b/cli/src/errors.test.ts@@ -0,0 +1,18 @@+import assert from "node:assert/strict";+import test from "node:test";++import { APIError } from "./api.js";+import { CLIError, structuredError } from "./errors.js";++test("structured CLI errors always include a stable code and fix hint", () => {+ assert.deepEqual(+ structuredError(new CLIError("doctor_failed", "Invalid project.", "Run doctor.")),+ { code: "doctor_failed", message: "Invalid project.", hint: "Run doctor." },+ );+ assert.deepEqual(structuredError(new APIError("Missing", 404)), {+ code: "resource_not_found",+ message: "Missing",+ hint: "Check the bound project and resource identifier, then retry.",+ details: { status: 404 },+ });+});diff --git a/cli/src/errors.ts b/cli/src/errors.tsnew file mode 100644index 00000000..18dbcc88--- /dev/null+++ b/cli/src/errors.ts@@ -0,0 +1,84 @@+import { APIError } from "./api.js";++export interface StructuredCLIError {+ code: string;+ message: string;+ hint: string;+ details?: unknown;+}++export class CLIError extends Error {+ constructor(+ readonly code: string,+ message: string,+ readonly hint: string,+ readonly details?: unknown,+ ) {+ super(message);+ }+}++export function structuredError(error: unknown): StructuredCLIError {+ if (error instanceof CLIError) {+ return {+ code: error.code,+ message: error.message,+ hint: error.hint,+ ...(error.details === undefined ? {} : { details: error.details }),+ };+ }+ const message = error instanceof Error ? error.message : String(error);+ if (error instanceof APIError) {+ const code =+ error.status === 401 || error.status === 403+ ? "authentication_required"+ : error.status === 404+ ? "resource_not_found"+ : error.status === 409+ ? "conflict"+ : "api_request_failed";+ const hint =+ code === "authentication_required"+ ? "Run `opencomputer login` or set OPENCOMPUTER_API_KEY."+ : code === "resource_not_found"+ ? "Check the bound project and resource identifier, then retry."+ : code === "conflict"+ ? "Read the existing resource and retry with the same idempotency key."+ : "Retry the command; if it persists, inspect `opencomputer logs --json`.";+ return { code, message, hint, details: { status: error.status } };+ }+ if (/not logged in/i.test(message)) {+ return {+ code: "authentication_required",+ message,+ hint: "Run `opencomputer login` or set OPENCOMPUTER_API_KEY.",+ };+ }+ if (/not connected to a cloud project|opencomputer link/i.test(message)) {+ return {+ code: "binding_required",+ message,+ hint:+ "Run `opencomputer link --project <id|slug>` or `opencomputer link --create-project <name>`.",+ };+ }+ if (/not inside an OpenComputer app|No OpenComputer project found/i.test(message)) {+ return {+ code: "project_not_found",+ message,+ hint: "Run the command inside a project, or create one with `opencomputer init <directory>`.",+ };+ }+ if (/unexpected argument|unknown command|requires a value|usage:|must be|choose either/i.test(message)) {+ return {+ code: "invalid_arguments",+ message,+ hint: "Run `opencomputer --help` and pass explicit non-interactive arguments.",+ };+ }+ return {+ code: "command_failed",+ message,+ hint: "Check the command inputs and local project state, then retry.",+ };+}diff --git a/cli/src/index.ts b/cli/src/index.tsindex 3dd77669..545079ee 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -3,6 +3,7 @@import { readFileSync } from "node:fs";import { runCommand, type GlobalOptions } from "./commands.js";+import { structuredError } from "./errors.js";const VERSION = String((@@ -48,7 +49,8 @@ Usage:opencomputer whoamiopencomputer agentsopencomputer init <directory|.>- opencomputer link+ opencomputer link (--project <id|slug> | --create-project <name>)+ opencomputer doctoropencomputer deploy --watch [--project <id|slug> | --create-project <name>]opencomputer dev [--project <id|slug> | --create-project <name>] (legacy alias)opencomputer session [prompt] [--agent <project-agent>] [--keep]@@ -58,10 +60,10 @@ Usage:opencomputer session attach <session-id>opencomputer session send <session-id> <prompt> [--keep]opencomputer session end <session-id>- opencomputer secrets set <name> [--environment development|production] [--agent <agent>|current]+ opencomputer secrets set <name> --value-stdin [--environment development|production] [--agent <agent>|current]opencomputer secrets list [--environment development|production] [--agent <agent>|current]opencomputer secrets remove <name> [--environment development|production] [--agent <agent>|current]- opencomputer env set <name> [--environment development|production] [--agent <agent>|current]+ opencomputer env set <name> --value-stdin [--environment development|production] [--agent <agent>|current]opencomputer env list [--environment development|production] [--agent <agent>|current]opencomputer env remove <name> [--environment development|production] [--agent <agent>|current]opencomputer model-access connect codex [--project <id|slug>]@@ -74,6 +76,8 @@ Usage:opencomputer webhooks rotate-token <webhook-id> [--project <id|slug>]opencomputer webhooks remove <webhook-id> [--project <id|slug>]opencomputer logs [--agent <agent>] [--session <session-id>] [--environment development|production] [--follow]+ opencomputer channels status [--agent <agent>] [--environment development|production]+ opencomputer sessions tail <session-id> [--after <cursor>] [--no-follow]opencomputer deploy [--alias development|production] [--watch]opencomputer run <agent> <prompt> [--keep]@@ -81,6 +85,7 @@ Global options:--api-url <url> OpenComputer API (default: https://app.opencomputer.dev)--api-key <key> API key (or OPENCOMPUTER_API_KEY)--json Print machine-readable output+ --idempotency-key <key> Stable retry key for mutating commands--verbose Print session events--help Show this help--version Show the CLI version@@ -102,6 +107,7 @@ async function main(): Promise<void> {apiKey: takeOption(args, "--api-key"),json: takeFlag(args, "--json"),verbose: takeFlag(args, "--verbose"),+ idempotencyKey: takeOption(args, "--idempotency-key"),};const command = args.shift();if (!command) {@@ -112,8 +118,11 @@ async function main(): Promise<void> {}main().catch((error: unknown) => {- process.stderr.write(- `opencomputer: ${error instanceof Error ? error.message : String(error)}\n`,- );+ const failure = structuredError(error);+ if (process.argv.includes("--json")) {+ process.stderr.write(`${JSON.stringify({ error: failure })}\n`);+ } else {+ process.stderr.write(`opencomputer: ${failure.message}\nfix: ${failure.hint}\n`);+ }process.exitCode = 1;});diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex 1c218f75..e3b474c3 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -60,7 +60,7 @@ test("init creates a multi-agent-ready hello-world agent by default", async () =assert.equal(packageJSON.devDependencies["@types/node"], undefined);assert.match(await readFile(resolve(root, "README.md"), "utf8"),- /Deploy agent changes to Development \(Cloud\)[\s\S]*npm run deploy -- --watch[\s\S]*opencomputer\/\.env\.local/,+ /Deploy agent changes to Development \(Cloud\)[\s\S]*npm run deploy -- --watch[\s\S]*opencomputer\/\.env\.example[\s\S]*--value-stdin/,);assert.match(await readFile(resolve(root, "opencomputer", ".env.example"), "utf8"),diff --git a/cli/src/project.ts b/cli/src/project.tsindex 894c9a6e..473fb1f3 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -685,12 +685,12 @@ Start the web app separately:npm run dev:web\`\`\`-The first run asks you to create a cloud project or select an existing one.-That choice is saved for later watched deployments.+Link once with \`opencomputer link --project <id|slug>\` or+\`opencomputer link --create-project <name>\`. Later commands reuse that binding.-Development secrets can be placed in \`opencomputer/.env.local\`. Only values-referenced by \`useSecret()\` are synchronized, and their allowed origins are-inferred from \`defineConnection()\` declarations.+Declare required names in \`opencomputer/.env.example\` and set values with+\`opencomputer secrets set <name> --value-stdin\`. Allowed origins are inferred+from \`defineConnection()\` declarations.`: `# Hello World OpenComputer agent@@ -702,12 +702,12 @@ Deploy agent changes to Development (Cloud):npm run deploy -- --watch\`\`\`-The first run asks you to create a cloud project or select an existing one.-That choice is saved for later watched deployments.+Link once with \`opencomputer link --project <id|slug>\` or+\`opencomputer link --create-project <name>\`. Later commands reuse that binding.-Development secrets can be placed in \`opencomputer/.env.local\`. Only values-referenced by \`useSecret()\` are synchronized, and their allowed origins are-inferred from \`defineConnection()\` declarations.+Declare required names in \`opencomputer/.env.example\` and set values with+\`opencomputer secrets set <name> --value-stdin\`. Allowed origins are inferred+from \`defineConnection()\` declarations.`,);diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex ad63acb7..7e8cca50 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -631,6 +631,17 @@ describe("managed agents proxy", () => {botUserId: "bot_private",verifiedAt: "2026-07-31T00:30:00.000Z",verificationError: null,+ lastEventAt: "2026-07-31T00:45:00.000Z",+ lastDelivery: {+ status: "delivered",+ at: "2026-07-31T00:46:00.000Z",+ responseBody: "private",+ },+ lastError: {+ category: "turn_delivery_failed",+ at: "2026-07-31T00:40:00.000Z",+ message: "private",+ },status: "connected",createdAt: "2026-07-31T00:00:00.000Z",updatedAt: "2026-07-31T01:00:00.000Z",@@ -689,6 +700,15 @@ describe("managed agents proxy", () => {teamName: "OpenComputer",verifiedAt: "2026-07-31T00:30:00.000Z",verificationError: null,+ lastEventAt: "2026-07-31T00:45:00.000Z",+ lastDelivery: {+ status: "delivered",+ at: "2026-07-31T00:46:00.000Z",+ },+ lastError: {+ category: "turn_delivery_failed",+ at: "2026-07-31T00:40:00.000Z",+ },status: "connected",createdAt: "2026-07-31T00:00:00.000Z",updatedAt: "2026-07-31T01:00:00.000Z",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex d8ad482c..e0652274 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -312,6 +312,20 @@ function publicModelAccessBinding(value: unknown): Record<string, unknown> {function publicChannel(value: unknown): Record<string, unknown> {const channel = record(value) ?? {};+ const lastDelivery = record(channel.lastDelivery);+ const lastError = record(channel.lastError);+ const publicLastDelivery =+ lastDelivery &&+ (lastDelivery.status === "delivered" || lastDelivery.status === "failed") &&+ typeof lastDelivery.at === "string"+ ? { status: lastDelivery.status, at: lastDelivery.at }+ : undefined;+ const publicLastError =+ lastError &&+ typeof lastError.category === "string" &&+ typeof lastError.at === "string"+ ? { category: lastError.category, at: lastError.at }+ : undefined;return {id: channel.id,channel: "slack",@@ -323,6 +337,11 @@ function publicChannel(value: unknown): Record<string, unknown> {teamName: channel.teamName,verifiedAt: channel.verifiedAt,verificationError: channel.verificationError,+ ...(typeof channel.lastEventAt === "string"+ ? { lastEventAt: channel.lastEventAt }+ : {}),+ ...(publicLastDelivery ? { lastDelivery: publicLastDelivery } : {}),+ ...(publicLastError ? { lastError: publicLastError } : {}),status: channel.status,createdAt: channel.createdAt,updatedAt: channel.updatedAt,diff --git a/docs/agents/channels.mdx b/docs/agents/channels.mdxindex b32b16ed..f6ece772 100644--- a/docs/agents/channels.mdx+++ b/docs/agents/channels.mdx@@ -90,6 +90,16 @@ member of the selected conversation. OpenComputer does not requestAdding a scope in code changes the generated manifest. Update and reinstallthe Slack app so its granted scopes satisfy the current deployment.+Inspect delivery health without opening the dashboard:++```bash+opencomputer channels status --environment development --json+```++The result reports the last accepted provider event, the latest outbound+delivery status, and the latest redacted error category. It never includes+message content, provider responses, tokens, or signing secrets.+## Environment isolationDevelopment and Production never share Slack credentials, destinationdiff --git a/docs/agents/deployments.mdx b/docs/agents/deployments.mdxindex 0a9ebe22..e1e11fb6 100644--- a/docs/agents/deployments.mdx+++ b/docs/agents/deployments.mdx@@ -24,6 +24,11 @@ From the project directory:npm run deploy -- --alias production```+Every deploy first runs `opencomputer doctor`, a local static scan for invalid+connection origins, misplaced tools, inconsistent channel declarations, and+missing secret declarations. Run `opencomputer doctor --json` directly to get+structured diagnostics before invoking a deployment agent.+The CLI builds the current source, creates an immutable deployment, and movesthe `production` alias to it. Development remains available for further work.diff --git a/docs/agents/examples/test-coverage.mdx b/docs/agents/examples/test-coverage.mdxindex f06225c2..71bed9a7 100644--- a/docs/agents/examples/test-coverage.mdx+++ b/docs/agents/examples/test-coverage.mdx@@ -82,10 +82,10 @@ repository files cannot redirect the publishing tool to another repository.Create a short-lived, fine-grained GitHub token restricted to the fixturerepository with **Contents: read and write** and **Pull requests: read and-write**. Store it as a Development secret through the hidden prompt:+write**. Pipe it into the stdin-only Development secret command:```bash-npm run opencomputer -- secrets set GITHUB_PAT \+printf %s "$GITHUB_PAT" | npm run opencomputer -- secrets set GITHUB_PAT --value-stdin \--environment development \--agent current```diff --git a/docs/agents/projects.mdx b/docs/agents/projects.mdxindex eed9fd35..69c40abc 100644--- a/docs/agents/projects.mdx+++ b/docs/agents/projects.mdx@@ -44,22 +44,24 @@ The source scaffold and cloud project are separate. `opencomputer init` writeslocal source. Link it to a cloud project with:```bash-npx --package @opencomputer/cli opencomputer link+npx --package @opencomputer/cli opencomputer link --project <project-id-or-slug>+# Or create one explicitly:+npx --package @opencomputer/cli opencomputer link --create-project "Support agents"```-The command asks whether to create a project or select an existing one. If you-skip it, the first project-scoped command shows the same prompt.+There is no project picker. If you skip linking, project-scoped commands return+a structured `binding_required` error with the explicit command to run.-For non-interactive use:+You can also link as part of a watched deploy:```bashnpx --package @opencomputer/cli opencomputer deploy --watch --project <project-id-or-slug>npx --package @opencomputer/cli opencomputer deploy --watch --create-project "Support agents"```-Later commands reuse `.opencomputer/project.json`. Run `opencomputer link`-again when you intentionally want this source directory to target another-project.+Later commands reuse `.opencomputer/project.json`. Run `opencomputer link` with+an explicit selector again when you intentionally want this source directory+to target another project.## Add another agentdiff --git a/docs/agents/secrets.mdx b/docs/agents/secrets.mdxindex 41db1751..0b05d5cd 100644--- a/docs/agents/secrets.mdx+++ b/docs/agents/secrets.mdx@@ -50,11 +50,9 @@ Place development-only values in `opencomputer/.env.local`:GITHUB_TOKEN=github_pat_...```-When `npm run deploy -- --watch` starts, the CLI considers only names referenced by-`useSecret()` in a `defineConnection()` declaration. It infers the allowed-origins from those declarations and asks before uploading each newly discovered-secret. Changed values are synchronized while the development process is-running.+`opencomputer doctor` compares these local names with `useSecret()` references+and `.env.example`. Upload is always explicit; deployment never opens a value+prompt. The CLI infers the allowed origins from the source declaration.Variables without a matching declaration are skipped. OpenComputer nevergrants an unmatched value access to every host, and removing a local variable@@ -64,30 +62,29 @@ is intentional. The starter ignores `opencomputer/.env.local` and includes an## Set a project secret-Secrets belong to a cloud project. If the app is not linked yet, this command-first asks you to select or create one, then continues setting the secret.+Secrets belong to a cloud project. Link explicitly first with+`opencomputer link --project <id|slug>` or `--create-project <name>`.```bash-npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN+printf %s "$GITHUB_TOKEN" | npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --value-stdin```-The CLI reads the value from a hidden prompt. When run from an initialized-project it can infer allowed origins from connections that reference the-secret. For CI, provide the value through standard input rather than a command-argument.+The CLI accepts the value only from piped standard input. When run from an+initialized project it infers allowed origins from connections that reference+the secret.Project secrets are available to declared connections in every agent in theproject. Create an agent-specific override when one agent needs a differentcredential:```bash-npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --agent current+printf %s "$GITHUB_TOKEN" | npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --value-stdin --agent current```Secrets are separate for `development` and `production`:```bash-npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --environment production+printf %s "$GITHUB_TOKEN" | npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --value-stdin --environment productionnpx --package @opencomputer/cli opencomputer secrets list --environment developmentnpx --package @opencomputer/cli opencomputer secrets remove GITHUB_TOKEN --environment development```@@ -102,12 +99,12 @@ normal environment variable. Configure it in the **Agent runtime variables**section of the project's Secrets page, or with the CLI:```bash-npx --package @opencomputer/cli opencomputer env set DATABASE_URL+printf %s "$DATABASE_URL" | npx --package @opencomputer/cli opencomputer env set DATABASE_URL --value-stdinnpx --package @opencomputer/cli opencomputer env list --environment developmentnpx --package @opencomputer/cli opencomputer env remove DATABASE_URL```-The CLI reads new values from a hidden prompt. Runtime variables can apply to+The CLI reads new values only from piped standard input. Runtime variables can apply tothe whole project or override one agent with `--agent current`, and developmentand production values are separate. No declaration in agent source is needed.diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex 513d95c8..539a1d20 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -56,6 +56,14 @@ npm run session -- send <session-id> "Continue"npm run session -- end <session-id>```+Follow the durable event log directly. With `--json`, each event is one NDJSON+record suitable for a coding agent or log processor:++```bash+opencomputer sessions tail <session-id> --after 0 --json+opencomputer sessions tail <session-id> --after 42 --no-follow --json+```+Project scripts resolve the `opencomputer` binary from the installed`@opencomputer/cli` package. For a one-off invocation outside those scripts,select the scoped package explicitly: