Skip to content

An open-source, faster Devin alternative

TypeScript

cli: memory command group over the project memory API

Igor Zalutski3e60322e1976
diff --git a/cli/README.md b/cli/README.md
index 4624b7c2..3ccbac4c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -57,6 +57,29 @@ opencomputer webhooks remove <webhook-id>
Invoke the URL with a JSON object containing `text`, `payload`, or both. The
structured payload is available to agent code as `input.payload`.
+## Memory
+
+Manage the documents a project's memory resources hold, per environment.
+Every command resolves the linked project; `--environment` defaults to
+development. `list` and `show` print the management API's fields with
+`--json`:
+
+```bash
+opencomputer memory create requirements workshop --title "Workshop requirements"
+opencomputer memory list requirements --environment development
+opencomputer memory show requirements workshop --json
+opencomputer memory edit requirements workshop # opens $EDITOR, saves conditionally
+opencomputer memory freeze requirements workshop # agentWrites: disabled
+opencomputer memory unfreeze requirements workshop
+opencomputer memory export --out ./memory # <out>/<resource>/<id>.json
+opencomputer memory remove requirements workshop
+```
+
+`edit` replaces the text with the revision it read; if the document changed
+meanwhile the command exits non-zero with the conflict and keeps your edited
+text in a temporary file. Pass `--text-file` or `--text-stdin` to `create` and
+`edit` to supply text without an editor.
+
## Secrets and managed egress
Secret values are accepted only from standard input with `--value-stdin`.
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 3fc61788..9eaa02f7 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.6.8",
+ "version": "0.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.6.8",
+ "version": "0.7.0",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
diff --git a/cli/package.json b/cli/package.json
index e7a49818..342a6724 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.6.9",
+ "version": "0.7.0",
"description": "Build, test, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
diff --git a/cli/src/api.test.ts b/cli/src/api.test.ts
index 18867e39..8cca67d5 100644
--- a/cli/src/api.test.ts
+++ b/cli/src/api.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { OpenComputerClient } from "./api.js";
+import { APIError, OpenComputerClient } from "./api.js";
test("mutations derive stable, operation-specific idempotency headers", async (context) => {
const requests: Request[] = [];
@@ -25,3 +25,103 @@ test("mutations derive stable, operation-specific idempotency headers", async (c
assert.notEqual(keys[0], keys[2]);
assert.equal(keys[0]?.includes("retry-42"), false);
});
+
+test("memory documents travel with their ETag and send it back as a precondition", async (context) => {
+ const requests: Request[] = [];
+ const document = {
+ id: "workshop",
+ title: "Workshop requirements",
+ text: "Node.js 22.",
+ summary: "",
+ agentWrites: "enabled",
+ revision: "rev-1",
+ bytes: 11,
+ maxBytes: 8192,
+ updatedAt: "2026-09-10T12:00:00.000Z",
+ writer: { kind: "owner" },
+ };
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ if (request.method === "DELETE") return new Response(null, { status: 204 });
+ return Response.json(document, { headers: { etag: '"rev-1"' } });
+ });
+ const client = new OpenComputerClient({
+ apiUrl: "https://app.opencomputer.dev",
+ apiKey: "test",
+ });
+ const target = {
+ projectId: "prj_1",
+ resource: "requirements",
+ id: "workshop",
+ environment: "development" as const,
+ };
+
+ const created = await client.createMemoryDocument({
+ ...target,
+ title: "Workshop requirements",
+ text: "Node.js 22.",
+ });
+ assert.equal(created.etag, '"rev-1"');
+ assert.equal(created.document.revision, "rev-1");
+ await client.replaceMemoryDocument({ ...target, etag: created.etag, text: "Node 22" });
+ await client.patchMemoryDocument({ ...target, etag: created.etag, agentWrites: "disabled" });
+ await client.deleteMemoryDocument({ ...target, etag: created.etag });
+ await client.memoryDocuments({ ...target, cursor: "c2" });
+
+ const [create, replace, patch, remove, list] = requests;
+ assert.ok(create && replace && patch && remove && list);
+ assert.equal(
+ create.url,
+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents/workshop?environment=development",
+ );
+ assert.equal(create.method, "PUT");
+ assert.equal(create.headers.get("if-none-match"), "*");
+ assert.equal(create.headers.get("if-match"), null);
+ assert.deepEqual(await create.json(), {
+ title: "Workshop requirements",
+ text: "Node.js 22.",
+ });
+ assert.equal(replace.headers.get("if-match"), '"rev-1"');
+ assert.deepEqual(await replace.json(), { text: "Node 22" });
+ assert.equal(patch.method, "PATCH");
+ assert.deepEqual(await patch.json(), { agentWrites: "disabled" });
+ assert.equal(remove.method, "DELETE");
+ assert.equal(remove.headers.get("if-match"), '"rev-1"');
+ assert.equal(
+ list.url,
+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/memory/requirements/documents?environment=development&cursor=c2",
+ );
+ for (const request of requests) {
+ assert.equal(request.headers.get("x-api-key"), "test");
+ }
+});
+
+test("memory precondition failures surface the API's code", async (context) => {
+ context.mock.method(globalThis, "fetch", async () =>
+ Response.json(
+ { error: { code: "precondition_failed", message: "The document changed." } },
+ { status: 412 },
+ ),
+ );
+ const client = new OpenComputerClient({
+ apiUrl: "https://app.opencomputer.dev",
+ apiKey: "test",
+ });
+
+ await assert.rejects(
+ client.replaceMemoryDocument({
+ projectId: "prj_1",
+ resource: "requirements",
+ id: "workshop",
+ environment: "development",
+ etag: '"rev-0"',
+ text: "stale",
+ }),
+ (error: unknown) =>
+ error instanceof APIError &&
+ error.status === 412 &&
+ error.code === "precondition_failed" &&
+ error.message === "The document changed.",
+ );
+});
diff --git a/cli/src/api.ts b/cli/src/api.ts
index 1e05116b..07273e1c 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -231,6 +231,48 @@ export interface ManagedSessionSnapshot {
}>;
}
+export type MemoryEnvironment = "development" | "production";
+
+export type MemoryWriter =
+ | { kind: "owner" }
+ | { kind: "agent"; sessionId: string };
+
+/** One document's metadata, as the list route returns it (no text). */
+export interface MemoryDocumentMeta {
+ id: string;
+ title: string;
+ summary: string;
+ agentWrites: "enabled" | "disabled";
+ revision: string;
+ bytes: number;
+ maxBytes: number;
+ updatedAt: string;
+ writer: MemoryWriter;
+}
+
+/** A full document, as read, create, replace and patch return it. */
+export interface MemoryDocument extends MemoryDocumentMeta {
+ text: string;
+}
+
+export interface MemoryDocumentPage {
+ documents: MemoryDocumentMeta[];
+ nextCursor: string | null;
+}
+
+/** A document together with the `ETag` the next conditional request must send back verbatim. */
+export interface MemoryDocumentRead {
+ document: MemoryDocument;
+ etag: string;
+}
+
+/** A memory resource declared by a deployment (`projectDeployment.resources.memory`). */
+export interface MemoryDeclaration {
+ id: string;
+ description?: string;
+ provider?: { kind: string; maxBytes?: number };
+}
+
interface CreateSessionResult {
session: ManagedSessionSnapshot;
deployment?: ManagedAgentDeployment;
@@ -240,11 +282,24 @@ export class APIError extends Error {
constructor(
message: string,
readonly status: number,
+ /** The typed reason from `{ error: { code } }` when the API sent one. */
+ readonly code?: string,
) {
super(message);
}
}
+function errorCode(body: unknown): string | undefined {
+ if (body && typeof body === "object") {
+ const error = (body as Record<string, unknown>).error;
+ if (error && typeof error === "object") {
+ const code = (error as Record<string, unknown>).code;
+ if (typeof code === "string") return code;
+ }
+ }
+ return undefined;
+}
+
function errorMessage(body: unknown, status: number): string {
if (body && typeof body === "object") {
const record = body as Record<string, unknown>;
@@ -304,7 +359,11 @@ export class OpenComputerClient {
});
if (!response.ok) {
const body: unknown = await response.json().catch(() => undefined);
- throw new APIError(errorMessage(body, response.status), response.status);
+ throw new APIError(
+ errorMessage(body, response.status),
+ response.status,
+ errorCode(body),
+ );
}
return response;
}
@@ -683,6 +742,145 @@ export class OpenComputerClient {
);
}
+ deployment(deploymentId: string) {
+ return this.request<
+ ManagedAgentDeployment & {
+ projectDeployment?: {
+ resources?: Partial<ProjectResourceManifest> & {
+ memory?: MemoryDeclaration[];
+ };
+ };
+ }
+ >(`/api/managed-agents/deployments/${encodeURIComponent(deploymentId)}`);
+ }
+
+ // Project memory (docs/agents/document-memory.mdx, "Management API").
+ // Every mutation is conditional: the caller sends back the ETag it read.
+
+ private memoryPath(input: {
+ projectId: string;
+ resource: string;
+ id?: string;
+ environment: MemoryEnvironment;
+ cursor?: string;
+ }): string {
+ const query = new URLSearchParams({ environment: input.environment });
+ if (input.cursor) query.set("cursor", input.cursor);
+ return (
+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}` +
+ `/memory/${encodeURIComponent(input.resource)}/documents` +
+ (input.id !== undefined ? `/${encodeURIComponent(input.id)}` : "") +
+ `?${query.toString()}`
+ );
+ }
+
+ private async memoryDocumentResponse(
+ path: string,
+ init: RequestInit,
+ ): Promise<MemoryDocumentRead> {
+ const response = await this.response(path, init);
+ const document = (await response.json()) as MemoryDocument;
+ return { document, etag: response.headers.get("etag") ?? "" };
+ }
+
+ memoryDocuments(input: {
+ projectId: string;
+ resource: string;
+ environment: MemoryEnvironment;
+ cursor?: string;
+ }) {
+ return this.request<MemoryDocumentPage>(
+ this.memoryPath({
+ projectId: input.projectId,
+ resource: input.resource,
+ environment: input.environment,
+ ...(input.cursor ? { cursor: input.cursor } : {}),
+ }),
+ );
+ }
+
+ memoryDocument(input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ }) {
+ return this.memoryDocumentResponse(this.memoryPath(input), {});
+ }
+
+ createMemoryDocument(input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ title: string;
+ text: string;
+ summary?: string;
+ agentWrites?: "enabled" | "disabled";
+ }) {
+ return this.memoryDocumentResponse(this.memoryPath(input), {
+ method: "PUT",
+ headers: { "if-none-match": "*" },
+ body: JSON.stringify({
+ title: input.title,
+ text: input.text,
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),
+ }),
+ });
+ }
+
+ replaceMemoryDocument(input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ etag: string;
+ text: string;
+ summary?: string;
+ }) {
+ return this.memoryDocumentResponse(this.memoryPath(input), {
+ method: "PUT",
+ headers: { "if-match": input.etag },
+ body: JSON.stringify({
+ text: input.text,
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
+ }),
+ });
+ }
+
+ patchMemoryDocument(input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ etag: string;
+ title?: string;
+ agentWrites?: "enabled" | "disabled";
+ }) {
+ return this.memoryDocumentResponse(this.memoryPath(input), {
+ method: "PATCH",
+ headers: { "if-match": input.etag },
+ body: JSON.stringify({
+ ...(input.title !== undefined ? { title: input.title } : {}),
+ ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),
+ }),
+ });
+ }
+
+ deleteMemoryDocument(input: {
+ projectId: string;
+ resource: string;
+ id: string;
+ environment: MemoryEnvironment;
+ etag: string;
+ }) {
+ return this.request<void>(this.memoryPath(input), {
+ method: "DELETE",
+ headers: { "if-match": input.etag },
+ });
+ }
+
logs(input: {
agentId?: string;
sessionId?: string;
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 82597839..225f6efa 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -1,8 +1,12 @@
import {
+ APIError,
OpenComputerClient,
type ManagedAgentEvent,
type ManagedAgentLog,
type ManagedSessionSnapshot,
+ type MemoryDocument,
+ type MemoryDocumentMeta,
+ type MemoryEnvironment,
} from "./api.js";
import { login, logout } from "./auth.js";
import { codexLogin } from "./codex-oauth.js";
@@ -39,6 +43,10 @@ import {
materializeTemplateCheckout,
} from "./template-local.js";
import { materializeProjectArchive } from "./project-local.js";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
import { createInterface } from "node:readline/promises";
import { doctorProject, type DoctorResult } from "./doctor.js";
import { CLIError } from "./errors.js";
@@ -258,6 +266,119 @@ function printSession(session: ManagedSessionSnapshot): void {
);
}
+// Project memory (docs/agents/document-memory.mdx, "Owner access").
+
+const MEMORY_USAGE =
+ "Use `opencomputer memory list|show|create|edit|freeze|unfreeze|export|remove`.";
+
+function memoryWriterLabel(document: MemoryDocumentMeta): string {
+ return document.writer.kind === "agent"
+ ? `agent ${document.writer.sessionId}`
+ : "owner";
+}
+
+function memorySizeLabel(document: MemoryDocumentMeta): string {
+ return (
+ `${document.bytes}/${document.maxBytes} bytes` +
+ (document.bytes > document.maxBytes ? " (over limit)" : "")
+ );
+}
+
+function printMemoryDocument(document: MemoryDocument): void {
+ process.stdout.write(
+ `${document.id} ${document.title}\n` +
+ `summary: ${document.summary || "—"}\n` +
+ `agent writes: ${document.agentWrites}\n` +
+ `size: ${memorySizeLabel(document)}\n` +
+ `updated: ${document.updatedAt} by ${memoryWriterLabel(document)}\n` +
+ `revision: ${document.revision}\n\n` +
+ `${document.text}${document.text.endsWith("\n") || !document.text ? "" : "\n"}`,
+ );
+}
+
+async function readMemoryText(args: string[]): Promise<string | undefined> {
+ const textFile = option(args, "--text-file");
+ const textStdin = flag(args, "--text-stdin");
+ if (textFile && textStdin) {
+ throw new Error("Choose either --text-file or --text-stdin.");
+ }
+ if (textFile) return readFile(resolvePath(textFile), "utf8");
+ if (!textStdin) return undefined;
+ if (process.stdin.isTTY) {
+ throw new CLIError(
+ "value_stdin_required",
+ "--text-stdin requires piped standard input.",
+ "Use `cat notes.md | opencomputer memory ... --text-stdin`.",
+ );
+ }
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+// Opens the current text in $VISUAL/$EDITOR and returns what the user saved.
+// The file stays in place on a failed save so the edit is not lost.
+async function editMemoryTextInEditor(
+ resource: string,
+ id: string,
+ text: string,
+): Promise<{ text: string; path: string; discard: () => Promise<void> }> {
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ throw new CLIError(
+ "editor_required",
+ "memory edit opens an editor and needs an interactive terminal.",
+ "Pass --text-file <path> or pipe the new text with --text-stdin.",
+ );
+ }
+ const editor = process.env.VISUAL || process.env.EDITOR || "vi";
+ const directory = await mkdtemp(join(tmpdir(), "opencomputer-memory-"));
+ const path = join(directory, `${resource}--${id}.md`);
+ await writeFile(path, text, "utf8");
+ const result = spawnSync("/bin/sh", ["-c", `${editor} "$1"`, "sh", path], {
+ stdio: "inherit",
+ });
+ if (result.status !== 0) {
+ await rm(directory, { recursive: true, force: true });
+ throw new Error(`Editor exited with status ${result.status ?? "unknown"}.`);
+ }
+ return {
+ text: await readFile(path, "utf8"),
+ path,
+ discard: () => rm(directory, { recursive: true, force: true }),
+ };
+}
+
+async function memoryResourcesForEnvironment(
+ client: OpenComputerClient,
+ projectId: string,
+ environment: MemoryEnvironment,
+): Promise<string[]> {
+ const project = (await client.projects()).find(
+ (candidate) => candidate.id === projectId,
+ );
+ if (!project) throw new Error("The bound project is no longer available.");
+ const deploymentIds = [
+ ...new Set(
+ project.environments
+ .filter((candidate) => candidate.name === environment)
+ .flatMap((candidate) =>
+ candidate.activeDeploymentId ? [candidate.activeDeploymentId] : [],
+ ),
+ ),
+ ];
+ const resources = new Set<string>();
+ for (const deploymentId of deploymentIds) {
+ const deployment = await client.deployment(deploymentId);
+ for (const declaration of deployment.projectDeployment?.resources?.memory ??
+ []) {
+ if (typeof declaration.id === "string") resources.add(declaration.id);
+ }
+ }
+ return [...resources].sort();
+}
+
function printToolProgress(event: ManagedAgentEvent): void {
if (
event.type !== "tool.started" &&
@@ -1485,6 +1606,225 @@ export async function runCommand(
);
}
+ if (command === "memory") {
+ const action = args.shift();
+ const projectReference = option(args, "--project");
+ const environment = environmentOption(option(args, "--environment"));
+ if (!action) throw new Error(MEMORY_USAGE);
+ const project = await selectedProject(client, config, projectReference);
+ const projectId = project.projectId;
+
+ if (action === "export") {
+ const out = option(args, "--out");
+ const explicitResources = options(args, "--resource");
+ if (!out || args.length) {
+ throw new Error(
+ "Use `opencomputer memory export --out <dir> [--resource <id>] [--environment development|production]`.",
+ );
+ }
+ const resources = explicitResources.length
+ ? [...new Set(explicitResources)]
+ : await memoryResourcesForEnvironment(client, projectId, environment);
+ if (!resources.length) {
+ throw new CLIError(
+ "memory_resources_unknown",
+ `The active ${environment} deployment declares no memory resources.`,
+ "Pass --resource <id> for each resource to export, or deploy an agent that declares memory.",
+ );
+ }
+ const exported: Array<{ resource: string; id: string; path: string }> = [];
+ for (const resource of resources) {
+ const directory = resolvePath(out, resource);
+ await mkdir(directory, { recursive: true });
+ let cursor: string | undefined;
+ do {
+ const page = await client.memoryDocuments({
+ projectId,
+ resource,
+ environment,
+ ...(cursor ? { cursor } : {}),
+ });
+ for (const meta of page.documents) {
+ const { document } = await client.memoryDocument({
+ projectId,
+ resource,
+ id: meta.id,
+ environment,
+ });
+ const path = join(directory, `${document.id}.json`);
+ await writeFile(path, `${JSON.stringify(document, null, 2)}\n`, "utf8");
+ exported.push({ resource, id: document.id, path });
+ }
+ cursor = page.nextCursor ?? undefined;
+ } while (cursor);
+ }
+ if (globals.json) printJSON({ environment, exported });
+ else {
+ for (const entry of exported) process.stdout.write(`${entry.path}\n`);
+ process.stdout.write(
+ `Exported ${exported.length} document${exported.length === 1 ? "" : "s"} ` +
+ `from ${resources.length} resource${resources.length === 1 ? "" : "s"} (${environment}).\n`,
+ );
+ }
+ return;
+ }
+
+ const resource = args.shift();
+ if (!resource) throw new Error(MEMORY_USAGE);
+ if (action === "list") {
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const documents: MemoryDocumentMeta[] = [];
+ let cursor: string | undefined;
+ do {
+ const page = await client.memoryDocuments({
+ projectId,
+ resource,
+ environment,
+ ...(cursor ? { cursor } : {}),
+ });
+ documents.push(...page.documents);
+ cursor = page.nextCursor ?? undefined;
+ } while (cursor);
+ if (globals.json) printJSON({ documents });
+ else if (!documents.length) {
+ process.stdout.write(`No ${environment} documents in ${resource}.\n`);
+ } else {
+ for (const document of documents) {
+ process.stdout.write(
+ `${document.id.padEnd(24)} ${document.title.padEnd(32)} ` +
+ `${memorySizeLabel(document).padEnd(24)} ` +
+ `${document.agentWrites.padEnd(9)} ${document.updatedAt} ` +
+ `${memoryWriterLabel(document)}\n`,
+ );
+ }
+ }
+ return;
+ }
+
+ const id = args.shift();
+ if (!id) throw new Error(MEMORY_USAGE);
+ const target = { projectId, resource, id, environment };
+
+ if (action === "show") {
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const { document } = await client.memoryDocument(target);
+ if (globals.json) printJSON(document);
+ else printMemoryDocument(document);
+ return;
+ }
+ if (action === "create") {
+ const title = option(args, "--title");
+ const summary = option(args, "--summary");
+ const frozen = flag(args, "--frozen");
+ const text = await readMemoryText(args);
+ if (!title || args.length) {
+ throw new Error(
+ "Use `opencomputer memory create <resource> <id> --title <title> [--summary <text>] [--text-file <path>|--text-stdin] [--frozen]`.",
+ );
+ }
+ const { document } = await client.createMemoryDocument({
+ ...target,
+ title,
+ text: text ?? "",
+ ...(summary !== undefined ? { summary } : {}),
+ ...(frozen ? { agentWrites: "disabled" as const } : {}),
+ });
+ if (globals.json) printJSON(document);
+ else {
+ process.stdout.write(
+ `Created ${resource}/${document.id} (${memorySizeLabel(document)}, ${environment}).\n`,
+ );
+ }
+ return;
+ }
+ if (action === "edit") {
+ const summary = option(args, "--summary");
+ const supplied = await readMemoryText(args);
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const current = await client.memoryDocument(target);
+ let edited: Awaited<ReturnType<typeof editMemoryTextInEditor>> | undefined;
+ const text =
+ supplied ??
+ (edited = await editMemoryTextInEditor(
+ resource,
+ id,
+ current.document.text,
+ )).text;
+ if (text === current.document.text && summary === undefined) {
+ await edited?.discard();
+ if (globals.json) printJSON(current.document);
+ else process.stdout.write(`No changes to ${resource}/${id}.\n`);
+ return;
+ }
+ try {
+ const { document } = await client.replaceMemoryDocument({
+ ...target,
+ etag: current.etag,
+ text,
+ ...(summary !== undefined ? { summary } : {}),
+ });
+ await edited?.discard();
+ if (globals.json) printJSON(document);
+ else {
+ process.stdout.write(
+ `Saved ${resource}/${document.id} (${memorySizeLabel(document)}, revision ${document.revision}).\n`,
+ );
+ }
+ } catch (error) {
+ if (error instanceof APIError && error.status === 412) {
+ const latest = await client.memoryDocument(target).catch(() => null);
+ throw new CLIError(
+ "memory_conflict",
+ `${resource}/${id} changed since you opened it` +
+ (latest
+ ? ` (now revision ${latest.document.revision}, updated ${latest.document.updatedAt} by ${memoryWriterLabel(latest.document)})`
+ : "") +
+ `; your edit was not saved.`,
+ (edited ? `Your edited text is kept at ${edited.path}. ` : "") +
+ "Run `opencomputer memory show` to read the current text, reconcile, and edit again.",
+ {
+ status: 412,
+ ...(latest ? { current: latest.document } : {}),
+ ...(edited ? { editedTextPath: edited.path } : {}),
+ },
+ );
+ }
+ await edited?.discard();
+ throw error;
+ }
+ return;
+ }
+ if (action === "freeze" || action === "unfreeze") {
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const current = await client.memoryDocument(target);
+ const agentWrites = action === "freeze" ? "disabled" : "enabled";
+ const { document } =
+ current.document.agentWrites === agentWrites
+ ? current
+ : await client.patchMemoryDocument({
+ ...target,
+ etag: current.etag,
+ agentWrites,
+ });
+ if (globals.json) printJSON(document);
+ else {
+ process.stdout.write(
+ `Agent writes ${document.agentWrites} for ${resource}/${document.id} (${environment}).\n`,
+ );
+ }
+ return;
+ }
+ if (action === "remove" || action === "delete") {
+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
+ const current = await client.memoryDocument(target);
+ await client.deleteMemoryDocument({ ...target, etag: current.etag });
+ if (globals.json) printJSON({ deleted: true, resource, id, environment });
+ else process.stdout.write(`Removed ${resource}/${id} (${environment}).\n`);
+ return;
+ }
+ throw new Error(MEMORY_USAGE);
+ }
+
if (command === "logs") {
const follow = flag(args, "--follow");
let agentId = option(args, "--agent");
diff --git a/cli/src/errors.test.ts b/cli/src/errors.test.ts
index b89d87ba..e92dc9d3 100644
--- a/cli/src/errors.test.ts
+++ b/cli/src/errors.test.ts
@@ -16,3 +16,20 @@ test("structured CLI errors always include a stable code and fix hint", () => {
details: { status: 404 },
});
});
+
+test("memory precondition and size failures map to their own codes", () => {
+ const stale = structuredError(
+ new APIError("Stale revision.", 412, "precondition_failed"),
+ );
+ assert.equal(stale.code, "precondition_failed");
+ assert.deepEqual(stale.details, { status: 412, apiCode: "precondition_failed" });
+ assert.match(stale.hint, /reconcile/);
+ assert.equal(
+ structuredError(new APIError("Too big.", 413, "memory_limit_exceeded")).code,
+ "payload_too_large",
+ );
+ assert.equal(
+ structuredError(new APIError("If-Match required.", 428)).code,
+ "precondition_required",
+ );
+});
diff --git a/cli/src/errors.ts b/cli/src/errors.ts
index 18dbcc88..8afcff89 100644
--- a/cli/src/errors.ts
+++ b/cli/src/errors.ts
@@ -36,7 +36,13 @@ export function structuredError(error: unknown): StructuredCLIError {
? "resource_not_found"
: error.status === 409
? "conflict"
- : "api_request_failed";
+ : error.status === 412
+ ? "precondition_failed"
+ : error.status === 413
+ ? "payload_too_large"
+ : error.status === 428
+ ? "precondition_required"
+ : "api_request_failed";
const hint =
code === "authentication_required"
? "Run `opencomputer login` or set OPENCOMPUTER_API_KEY."
@@ -44,8 +50,22 @@ export function structuredError(error: unknown): StructuredCLIError {
? "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 } };
+ : code === "precondition_failed"
+ ? "Read the current state, reconcile your change, and retry; a deleted ID cannot be reused."
+ : code === "payload_too_large"
+ ? "Shorten the content to fit the documented byte limit and retry."
+ : code === "precondition_required"
+ ? "Send the precondition the operation requires and retry."
+ : "Retry the command; if it persists, inspect `opencomputer logs --json`.";
+ return {
+ code,
+ message,
+ hint,
+ details: {
+ status: error.status,
+ ...(error.code ? { apiCode: error.code } : {}),
+ },
+ };
}
if (/not logged in/i.test(message)) {
return {
diff --git a/cli/src/index.ts b/cli/src/index.ts
index f0ed3e1b..84e192de 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -80,6 +80,14 @@ Usage:
opencomputer webhooks disable <webhook-id> [--project <id|slug>]
opencomputer webhooks rotate-token <webhook-id> [--project <id|slug>]
opencomputer webhooks remove <webhook-id> [--project <id|slug>]
+ opencomputer memory list <resource> [--environment development|production]
+ opencomputer memory show <resource> <id> [--environment development|production]
+ opencomputer memory create <resource> <id> --title <title> [--summary <text>] [--text-file <path>|--text-stdin] [--frozen]
+ opencomputer memory edit <resource> <id> [--text-file <path>|--text-stdin] [--summary <text>]
+ opencomputer memory freeze <resource> <id> [--environment development|production]
+ opencomputer memory unfreeze <resource> <id> [--environment development|production]
+ opencomputer memory export --out <dir> [--resource <id>] [--environment development|production]
+ opencomputer memory remove <resource> <id> [--environment development|production]
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]