An open-source, faster Devin alternative
TypeScript
Merge remote-tracking branch 'origin/feat/memory-surface' into feat/project-memory
Igor Zalutski04cbb55a3867
diff --cc cli/src/commands.tsindex f38996d6,16652716..981d45b3--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@@ -50,6 -48,12 +48,12 @@@ import { join, resolve as resolvePathimport { createInterface } from "node:readline/promises";import { doctorProject, type DoctorResult } from "./doctor.js";import { CLIError } from "./errors.js";+ import {+ memoryResources,+ saveMemoryEdit,+ type MemoryEditDraft,+ type MemoryResourceSummary,-} from "./memory.js";++} from "./memory-commands.js";export interface GlobalOptions {apiUrl?: string;diff --cc cli/src/memory-commands.test.tsindex 00000000,c82454cb..8dd14276mode 000000,100644..100644--- a/cli/src/memory-commands.test.ts+++ b/cli/src/memory-commands.test.ts@@@ -1,0 -1,286 +1,286 @@@+ import assert from "node:assert/strict";+ import { access, mkdtemp, rm, writeFile } from "node:fs/promises";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import test from "node:test";++ import { OpenComputerClient } from "./api.js";+ import { CLIError } from "./errors.js";-import { memoryResources, saveMemoryEdit } from "./memory.js";++import { memoryResources, saveMemoryEdit } from "./memory-commands.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")));+ });++ async function draftFile(): Promise<{+ path: string;+ discarded: () => boolean;+ discard: () => Promise<void>;+ cleanup: () => Promise<void>;+ }> {+ const directory = await mkdtemp(join(tmpdir(), "opencomputer-memory-test-"));+ const path = join(directory, "requirements--workshop.md");+ await writeFile(path, "Exercises must run on Node.js 22.\n", "utf8");+ let discarded = false;+ return {+ path,+ discarded: () => discarded,+ discard: async () => {+ discarded = true;+ await rm(directory, { recursive: true, force: true });+ },+ cleanup: () => rm(directory, { recursive: true, force: true }),+ };+ }++ const target = {+ projectId: "prj_1",+ resource: "requirements",+ id: "workshop",+ environment: "development" as const,+ etag: '"rev-1"',+ text: "Exercises must run on Node.js 22.\n",+ };++ test("an over-limit save keeps the edited draft and says where it is", async (context) => {+ context.mock.method(globalThis, "fetch", async () =>+ Response.json(+ {+ error: {+ code: "memory_limit_exceeded",+ message: "Text is 9000 bytes; the limit is 8192.",+ },+ },+ { status: 413 },+ ),+ );+ const draft = await draftFile();+ try {+ const error = await saveMemoryEdit(new OpenComputerClient(config), {+ ...target,+ draft,+ }).catch((error: unknown) => error);++ assert.ok(error instanceof CLIError);+ assert.equal(error.code, "memory_too_large");+ assert.match(error.message, /requirements\/workshop was not saved: Text is 9000 bytes/);+ assert.match(error.hint, new RegExp(`kept at ${draft.path}`));+ assert.match(error.hint, /--text-file/);+ assert.deepEqual(error.details, {+ status: 413,+ apiCode: "memory_limit_exceeded",+ editedTextPath: draft.path,+ });+ assert.equal(draft.discarded(), false);+ await access(draft.path);+ } finally {+ await draft.cleanup();+ }+ });++ test("a save that never reaches the API keeps the edited draft", async (context) => {+ context.mock.method(globalThis, "fetch", async () => {+ throw new TypeError("fetch failed");+ });+ const draft = await draftFile();+ try {+ const error = await saveMemoryEdit(new OpenComputerClient(config), {+ ...target,+ draft,+ }).catch((error: unknown) => error);++ assert.ok(error instanceof CLIError);+ assert.equal(error.code, "command_failed");+ assert.match(error.message, /was not saved: fetch failed/);+ assert.match(error.hint, new RegExp(`kept at ${draft.path}`));+ assert.deepEqual(error.details, { editedTextPath: draft.path });+ await access(draft.path);+ } finally {+ await draft.cleanup();+ }+ });++ test("a saved edit discards its draft", async (context) => {+ context.mock.method(globalThis, "fetch", async () =>+ Response.json(+ {+ id: "workshop",+ title: "Workshop requirements",+ text: target.text,+ summary: "",+ agentWrites: "enabled",+ revision: "rev-2",+ bytes: 34,+ maxBytes: 8192,+ updatedAt: "2026-09-10T12:00:00.000Z",+ writer: { kind: "owner" },+ },+ { headers: { etag: '"rev-2"' } },+ ),+ );+ const draft = await draftFile();+ try {+ const document = await saveMemoryEdit(new OpenComputerClient(config), {+ ...target,+ draft,+ });+ assert.equal(document.revision, "rev-2");+ assert.equal(draft.discarded(), true);+ await assert.rejects(access(draft.path));+ } finally {+ await draft.cleanup();+ }+ });diff --cc cli/src/memory-commands.tsindex 00000000,00000000..ef6f9d70new file mode 100644--- /dev/null+++ b/cli/src/memory-commands.ts@@@ -1,0 -1,0 +1,176 @@@++import {++ APIError,++ type MemoryDocument,++ type MemoryEnvironment,++ type MemoryResource,++ type OpenComputerClient,++} from "./api.js";++import { CLIError, structuredError } from "./errors.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;++}++++export interface MemoryEditDraft {++ /** The file holding the user's edited text. */++ path: string;++ discard: () => Promise<void>;++}++++/**++ * Replaces a document's text at the revision that was read. On success the++ * draft file goes; on any failure it stays and the error names it, so an++ * over-limit, unreachable or failing save costs no work.++ */++export async function saveMemoryEdit(++ client: OpenComputerClient,++ input: {++ projectId: string;++ resource: string;++ id: string;++ environment: MemoryEnvironment;++ etag: string;++ text: string;++ summary?: string;++ draft?: MemoryEditDraft;++ },++): Promise<MemoryDocument> {++ const { draft, ...replacement } = input;++ try {++ const { document } = await client.replaceMemoryDocument(replacement);++ await draft?.discard();++ return document;++ } catch (error) {++ const kept = draft++ ? { editedTextPath: draft.path }++ : {};++ const resume = draft++ ? ` Your edited text is kept at ${draft.path}; save it with ` +++ `\`opencomputer memory edit ${input.resource} ${input.id} --text-file ${draft.path}\`.`++ : "";++ if (error instanceof APIError && error.status === 412) {++ const latest = await client++ .memoryDocument(input)++ .catch(() => null);++ throw new CLIError(++ "memory_conflict",++ `${input.resource}/${input.id} changed since you opened it` +++ (latest++ ? ` (now revision ${latest.document.revision}, updated ${latest.document.updatedAt} by ${writerLabel(latest.document)})`++ : "") +++ `; your edit was not saved.`,++ "Run `opencomputer memory show` to read the current text, reconcile, and edit again." +++ resume,++ {++ status: 412,++ ...(latest ? { current: latest.document } : {}),++ ...kept,++ },++ );++ }++ const failure = structuredError(error);++ const details =++ failure.details && typeof failure.details === "object"++ ? (failure.details as Record<string, unknown>)++ : {};++ throw new CLIError(++ failure.code === "payload_too_large" ? "memory_too_large" : failure.code,++ `${input.resource}/${input.id} was not saved: ${failure.message}`,++ failure.hint + resume,++ { ...details, ...kept },++ );++ }++}++++function writerLabel(document: MemoryDocument): string {++ return document.writer.kind === "agent"++ ? `agent ${document.writer.sessionId}`++ : "owner";++}