Skip to content

An open-source, faster Devin alternative

TypeScript

cli: enumerate memory resources from the durable inventory

Igor Zalutskibe92035e6138
diff --git a/cli/README.md b/cli/README.md
index 3ccbac4c..e99da500 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -61,10 +61,12 @@ structured payload is available to agent code as `input.payload`.
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`:
+development. `list` without a resource shows the environment's resources,
+including ones no active deployment declares any more but that still hold
+documents. `list` and `show` print the management API's fields with `--json`:
```bash
+opencomputer memory list --environment development # resources, declared or not
opencomputer memory create requirements workshop --title "Workshop requirements"
opencomputer memory list requirements --environment development
opencomputer memory show requirements workshop --json
diff --git a/cli/src/api.ts b/cli/src/api.ts
index 8658a68f..513172ab 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -23,8 +23,10 @@ export interface ManagedProject {
id: string;
slug: string;
name: string;
+ /** One row per project agent and environment: that member's active deployment there. */
environments: Array<{
name: "development" | "production";
+ agentId?: string;
activeDeploymentId?: string;
updatedAt: string;
}>;
@@ -260,6 +262,18 @@ export interface MemoryDocumentPage {
nextCursor: string | null;
}
+/**
+ * One entry of the environment's resource inventory: storage outlives code,
+ * so `declared` says whether an active deployment still names the resource
+ * and `documents` counts the live documents it holds.
+ */
+export interface MemoryResource {
+ id: string;
+ provider: { kind?: string; maxBytes?: number };
+ declared: boolean;
+ documents: number;
+}
+
/** A document together with the `ETag` the next conditional request must send back verbatim. */
export interface MemoryDocumentRead {
document: MemoryDocument;
@@ -777,6 +791,18 @@ export class OpenComputerClient {
return { document, etag: response.headers.get("etag") ?? "" };
}
+ async memoryResources(input: {
+ projectId: string;
+ environment: MemoryEnvironment;
+ }): Promise<MemoryResource[]> {
+ const query = new URLSearchParams({ environment: input.environment });
+ const result = await this.request<{ resources: MemoryResource[] }>(
+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}` +
+ `/memory?${query.toString()}`,
+ );
+ return result.resources;
+ }
+
memoryDocuments(input: {
projectId: string;
resource: string;
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index f38996d6..dc15bb69 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -6,7 +6,6 @@ import {
type ManagedSessionSnapshot,
type MemoryDocument,
type MemoryDocumentMeta,
- type MemoryEnvironment,
} from "./api.js";
import { login, logout } from "./auth.js";
import { codexLogin } from "./codex-oauth.js";
@@ -50,6 +49,7 @@ 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";
+import { memoryResources, type MemoryResourceSummary } from "./memory.js";
export interface GlobalOptions {
apiUrl?: string;
@@ -269,7 +269,7 @@ 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`.";
+ "Use `opencomputer memory list [<resource>]|show|create|edit|freeze|unfreeze|export|remove`.";
function memoryWriterLabel(document: MemoryDocumentMeta): string {
return document.writer.kind === "agent"
@@ -318,6 +318,24 @@ async function readMemoryText(args: string[]): Promise<string | undefined> {
return Buffer.concat(chunks).toString("utf8");
}
+function printMemoryResources(
+ resources: MemoryResourceSummary[],
+ environment: string,
+): void {
+ if (!resources.length) {
+ process.stdout.write(`No ${environment} memory resources.\n`);
+ return;
+ }
+ for (const resource of resources) {
+ process.stdout.write(
+ `${resource.id.padEnd(24)} ${(resource.provider.kind ?? "document").padEnd(10)} ` +
+ `${(resource.provider.maxBytes !== undefined ? `${resource.provider.maxBytes} bytes` : "").padEnd(12)} ` +
+ `${(resource.declared ? "declared" : "not declared").padEnd(13)} ` +
+ `${resource.documents === undefined ? "" : `${resource.documents} document${resource.documents === 1 ? "" : "s"}`}\n`,
+ );
+ }
+}
+
// 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(
@@ -350,34 +368,6 @@ async function editMemoryTextInEditor(
};
}
-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.memory ?? []) {
- if (typeof declaration.id === "string") resources.add(declaration.id);
- }
- }
- return [...resources].sort();
-}
-
function printToolProgress(event: ManagedAgentEvent): void {
if (
event.type !== "tool.started" &&
@@ -1621,13 +1611,16 @@ export async function runCommand(
"Use `opencomputer memory export --out <dir> [--resource <id>] [--environment development|production]`.",
);
}
- const resources = explicitResources.length
- ? [...new Set(explicitResources)]
- : await memoryResourcesForEnvironment(client, projectId, environment);
+ const listing = explicitResources.length
+ ? undefined
+ : await memoryResources(client, projectId, environment);
+ const resources = listing
+ ? listing.resources.map((resource) => resource.id)
+ : [...new Set(explicitResources)];
if (!resources.length) {
throw new CLIError(
"memory_resources_unknown",
- `The active ${environment} deployment declares no memory resources.`,
+ `No ${environment} memory resources exist for this project.`,
"Pass --resource <id> for each resource to export, or deploy an agent that declares memory.",
);
}
@@ -1657,18 +1650,43 @@ export async function runCommand(
cursor = page.nextCursor ?? undefined;
} while (cursor);
}
- if (globals.json) printJSON({ environment, exported });
- else {
+ const undeclared =
+ listing?.resources
+ .filter((resource) => !resource.declared)
+ .map((resource) => resource.id) ?? [];
+ if (globals.json) {
+ printJSON({
+ environment,
+ exported,
+ ...(listing ? { resources: listing.resources } : {}),
+ });
+ } 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`,
+ `from ${resources.length} resource${resources.length === 1 ? "" : "s"} (${environment}).\n` +
+ (undeclared.length
+ ? `Not declared by any active deployment: ${undeclared.join(", ")}.\n`
+ : ""),
);
}
return;
}
const resource = args.shift();
+ if (action === "list" && !resource) {
+ const listing = await memoryResources(client, projectId, environment);
+ if (globals.json) printJSON(listing);
+ else {
+ printMemoryResources(listing.resources, environment);
+ if (listing.source === "declarations") {
+ process.stdout.write(
+ "Listed from active deployments' declarations; this backend has no resource inventory, so undeclared resources and document counts are not shown.\n",
+ );
+ }
+ }
+ return;
+ }
if (!resource) throw new Error(MEMORY_USAGE);
if (action === "list") {
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
diff --git a/cli/src/index.ts b/cli/src/index.ts
index 84e192de..e4296965 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -80,7 +80,7 @@ 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 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>]
diff --git a/cli/src/memory.test.ts b/cli/src/memory.test.ts
new file mode 100644
index 00000000..aedcf248
--- /dev/null
+++ b/cli/src/memory.test.ts
@@ -0,0 +1,162 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { OpenComputerClient } from "./api.js";
+import { memoryResources } from "./memory.js";
+
+const config = { apiUrl: "https://app.opencomputer.dev", apiKey: "test" };
+
+function route(input: string | URL | Request): string {
+ const url = new URL(input instanceof Request ? input.url : String(input));
+ return `${url.pathname}${url.search}`;
+}
+
+test("memory resources come from the durable inventory, undeclared ones included", async (context) => {
+ const paths: string[] = [];
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request) => {
+ paths.push(route(input));
+ return Response.json({
+ resources: [
+ {
+ id: "scratch",
+ provider: { kind: "document", maxBytes: 4096 },
+ declared: false,
+ documents: 2,
+ },
+ {
+ id: "requirements",
+ provider: { kind: "document", maxBytes: 8192 },
+ declared: true,
+ documents: 3,
+ },
+ ],
+ });
+ });
+
+ const listing = await memoryResources(
+ new OpenComputerClient(config),
+ "prj_1",
+ "production",
+ );
+
+ assert.deepEqual(paths, [
+ "/api/managed-agents/projects/prj_1/memory?environment=production",
+ ]);
+ assert.equal(listing.source, "inventory");
+ assert.deepEqual(
+ listing.resources.map((resource) => [
+ resource.id,
+ resource.declared,
+ resource.documents,
+ ]),
+ [
+ ["requirements", true, 3],
+ ["scratch", false, 2],
+ ],
+ );
+});
+
+test("without the inventory route, memory resources merge every project member's active declarations", async (context) => {
+ const paths: string[] = [];
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request) => {
+ const path = route(input);
+ paths.push(path);
+ if (path.startsWith("/api/managed-agents/projects/prj_1/memory")) {
+ return Response.json(
+ { error: { code: "not_found", message: "Route not found" } },
+ { status: 404 },
+ );
+ }
+ if (path === "/api/managed-agents/projects") {
+ return Response.json({
+ projects: [
+ {
+ id: "prj_1",
+ slug: "muse",
+ name: "Muse",
+ agents: [
+ { id: "muse", name: "Coordinator" },
+ { id: "muse--worker", name: "Worker" },
+ ],
+ environments: [
+ {
+ name: "development",
+ agentId: "muse",
+ activeDeploymentId: "muse:dev",
+ updatedAt: "2026-09-10T00:00:00.000Z",
+ },
+ {
+ name: "production",
+ agentId: "muse",
+ activeDeploymentId: "muse:prod",
+ updatedAt: "2026-09-10T00:00:00.000Z",
+ },
+ {
+ name: "development",
+ agentId: "muse--worker",
+ activeDeploymentId: "muse--worker:dev",
+ updatedAt: "2026-09-10T00:00:00.000Z",
+ },
+ {
+ name: "production",
+ agentId: "muse--worker",
+ updatedAt: "2026-09-10T00:00:00.000Z",
+ },
+ ],
+ createdAt: "2026-09-10T00:00:00.000Z",
+ updatedAt: "2026-09-10T00:00:00.000Z",
+ },
+ ],
+ });
+ }
+ if (path === "/api/managed-agents/deployments/muse%3Adev") {
+ return Response.json({
+ id: "muse:dev",
+ agentId: "muse",
+ alias: "development",
+ createdAt: "2026-09-10T00:00:00.000Z",
+ memory: [
+ {
+ id: "requirements",
+ provider: { kind: "document", maxBytes: 8192 },
+ },
+ ],
+ });
+ }
+ if (path === "/api/managed-agents/deployments/muse--worker%3Adev") {
+ return Response.json({
+ id: "muse--worker:dev",
+ agentId: "muse--worker",
+ alias: "development",
+ createdAt: "2026-09-10T00:00:00.000Z",
+ memory: [
+ { id: "requirements", provider: { kind: "document", maxBytes: 8192 } },
+ { id: "worker-notes", provider: { kind: "document", maxBytes: 4096 } },
+ ],
+ });
+ }
+ throw new Error(`unexpected request ${path}`);
+ });
+
+ const listing = await memoryResources(
+ new OpenComputerClient(config),
+ "prj_1",
+ "development",
+ );
+
+ assert.equal(listing.source, "declarations");
+ assert.deepEqual(listing.resources, [
+ {
+ id: "requirements",
+ provider: { kind: "document", maxBytes: 8192 },
+ declared: true,
+ },
+ {
+ id: "worker-notes",
+ provider: { kind: "document", maxBytes: 4096 },
+ declared: true,
+ },
+ ]);
+ assert.ok(paths.includes("/api/managed-agents/deployments/muse--worker%3Adev"));
+ assert.ok(!paths.some((path) => path.includes("muse%3Aprod")));
+});
diff --git a/cli/src/memory.ts b/cli/src/memory.ts
new file mode 100644
index 00000000..6e548597
--- /dev/null
+++ b/cli/src/memory.ts
@@ -0,0 +1,97 @@
+import {
+ APIError,
+ type MemoryEnvironment,
+ type MemoryResource,
+ type OpenComputerClient,
+} from "./api.js";
+
+// Project memory (docs/agents/document-memory.mdx, "Owner access"): the parts
+// of the `memory` command group that talk to the API and have to be right
+// independently of the terminal.
+
+/**
+ * A resource of the environment as the owner sees it. `documents` is unknown
+ * when the list came from deployment declarations rather than the inventory.
+ */
+export interface MemoryResourceSummary {
+ id: string;
+ provider: { kind?: string; maxBytes?: number };
+ declared: boolean;
+ documents?: number;
+}
+
+export interface MemoryResourceListing {
+ resources: MemoryResourceSummary[];
+ /** Where the list came from; declarations cannot show undeclared resources or counts. */
+ source: "inventory" | "declarations";
+}
+
+/**
+ * The environment's resources: the durable inventory when the backend has
+ * it, otherwise the declarations of every project member's active
+ * deployment there. Never one agent's declarations alone; a resource a
+ * worker declares, or one no deployment declares any more, is still data.
+ */
+export async function memoryResources(
+ client: OpenComputerClient,
+ projectId: string,
+ environment: MemoryEnvironment,
+): Promise<MemoryResourceListing> {
+ try {
+ const resources = await client.memoryResources({ projectId, environment });
+ return {
+ resources: [...resources]
+ .map((resource: MemoryResource) => ({
+ id: resource.id,
+ provider: resource.provider ?? {},
+ declared: resource.declared,
+ documents: resource.documents,
+ }))
+ .sort(byId),
+ source: "inventory",
+ };
+ } catch (error) {
+ // A backend without the inventory route: fall back to declarations.
+ if (!(error instanceof APIError && error.status === 404)) throw error;
+ }
+ 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 byResource = new Map<string, MemoryResourceSummary>();
+ for (const deploymentId of deploymentIds) {
+ const deployment = await client.deployment(deploymentId);
+ for (const declaration of deployment.memory ?? []) {
+ if (typeof declaration.id !== "string" || byResource.has(declaration.id)) {
+ continue;
+ }
+ byResource.set(declaration.id, {
+ id: declaration.id,
+ provider: {
+ ...(declaration.provider?.kind ? { kind: declaration.provider.kind } : {}),
+ ...(typeof declaration.provider?.maxBytes === "number"
+ ? { maxBytes: declaration.provider.maxBytes }
+ : {}),
+ },
+ declared: true,
+ });
+ }
+ }
+ return {
+ resources: [...byResource.values()].sort(byId),
+ source: "declarations",
+ };
+}
+
+function byId(left: { id: string }, right: { id: string }): number {
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
+}