An open-source, faster Devin alternative
TypeScript
fix: route CLI sessions to Development (#638)
Mohamed Habibbe113c0339dc
diff --git a/README.md b/README.mdindex d257a123..576d2c49 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@ contains one or more agents plus the React app used to interact with them.npm create @opencomputer/start@latest my-agentcd my-agentnpm install-npx opencomputer login+npx --package @opencomputer/cli opencomputer login```Sync agent code to Development (Cloud) in one terminal:diff --git a/cli/README.md b/cli/README.mdindex 8c11d0ad..8cbdc05c 100644--- a/cli/README.md+++ b/cli/README.md@@ -7,8 +7,8 @@ projects with an optional React application.npm create @opencomputer/start@latest my-agentcd my-agentnpm install-npx opencomputer login-npx opencomputer link+npx --package @opencomputer/cli opencomputer login+npx --package @opencomputer/cli opencomputer link```The npm initializer asks whether to include a React SPA, then delegates todiff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 24e87ef3..c31674ee 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.5.1",+ "version": "0.5.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.5.1",+ "version": "0.5.2","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex 65830b91..2108475a 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.5.1",+ "version": "0.5.2","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 4cfb8b26..7d8b8282 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -11,14 +11,18 @@ import {ensureProjectBinding,findOpenComputerProjectRoot,} from "./binding.js";-import { runLocalAgent } from "./local.js";import {assertStarterTarget,buildAgentArtifact,findAgentRoot,initializeAgentProject,- readManifest,} from "./project.js";+import {+ developmentAgentReference,+ parseSessionCommand,+ resolveProjectAgent,+} from "./session-command.js";+import { formatSessionEvent } from "./session-prompt.js";export interface GlobalOptions {apiUrl?: string;@@ -124,6 +128,21 @@ async function selectedProject(return { projectId: binding.projectId, agentId: binding.agentId };}+async function selectedSessionAgent(+ client: OpenComputerClient,+ project: { projectId: string; agentId: string },+ selector?: string,+): Promise<string> {+ if (!selector) return project.agentId;+ const current = (await client.projects()).find(+ (candidate) => candidate.id === project.projectId,+ );+ if (!current) {+ throw new Error("The bound project is no longer available.");+ }+ return resolveProjectAgent(current.agents, selector);+}+function printLog(entry: ManagedAgentLog, json: boolean): void {if (json) {process.stdout.write(`${JSON.stringify(entry)}\n`);@@ -152,13 +171,6 @@ async function requireAgentRoot(): Promise<string> {return root;}-async function inferAgentReference(alias: string): Promise<string | undefined> {- const root = await findAgentRoot();- if (!root) return undefined;- const manifest = await readManifest(root);- return `${manifest.id}@${alias}`;-}-function printSession(session: ManagedSessionSnapshot): void {const deployment = session.deploymentId? session.deploymentId.slice(session.deploymentId.lastIndexOf(":") + 1)@@ -193,6 +205,20 @@ function printToolProgress(event: ManagedAgentEvent): void {);}+function printSessionProgress(+ event: ManagedAgentEvent,+ json: boolean,+ verbose: boolean,+): void {+ if (json) return;+ if (verbose) {+ const formatted = formatSessionEvent(event);+ if (formatted) process.stderr.write(`${formatted}\n`);+ return;+ }+ printToolProgress(event);+}+function printAgentEvent(event: ManagedAgentEvent, json: boolean): void {if (json) {process.stdout.write(`${JSON.stringify(event)}\n`);@@ -345,6 +371,7 @@ async function runAgent(prompt: string,keep: boolean,json: boolean,+ verbose: boolean,): Promise<unknown> {const created = await client.createSession(agent);process.stderr.write(`Starting ${agent}…\n`);@@ -353,7 +380,7 @@ async function runAgent(created.session.id,0,(event) => event.type === "runtime.connected",- () => undefined,+ (event) => printSessionProgress(event, json, verbose),90_000,);const turn = await client.createTurn(created.session.id, prompt);@@ -377,7 +404,7 @@ async function runAgent() {completedText = event.data.text;} else {- if (!json) printToolProgress(event);+ printSessionProgress(event, json, verbose);}},180_000,@@ -564,7 +591,14 @@ export async function runCommand(if (!agent || !prompt) {throw new Error("Usage: opencomputer run <agent> <prompt>");}- const result = await runAgent(client, agent, prompt, keep, globals.json);+ const result = await runAgent(+ client,+ agent,+ prompt,+ keep,+ globals.json,+ globals.verbose === true,+ );if (globals.json) printJSON(result);return;}@@ -740,56 +774,39 @@ export async function runCommand(}if (command === "session") {- const local = flag(args, "--local");- const remote = flag(args, "--remote");- const keep = flag(args, "--keep");- const agentOption = option(args, "--agent");- const alias = option(args, "--alias") ?? "production";- if (local && (remote || agentOption)) {- throw new Error("--local cannot be combined with --remote or --agent.");- }- const knownActions = new Set([- "create",- "list",- "inspect",- "attach",- "send",- "end",- ]);- const shorthand = args[0];- const action =- shorthand && knownActions.has(shorthand) ? args.shift()! : "create";- const useRemote = remote || Boolean(agentOption) || action !== "create";- if (!useRemote) {- const prompt = args.join(" ").trim();- await runLocalAgent(prompt ? ["run", prompt] : ["shell"], config, {- verbose: globals.verbose,- });- return;- }- if (action === "list") {- if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const session = parseSessionCommand(args);+ const sessionArgs = session.args;+ if (session.action === "list") {+ if (sessionArgs.length)+ throw new Error(`Unexpected argument: ${sessionArgs[0]}`);const sessions = await client.sessions();if (globals.json) printJSON(sessions);else if (!sessions.length) process.stdout.write("No sessions.\n");else sessions.forEach(printSession);return;}- if (action === "create") {- const prompt = args.join(" ").trim();- const agent = agentOption ?? (await inferAgentReference(alias));- if (!agent) {- throw new Error(- "No agent repository found. Pass --agent <agent>@<alias>.",- );- }+ if (session.action === "create") {+ const prompt = sessionArgs.join(" ").trim();+ const project = await selectedProject(+ client,+ config,+ undefined,+ !globals.json,+ );+ const agentId = await selectedSessionAgent(+ client,+ project,+ session.agent,+ );+ const agent = developmentAgentReference(agentId);if (prompt) {const result = await runAgent(client,agent,prompt,- keep,+ session.keep,globals.json,+ globals.verbose === true,);if (globals.json) printJSON(result);return;@@ -803,14 +820,14 @@ export async function runCommand(() => undefined,90_000,);- if (!keep) {+ if (!session.keep) {await client.suspendSession(created.session.id).catch(() => undefined);}const result = {sessionId: created.session.id,agentId: created.deployment?.agentId ?? agent,deploymentId: created.deployment?.id,- status: keep ? "running" : "suspended",+ status: session.keep ? "running" : "suspended",cursor: connected.cursor,};if (globals.json) printJSON(result);@@ -824,26 +841,28 @@ export async function runCommand(}return;}- const sessionId = args.shift();+ const sessionId = sessionArgs.shift();if (!sessionId) throw new Error("A session ID is required.");- if (action === "inspect") {- if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ if (session.action === "inspect") {+ if (sessionArgs.length)+ throw new Error(`Unexpected argument: ${sessionArgs[0]}`);printJSON(await client.session(sessionId));return;}- if (action === "attach") {- if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ if (session.action === "attach") {+ if (sessionArgs.length)+ throw new Error(`Unexpected argument: ${sessionArgs[0]}`);await attachSession(client, sessionId, globals.json);return;}- if (action === "send") {- const prompt = args.join(" ").trim();+ if (session.action === "send") {+ const prompt = sessionArgs.join(" ").trim();if (!prompt) throw new Error("A prompt is required.");const result = await sendAgentTurn(client,sessionId,prompt,- keep,+ session.keep,globals.json,);if (globals.json) {@@ -851,8 +870,9 @@ export async function runCommand(}return;}- if (action === "end") {- if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ if (session.action === "end") {+ if (sessionArgs.length)+ throw new Error(`Unexpected argument: ${sessionArgs[0]}`);await client.terminateSession(sessionId).catch(() => undefined);const ended = await client.endSession(sessionId);if (globals.json) printJSON(ended);diff --git a/cli/src/index.ts b/cli/src/index.tsindex 533604d4..80b15d55 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -50,9 +50,8 @@ Usage:opencomputer init <directory|.> [--spa|--agent-only]opencomputer linkopencomputer dev [--project <id|slug> | --create-project <name>]- opencomputer session [prompt]- opencomputer session create <prompt> [--local]- opencomputer session create [prompt] --remote [--agent <agent>@<alias>] [--keep]+ opencomputer session [prompt] [--agent <project-agent>] [--keep]+ opencomputer session create [prompt] [--agent <project-agent>] [--keep]opencomputer session listopencomputer session inspect <session-id>opencomputer session attach <session-id>diff --git a/cli/src/session-command.test.ts b/cli/src/session-command.test.tsnew file mode 100644index 00000000..64097818--- /dev/null+++ b/cli/src/session-command.test.ts@@ -0,0 +1,81 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ developmentAgentReference,+ parseSessionCommand,+ resolveProjectAgent,+} from "./session-command.js";++test("sessions target the bound agent's Development deployment", () => {+ assert.equal(+ developmentAgentReference("unleash-mcp-test"),+ "unleash-mcp-test@development",+ );+});++test("session shorthand targets the normal create flow", () => {+ assert.deepEqual(parseSessionCommand(["Review", "this", "repository"]), {+ action: "create",+ args: ["Review", "this", "repository"],+ keep: false,+ });+});++test("session create retains lifecycle options", () => {+ assert.deepEqual(parseSessionCommand(["create", "Hello", "--keep"]), {+ action: "create",+ args: ["Hello"],+ keep: true,+ });+});++test("session accepts a project agent selector", () => {+ assert.deepEqual(parseSessionCommand(["Hello", "--agent", "reviewer"]), {+ action: "create",+ args: ["Hello"],+ keep: false,+ agent: "reviewer",+ });+ assert.deepEqual(parseSessionCommand(["--agent=reviewer", "Hello"]), {+ action: "create",+ args: ["Hello"],+ keep: false,+ agent: "reviewer",+ });+});++test("session resolves an agent only within the current project", () => {+ const agents = [+ { id: "triage", name: "Triage" },+ { id: "reviewer", name: "Reviewer" },+ ];+ assert.equal(resolveProjectAgent(agents, "reviewer"), "reviewer");+ assert.equal(resolveProjectAgent(agents, "Triage"), "triage");+ assert.throws(+ () => resolveProjectAgent(agents, "external"),+ /Available agents: triage, reviewer/,+ );+ assert.throws(+ () => resolveProjectAgent(agents, "reviewer@production"),+ /environment aliases are not supported/,+ );+});++for (const option of ["--local", "--remote", "--alias"]) {+ test(`session rejects deprecated routing option ${option}`, () => {+ assert.throws(+ () => parseSessionCommand(["Hello", option, "value"]),+ new RegExp(+ `${option} is no longer supported; sessions use the current project's Development deployment`,+ ),+ );+ });+}++test("session rejects equals-form deprecated routing options", () => {+ assert.throws(+ () => parseSessionCommand(["Hello", "--alias=production"]),+ /--alias is no longer supported/,+ );+});diff --git a/cli/src/session-command.ts b/cli/src/session-command.tsnew file mode 100644index 00000000..50798d7c--- /dev/null+++ b/cli/src/session-command.ts@@ -0,0 +1,102 @@+export type SessionAction =+ | "create"+ | "list"+ | "inspect"+ | "attach"+ | "send"+ | "end";++export type SessionCommand = {+ action: SessionAction;+ args: string[];+ keep: boolean;+ agent?: string;+};++export function developmentAgentReference(agentId: string): string {+ return `${agentId}@development`;+}++export function resolveProjectAgent(+ agents: Array<{ id: string; name: string }>,+ selector: string,+): string {+ if (selector.includes("@")) {+ throw new Error(+ "--agent selects a project agent only; session environment aliases are not supported.",+ );+ }+ const exactId = agents.find((agent) => agent.id === selector);+ if (exactId) return exactId.id;+ const named = agents.filter((agent) => agent.name === selector);+ if (named.length === 1) return named[0]!.id;+ const available = agents.map((agent) => agent.id).join(", ") || "none";+ throw new Error(+ `Agent ${selector} is not unique in the current project. Available agents: ${available}.`,+ );+}++const ACTIONS = new Set<SessionAction>([+ "create",+ "list",+ "inspect",+ "attach",+ "send",+ "end",+]);++const DEPRECATED_ROUTING_OPTIONS = [+ "--local",+ "--remote",+ "--alias",+] as const;++function takeAgentOption(args: string[]): string | undefined {+ const equalsIndex = args.findIndex((argument) =>+ argument.startsWith("--agent="),+ );+ if (equalsIndex >= 0) {+ const value = args[equalsIndex]!.slice("--agent=".length);+ if (!value) throw new Error("--agent requires a value");+ args.splice(equalsIndex, 1);+ return value;+ }+ const index = args.indexOf("--agent");+ if (index < 0) return undefined;+ const value = args[index + 1];+ if (!value || value.startsWith("--")) {+ throw new Error("--agent requires a value");+ }+ args.splice(index, 2);+ return value;+}++export function parseSessionCommand(rawArgs: string[]): SessionCommand {+ const deprecated = rawArgs.find((argument) =>+ DEPRECATED_ROUTING_OPTIONS.some(+ (option) => argument === option || argument.startsWith(`${option}=`),+ ),+ );+ if (deprecated) {+ throw new Error(+ `${deprecated.split("=")[0]} is no longer supported; ` ++ "sessions use the current project's Development deployment.",+ );+ }++ const args = [...rawArgs];+ const agent = takeAgentOption(args);+ const keepIndex = args.indexOf("--keep");+ const keep = keepIndex >= 0;+ if (keep) args.splice(keepIndex, 1);++ const shorthand = args[0] as SessionAction | undefined;+ const action =+ shorthand && ACTIONS.has(shorthand)+ ? (args.shift()! as SessionAction)+ : "create";+ if (agent && action !== "create") {+ throw new Error("--agent is only supported when creating a session.");+ }+ return { action, args, keep, ...(agent ? { agent } : {}) };+}diff --git a/create-start/README.md b/create-start/README.mdindex 7bb05d2f..46e953f0 100644--- a/create-start/README.md+++ b/create-start/README.md@@ -6,7 +6,7 @@ Create a hello-world OpenComputer application:npm create @opencomputer/start@latest my-agentcd my-agentnpm install-npx opencomputer login+npx --package @opencomputer/cli opencomputer loginnpm run dev```diff --git a/create-start/package.json b/create-start/package.jsonindex 5cb39234..be923e45 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.5.1",+ "version": "0.5.2","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "0.5.1"+ "@opencomputer/cli": "0.5.2"},"publishConfig": {"access": "public"diff --git a/docs/agents/development.mdx b/docs/agents/development.mdxindex 03537076..d2932e54 100644--- a/docs/agents/development.mdx+++ b/docs/agents/development.mdx@@ -26,14 +26,14 @@ On the first run, select an existing project or create one. The choice is savedlocally and reused by later commands.```bash-npx opencomputer link+npx --package @opencomputer/cli opencomputer link```Use an explicit project in scripts or other non-interactive environments:```bash-npx opencomputer dev --project <project-id-or-slug>-npx opencomputer dev --create-project "Support agents"+npx --package @opencomputer/cli opencomputer dev --project <project-id-or-slug>+npx --package @opencomputer/cli opencomputer dev --create-project "Support agents"```## Work with the React applicationdiff --git a/docs/agents/logs.mdx b/docs/agents/logs.mdxindex c8e0a269..477aa3dc 100644--- a/docs/agents/logs.mdx+++ b/docs/agents/logs.mdx@@ -12,28 +12,28 @@ inspect failures from the project or CLI.From an initialized project:```bash-npx opencomputer logs+npx --package @opencomputer/cli opencomputer logs```The CLI uses the local project binding and current agent automatically. Follownew entries while developing:```bash-npx opencomputer logs --follow+npx --package @opencomputer/cli opencomputer logs --follow```## Filter logs```bash-npx opencomputer logs --agent hello-world --environment development-npx opencomputer logs --session <session-id>-npx opencomputer logs --limit 200+npx --package @opencomputer/cli opencomputer logs --agent hello-world --environment development+npx --package @opencomputer/cli opencomputer logs --session <session-id>+npx --package @opencomputer/cli opencomputer logs --limit 200```Use JSON Lines for scripts and log processors:```bash-npx opencomputer logs --follow --json+npx --package @opencomputer/cli opencomputer logs --follow --json```Each entry includes a stable cursor, timestamp, level, source, message, anddiff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdxindex 145bd143..78a2c469 100644--- a/docs/agents/overview.mdx+++ b/docs/agents/overview.mdx@@ -56,7 +56,7 @@ subagents needed for that render.npm create @opencomputer/start@latest my-agentcd my-agentnpm install-npx opencomputer login+npx --package @opencomputer/cli opencomputer loginnpm run dev```diff --git a/docs/agents/playground.mdx b/docs/agents/playground.mdxindex ea33be43..f47a76f5 100644--- a/docs/agents/playground.mdx+++ b/docs/agents/playground.mdx@@ -35,8 +35,8 @@ internal execution implementation.Use the CLI when a failure needs more detail:```bash-npx opencomputer logs --follow-npx opencomputer logs --session <session-id>+npx --package @opencomputer/cli opencomputer logs --follow+npx --package @opencomputer/cli opencomputer logs --session <session-id>```See [Logs](/agents/logs) for filters and JSON output.diff --git a/docs/agents/projects.mdx b/docs/agents/projects.mdxindex 3573c371..b8c83a2e 100644--- a/docs/agents/projects.mdx+++ b/docs/agents/projects.mdx@@ -43,7 +43,7 @@ The source scaffold and cloud project are separate. `npm create` writes localsource. Link it to a cloud project with:```bash-npx opencomputer link+npx --package @opencomputer/cli opencomputer link```The command asks whether to create a project or select an existing one. If you@@ -52,8 +52,8 @@ skip it, the first project-scoped command shows the same prompt.For non-interactive use:```bash-npx opencomputer dev --project <project-id-or-slug>-npx opencomputer dev --create-project "Support agents"+npx --package @opencomputer/cli opencomputer dev --project <project-id-or-slug>+npx --package @opencomputer/cli opencomputer dev --create-project "Support agents"```Later commands reuse `.opencomputer/project.json`. Run `opencomputer link`diff --git a/docs/agents/quickstart.mdx b/docs/agents/quickstart.mdxindex 8a53bfeb..a6e8bc95 100644--- a/docs/agents/quickstart.mdx+++ b/docs/agents/quickstart.mdx@@ -22,7 +22,7 @@ The initializer asks whether to create agent code only or include a React SPA.## 2. Log in```bash-npx opencomputer login+npx --package @opencomputer/cli opencomputer login```The CLI opens the OpenComputer device-login flow and stores the login locally.diff --git a/docs/agents/secrets.mdx b/docs/agents/secrets.mdxindex a263c6a6..fecbb2fa 100644--- a/docs/agents/secrets.mdx+++ b/docs/agents/secrets.mdx@@ -72,7 +72,7 @@ Secrets belong to a cloud project. If the app is not linked yet, this commandfirst asks you to select or create one, then continues setting the secret.```bash-npx opencomputer secrets set GITHUB_TOKEN+npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN```The CLI reads the value from a hidden prompt. When run from an initialized@@ -85,15 +85,15 @@ project. Create an agent-specific override when one agent needs a differentcredential:```bash-npx opencomputer secrets set GITHUB_TOKEN --agent current+npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --agent current```Secrets are separate for `development` and `production`:```bash-npx opencomputer secrets set GITHUB_TOKEN --environment production-npx opencomputer secrets list --environment development-npx opencomputer secrets remove GITHUB_TOKEN --environment development+npx --package @opencomputer/cli opencomputer secrets set GITHUB_TOKEN --environment production+npx --package @opencomputer/cli opencomputer secrets list --environment development+npx --package @opencomputer/cli opencomputer secrets remove GITHUB_TOKEN --environment development```List output contains metadata such as the name, scope, environment, anddiff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdxindex fbeb62ba..8ef0f401 100644--- a/docs/agents/sessions.mdx+++ b/docs/agents/sessions.mdx@@ -35,22 +35,46 @@ debug inspector.## CLI-Start an interactive session against the development agent:+Start a session against the development agent:```bashnpm run session```-Or manage remote sessions explicitly:+The session command always uses the current project's bound Development+deployment. It does not select between local and remote runtimes.++Projects with multiple agents may select another member of the bound project.+The environment remains Development:++```bash+npm run session -- --agent reviewer "Review this change"+```++Add `--verbose` to stream non-message lifecycle, runtime, tool, egress, usage,+and turn events. Assistant message text continues to stream normally:++```bash+npm run session -- --verbose --agent reviewer "Review this change"+```++Or manage the durable session lifecycle explicitly:++```bash+npm run session -- create "Draft a response"+npm run session -- list+npm run session -- inspect <session-id>+npm run session -- attach <session-id>+npm run session -- send <session-id> "Continue"+npm run session -- end <session-id>+```++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:```bash-npx opencomputer session create "Draft a response" --remote \- --agent hello-world@development-npx opencomputer session list-npx opencomputer session inspect <session-id>-npx opencomputer session attach <session-id>-npx opencomputer session send <session-id> "Continue"-npx opencomputer session end <session-id>+npx --package @opencomputer/cli opencomputer session "Draft a response"```Use `--keep` on supported commands when the session should remain active after