Skip to content

An open-source, faster Devin alternative

TypeScript

cli: session create --memory <resource>=<documentId>[:access] [--create-document]

Igor Zalutski444c2a769215
diff --git a/cli/src/api.ts b/cli/src/api.ts
index 56deb639..d36643c5 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -280,7 +280,19 @@ export interface MemoryDocumentRead {
etag: string;
}
-interface CreateSessionResult {
+/**
+ * A session's memory binding (docs/agents/document-memory.mdx, "Session
+ * bindings"), keyed by resource id in the session create body.
+ */
+export type MemoryBinding =
+ | { scope: "document"; id: string; access?: "read" | "read-write" }
+ | { scope: "collection"; access?: "read" };
+
+export type MemoryBindings = Record<string, MemoryBinding>;
+
+export interface CreateSessionResult {
+ /** 201 created the session; 200 replayed an earlier create under the same Idempotency-Key. */
+ created: boolean;
session: ManagedSessionSnapshot;
deployment?: ManagedAgentDeployment;
}
@@ -974,11 +986,21 @@ export class OpenComputerClient {
);
}
- createSession(agentId: string) {
- return this.request<CreateSessionResult>("/api/managed-agents/sessions", {
+ async createSession(
+ agentId: string,
+ options: { memory?: MemoryBindings } = {},
+ ): Promise<CreateSessionResult> {
+ const response = await this.response("/api/managed-agents/sessions", {
method: "POST",
- body: JSON.stringify({ agentId }),
+ body: JSON.stringify({
+ agentId,
+ ...(options.memory && Object.keys(options.memory).length
+ ? { memory: options.memory }
+ : {}),
+ }),
});
+ const body = (await response.json()) as Omit<CreateSessionResult, "created">;
+ return { created: response.status === 201, ...body };
}
async sessions(): Promise<ManagedSessionSnapshot[]> {
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 981d45b3..cb8d7f73 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -3,6 +3,7 @@ import {
type ManagedAgentEvent,
type ManagedAgentLog,
type ManagedSessionSnapshot,
+ type MemoryBindings,
type MemoryDocument,
type MemoryDocumentMeta,
} from "./api.js";
@@ -49,8 +50,11 @@ import { createInterface } from "node:readline/promises";
import { doctorProject, type DoctorResult } from "./doctor.js";
import { CLIError } from "./errors.js";
import {
+ createSessionWithMemory,
+ ensureMemoryDocuments,
memoryResources,
saveMemoryEdit,
+ type EnsuredMemoryDocument,
type MemoryEditDraft,
type MemoryResourceSummary,
} from "./memory-commands.js";
@@ -613,8 +617,9 @@ async function runAgent(
json: boolean,
verbose: boolean,
idempotencyKey?: string,
+ memory?: MemoryBindings,
): Promise<unknown> {
- const created = await client.createSession(agent);
+ const created = await createSessionWithMemory(client, agent, memory);
process.stderr.write(`Starting ${agent}…\n`);
const connected = await waitForEvent(
client,
@@ -667,11 +672,31 @@ async function runAgent(
turnId: turn.turnId,
agentId: created.deployment?.agentId ?? agent,
deploymentId: created.deployment?.id,
+ ...(memory ? { memory } : {}),
status: "completed",
output: streamedText || completedText || undefined,
};
}
+function printMemoryBindings(
+ memory: MemoryBindings | undefined,
+ documents: EnsuredMemoryDocument[],
+): string {
+ if (!memory) return "";
+ return Object.entries(memory)
+ .map(([resource, binding]) => {
+ if (binding.scope === "collection") {
+ return `Memory: ${resource} (collection, read)\n`;
+ }
+ const ensured = documents.find(
+ (document) => document.resource === resource && document.id === binding.id,
+ );
+ const state = ensured ? (ensured.created ? ", created" : ", existing") : "";
+ return `Memory: ${resource}/${binding.id} (${binding.access ?? "read-write"}${state})\n`;
+ })
+ .join("");
+}
+
export async function runCommand(
command: string,
rawArgs: string[],
@@ -1953,6 +1978,14 @@ export async function runCommand(
session.agent,
);
const agent = developmentAgentReference(agentId);
+ // Sessions from the CLI run on Development, so its memory is bound.
+ const documents = session.createDocuments && session.memory
+ ? await ensureMemoryDocuments(client, {
+ projectId: project.projectId,
+ environment: "development",
+ bindings: session.memory,
+ })
+ : [];
if (prompt) {
const result = await runAgent(
client,
@@ -1962,11 +1995,22 @@ export async function runCommand(
globals.json,
globals.verbose === true,
globals.idempotencyKey,
+ session.memory,
);
- if (globals.json) printJSON(result);
+ if (globals.json) {
+ printJSON(
+ documents.length
+ ? { ...(result as Record<string, unknown>), documents }
+ : result,
+ );
+ }
return;
}
- const created = await client.createSession(agent);
+ const created = await createSessionWithMemory(
+ client,
+ agent,
+ session.memory,
+ );
const connected = await waitForEvent(
client,
created.session.id,
@@ -1980,17 +2024,21 @@ export async function runCommand(
}
const result = {
sessionId: created.session.id,
+ created: created.created,
agentId: created.deployment?.agentId ?? agent,
deploymentId: created.deployment?.id,
+ ...(session.memory ? { memory: session.memory } : {}),
+ ...(documents.length ? { documents } : {}),
status: session.keep ? "running" : "suspended",
cursor: connected.cursor,
};
if (globals.json) printJSON(result);
else {
process.stdout.write(
- `Session: ${result.sessionId}\n` +
+ `Session: ${result.sessionId}${created.created ? "" : " (existing)"}\n` +
`Agent: ${result.agentId}\n` +
`Deployment: ${result.deploymentId ?? "—"}\n` +
+ printMemoryBindings(session.memory, documents) +
`Runtime: ${result.status}\n`,
);
}
diff --git a/cli/src/index.ts b/cli/src/index.ts
index e4296965..83682a7c 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -60,6 +60,10 @@ Usage:
opencomputer dev [--project <id|slug> | --create-project <name>] (legacy alias)
opencomputer session [prompt] [--agent <project-agent>] [--keep]
opencomputer session create [prompt] [--agent <project-agent>] [--keep]
+ [--memory <resource>=<documentId>[:read|read-write] | --memory <resource>]... [--create-document]
+ --memory binds a document (read-write by default) or a collection; --create-document
+ creates each bound document that does not exist yet; with --idempotency-key a retry
+ returns the same session
opencomputer session list
opencomputer session inspect <session-id>
opencomputer session attach <session-id>
diff --git a/cli/src/memory-commands.test.ts b/cli/src/memory-commands.test.ts
index 8dd14276..f8d85a6c 100644
--- a/cli/src/memory-commands.test.ts
+++ b/cli/src/memory-commands.test.ts
@@ -6,7 +6,12 @@ import test from "node:test";
import { OpenComputerClient } from "./api.js";
import { CLIError } from "./errors.js";
-import { memoryResources, saveMemoryEdit } from "./memory-commands.js";
+import {
+ createSessionWithMemory,
+ ensureMemoryDocuments,
+ memoryResources,
+ saveMemoryEdit,
+} from "./memory-commands.js";
const config = { apiUrl: "https://app.opencomputer.dev", apiKey: "test" };
@@ -284,3 +289,90 @@ test("a saved edit discards its draft", async (context) => {
await draft.cleanup();
}
});
+
+test("--create-document creates missing bound documents, keeps existing ones, and refuses deleted ids", async (context) => {
+ const requests: Array<{ method: string; path: string; ifNoneMatch: string | null }> = [];
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const path = route(request);
+ requests.push({ method: request.method, path, ifNoneMatch: request.headers.get("if-none-match") });
+ const document = (id: string, revision: string) =>
+ Response.json({ id, title: id, text: "", summary: "", agentWrites: "enabled", revision, bytes: 0, maxBytes: 8192, updatedAt: "2026-09-10T00:00:00.000Z", writer: { kind: "owner" } }, { status: request.method === "PUT" ? 201 : 200, headers: { etag: `"${revision}"` } });
+ if (path.includes("/documents/fresh?")) return document("fresh", "r1");
+ if (path.includes("/documents/kept?")) {
+ return request.method === "PUT"
+ ? Response.json({ error: { code: "precondition_failed", message: "used" } }, { status: 412 })
+ : document("kept", "r9");
+ }
+ if (path.includes("/documents/gone?")) {
+ return request.method === "PUT"
+ ? Response.json({ error: { code: "precondition_failed", message: "used" } }, { status: 412 })
+ : Response.json({ error: { code: "not_found", message: "deleted" } }, { status: 404 });
+ }
+ throw new Error(`unexpected ${request.method} ${path}`);
+ });
+ const client = new OpenComputerClient(config);
+
+ const ensured = await ensureMemoryDocuments(client, {
+ projectId: "prj_1",
+ environment: "development",
+ bindings: {
+ topics: { scope: "document", id: "fresh", access: "read-write" },
+ profile: { scope: "document", id: "kept", access: "read" },
+ archive: { scope: "collection" },
+ },
+ });
+ assert.deepEqual(ensured, [
+ { resource: "topics", id: "fresh", created: true, revision: "r1" },
+ { resource: "profile", id: "kept", created: false, revision: "r9" },
+ ]);
+ assert.deepEqual(requests.map((request) => `${request.method} ${request.path.split("?")[0]} ${request.ifNoneMatch ?? ""}`.trim()), [
+ "PUT /api/managed-agents/projects/prj_1/memory/topics/documents/fresh *",
+ "PUT /api/managed-agents/projects/prj_1/memory/profile/documents/kept *",
+ "GET /api/managed-agents/projects/prj_1/memory/profile/documents/kept",
+ ]);
+
+ await assert.rejects(
+ ensureMemoryDocuments(client, {
+ projectId: "prj_1",
+ environment: "development",
+ bindings: { topics: { scope: "document", id: "gone" } },
+ }),
+ (error: unknown) => error instanceof CLIError && error.code === "memory_document_deleted" && /reserved/.test(error.message),
+ );
+});
+
+test("session create sends bindings, reports replay, and names a reused key's conflict", async (context) => {
+ const bodies: Array<Record<string, unknown>> = [];
+ let status = 201;
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ assert.equal(route(request), "/api/managed-agents/sessions");
+ bodies.push((await request.json()) as Record<string, unknown>);
+ if (status === 409) {
+ return Response.json({ error: { code: "idempotency_conflict", message: "Idempotency-Key was already used with different session input" } }, { status });
+ }
+ return Response.json({ session: { id: "ses-1", status: "connecting" }, deployment: { id: "muse:dev", agentId: "muse", alias: "development" } }, { status });
+ });
+ const client = new OpenComputerClient(config, "topic/workshop/1");
+ const memory = { topics: { scope: "document" as const, id: "workshop", access: "read-write" as const } };
+
+ const created = await createSessionWithMemory(client, "muse@development", memory);
+ assert.equal(created.created, true);
+ assert.equal(created.session.id, "ses-1");
+ assert.deepEqual(bodies[0], { agentId: "muse@development", memory });
+
+ status = 200;
+ const replayed = await createSessionWithMemory(client, "muse@development", memory);
+ assert.equal(replayed.created, false);
+
+ status = 201;
+ await createSessionWithMemory(client, "muse@development");
+ assert.deepEqual(bodies[2], { agentId: "muse@development" });
+
+ status = 409;
+ await assert.rejects(
+ createSessionWithMemory(client, "muse@development", memory),
+ (error: unknown) => error instanceof CLIError && error.code === "session_idempotency_conflict" && /different agent, deployment, environment or memory bindings/.test(error.message),
+ );
+});
diff --git a/cli/src/memory-commands.ts b/cli/src/memory-commands.ts
index ef6f9d70..4ff35fde 100644
--- a/cli/src/memory-commands.ts
+++ b/cli/src/memory-commands.ts
@@ -1,5 +1,7 @@
import {
APIError,
+ type CreateSessionResult,
+ type MemoryBindings,
type MemoryDocument,
type MemoryEnvironment,
type MemoryResource,
@@ -174,3 +176,87 @@ function writerLabel(document: MemoryDocument): string {
? `agent ${document.writer.sessionId}`
: "owner";
}
+
+/** One bound document after `--create-document`: created now, or already there. */
+export interface EnsuredMemoryDocument {
+ resource: string;
+ id: string;
+ created: boolean;
+ revision: string;
+}
+
+/**
+ * Creates every document a session's bindings name that does not exist yet
+ * (title = its id, empty text), and reports each with whether it was created.
+ * A deleted id is reserved and a binding to it would fail admission, so it
+ * fails here, before any session is created.
+ */
+export async function ensureMemoryDocuments(
+ client: OpenComputerClient,
+ input: {
+ projectId: string;
+ environment: MemoryEnvironment;
+ bindings: MemoryBindings;
+ },
+): Promise<EnsuredMemoryDocument[]> {
+ const ensured: EnsuredMemoryDocument[] = [];
+ for (const [resource, binding] of Object.entries(input.bindings)) {
+ if (binding.scope !== "document") continue;
+ const target = {
+ projectId: input.projectId,
+ resource,
+ id: binding.id,
+ environment: input.environment,
+ };
+ try {
+ const { document } = await client.createMemoryDocument({
+ ...target,
+ title: binding.id,
+ text: "",
+ });
+ ensured.push({ resource, id: binding.id, created: true, revision: document.revision });
+ continue;
+ } catch (error) {
+ if (!(error instanceof APIError && error.status === 412)) throw error;
+ }
+ try {
+ const { document } = await client.memoryDocument(target);
+ ensured.push({ resource, id: binding.id, created: false, revision: document.revision });
+ } catch (error) {
+ if (error instanceof APIError && error.status === 404) {
+ throw new CLIError(
+ "memory_document_deleted",
+ `${resource}/${binding.id} was deleted and its id is reserved; a session cannot bind it.`,
+ "Bind a new document id, or create one with `opencomputer memory create`.",
+ { resource, id: binding.id },
+ );
+ }
+ throw error;
+ }
+ }
+ return ensured;
+}
+
+/**
+ * Creates a session, with bindings when given. A reused `--idempotency-key`
+ * whose earlier session had different inputs is a 409; name the cause.
+ */
+export async function createSessionWithMemory(
+ client: OpenComputerClient,
+ agent: string,
+ memory?: MemoryBindings,
+): Promise<CreateSessionResult> {
+ try {
+ return await client.createSession(agent, memory ? { memory } : {});
+ } catch (error) {
+ if (error instanceof APIError && error.status === 409) {
+ throw new CLIError(
+ "session_idempotency_conflict",
+ "This --idempotency-key already created a session with a different agent, deployment, environment or memory bindings.",
+ "Pass a new --idempotency-key to start another session, or repeat the earlier command unchanged to get the existing one.",
+ { status: 409, ...(memory ? { memory } : {}) },
+ );
+ }
+ throw error;
+ }
+}
diff --git a/cli/src/session-command.test.ts b/cli/src/session-command.test.ts
index 64097818..b7291588 100644
--- a/cli/src/session-command.test.ts
+++ b/cli/src/session-command.test.ts
@@ -3,6 +3,7 @@ import test from "node:test";
import {
developmentAgentReference,
+ parseMemoryBinding,
parseSessionCommand,
resolveProjectAgent,
} from "./session-command.js";
@@ -79,3 +80,44 @@ test("session rejects equals-form deprecated routing options", () => {
/--alias is no longer supported/,
);
});
+
+test("session create binds memory documents and collections", () => {
+ assert.deepEqual(
+ parseSessionCommand([
+ "create",
+ "--memory",
+ "topics=workshop",
+ "--memory=profile=owner:read",
+ "--memory",
+ "archive",
+ "--create-document",
+ "Plan the workshop",
+ ]),
+ {
+ action: "create",
+ args: ["Plan the workshop"],
+ keep: false,
+ memory: {
+ topics: { scope: "document", id: "workshop", access: "read-write" },
+ profile: { scope: "document", id: "owner", access: "read" },
+ archive: { scope: "collection" },
+ },
+ createDocuments: true,
+ },
+ );
+ assert.deepEqual(parseMemoryBinding("notes=work_shop-1:read-write"), {
+ resource: "notes",
+ binding: { scope: "document", id: "work_shop-1", access: "read-write" },
+ });
+});
+
+test("session create rejects malformed memory bindings", () => {
+ assert.throws(() => parseSessionCommand(["--memory"]), /--memory requires a value/);
+ assert.throws(() => parseSessionCommand(["--memory", "Notes=workshop"]), /is not a resource id/);
+ assert.throws(() => parseSessionCommand(["--memory", "notes=work shop"]), /is not a document id/);
+ assert.throws(() => parseSessionCommand(["--memory", "notes=workshop:write"]), /access must be read or read-write/);
+ assert.throws(() => parseSessionCommand(["--memory", "notes=a", "--memory", "notes=b"]), /names resource notes twice/);
+ assert.throws(() => parseSessionCommand(["send", "ses-1", "hi", "--memory", "notes=a"]), /only supported when creating/);
+ assert.throws(() => parseSessionCommand(["--create-document"]), /needs at least one --memory/);
+ assert.throws(() => parseSessionCommand(["--memory", "notes", "--create-document"]), /applies to document bindings/);
+});
diff --git a/cli/src/session-command.ts b/cli/src/session-command.ts
index 50798d7c..4302c3eb 100644
--- a/cli/src/session-command.ts
+++ b/cli/src/session-command.ts
@@ -6,13 +6,81 @@ export type SessionAction =
| "send"
| "end";
+import type { MemoryBindings } from "./api.js";
+
export type SessionCommand = {
action: SessionAction;
args: string[];
keep: boolean;
agent?: string;
+ /** `--memory` bindings for `create`, keyed by resource. */
+ memory?: MemoryBindings;
+ /** `--create-document`: create each bound document that does not exist yet. */
+ createDocuments?: boolean;
};
+const RESOURCE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+const DOCUMENT_ID = /^[A-Za-z0-9_-]{1,128}$/;
+
+/**
+ * One `--memory` value: `<resource>=<documentId>[:read|read-write]` binds a
+ * document (read-write by default), `<resource>` alone binds the collection.
+ */
+export function parseMemoryBinding(
+ value: string,
+): { resource: string; binding: MemoryBindings[string] } {
+ const usage =
+ "--memory takes <resource>=<documentId>[:read|read-write] or <resource> for a collection";
+ const equals = value.indexOf("=");
+ const resource = equals < 0 ? value : value.slice(0, equals);
+ if (!RESOURCE_ID.test(resource) || resource.length > 128) {
+ throw new Error(`${usage}; ${JSON.stringify(resource)} is not a resource id`);
+ }
+ if (equals < 0) return { resource, binding: { scope: "collection" } };
+ const target = value.slice(equals + 1);
+ const colon = target.lastIndexOf(":");
+ const id = colon < 0 ? target : target.slice(0, colon);
+ const access = colon < 0 ? "read-write" : target.slice(colon + 1);
+ if (!DOCUMENT_ID.test(id)) {
+ throw new Error(`${usage}; ${JSON.stringify(id)} is not a document id`);
+ }
+ if (access !== "read" && access !== "read-write") {
+ throw new Error(`${usage}; access must be read or read-write`);
+ }
+ return { resource, binding: { scope: "document", id, access } };
+}
+
+function takeMemoryOptions(args: string[]): MemoryBindings | undefined {
+ const bindings: MemoryBindings = {};
+ let count = 0;
+ for (;;) {
+ const equalsIndex = args.findIndex((argument) =>
+ argument.startsWith("--memory="),
+ );
+ const index = equalsIndex >= 0 ? equalsIndex : args.indexOf("--memory");
+ if (index < 0) break;
+ let value: string;
+ if (equalsIndex >= 0) {
+ value = args[index]!.slice("--memory=".length);
+ args.splice(index, 1);
+ } else {
+ value = args[index + 1] ?? "";
+ if (!value || value.startsWith("--")) {
+ throw new Error("--memory requires a value");
+ }
+ args.splice(index, 2);
+ }
+ if (!value) throw new Error("--memory requires a value");
+ const { resource, binding } = parseMemoryBinding(value);
+ if (bindings[resource]) {
+ throw new Error(`--memory names resource ${resource} twice`);
+ }
+ bindings[resource] = binding;
+ count += 1;
+ }
+ return count ? bindings : undefined;
+}
+
export function developmentAgentReference(agentId: string): string {
return `${agentId}@development`;
}
@@ -86,6 +154,10 @@ export function parseSessionCommand(rawArgs: string[]): SessionCommand {
const args = [...rawArgs];
const agent = takeAgentOption(args);
+ const memory = takeMemoryOptions(args);
+ const createDocumentsIndex = args.indexOf("--create-document");
+ const createDocuments = createDocumentsIndex >= 0;
+ if (createDocuments) args.splice(createDocumentsIndex, 1);
const keepIndex = args.indexOf("--keep");
const keep = keepIndex >= 0;
if (keep) args.splice(keepIndex, 1);
@@ -98,5 +170,24 @@ export function parseSessionCommand(rawArgs: string[]): SessionCommand {
if (agent && action !== "create") {
throw new Error("--agent is only supported when creating a session.");
}
- return { action, args, keep, ...(agent ? { agent } : {}) };
+ if (memory && action !== "create") {
+ throw new Error("--memory is only supported when creating a session.");
+ }
+ if (createDocuments && !memory) {
+ throw new Error("--create-document needs at least one --memory <resource>=<documentId>.");
+ }
+ if (
+ createDocuments &&
+ !Object.values(memory ?? {}).some((binding) => binding.scope === "document")
+ ) {
+ throw new Error("--create-document applies to document bindings; --memory <resource> binds a collection.");
+ }
+ return {
+ action,
+ args,
+ keep,
+ ...(agent ? { agent } : {}),
+ ...(memory ? { memory } : {}),
+ ...(createDocuments ? { createDocuments } : {}),
+ };
}