An open-source, faster Devin alternative
TypeScript
cli: compile memory declarations with the contract module, reject the rest
Igor Zalutski47e833e51d9e
diff --git a/cli/src/memory.ts b/cli/src/memory.tsnew file mode 100644index 00000000..0c695998--- /dev/null+++ b/cli/src/memory.ts@@ -0,0 +1,420 @@+/**+ * The memory declaration contract: what `defineMemory()`, `documentMemory()`+ * and `httpMemory()` accept and the normalized descriptor they produce.+ *+ * This module is shared verbatim by `@opencomputer/agent`+ * (`agent/src/memory.ts`) and the CLI (`cli/src/memory.ts`), where the+ * compiler runs it on the literal declarations it extracts from agent source+ * and inlines its compiled form into the artifact's runtime. The two copies+ * must stay byte-identical; a CLI test enforces it. Keep the module free of+ * imports so it can be inlined.+ */++export const MEMORY_DEFAULT_MAX_BYTES = 8_192;+export const MEMORY_MAX_BYTES_CEILING = 16_384;+export const MEMORY_ID_MAX_LENGTH = 128;+export const HTTP_MEMORY_DEFAULT_PATH = "/memory";+export const HTTP_MEMORY_MAX_TOOLS = 8;+/** Injected into every memory tool's model-facing schema to select a resource. */+export const MEMORY_RESERVED_ARGUMENT = "memory";+/** The built-in document provider's fixed tools, exposed as `memory_<name>`. */+export const DOCUMENT_MEMORY_TOOLS: readonly string[] = Object.freeze([+ "save",+ "read",+ "list",+]);++const MEMORY_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const HTTP_MEMORY_PATH_PATTERN = /^\/(?!\/)[^?#\s]*$/;+const HTTP_MEMORY_TOOL_NAME_PATTERN = /^[a-z0-9_]{1,32}$/;++export interface MemoryReference {+ readonly kind: "memory";+ readonly id: string;+}++/** Bounded text documents stored by OpenComputer. */+export interface DocumentMemoryProvider {+ readonly kind: "document";+ /** Maximum UTF-8 size of each document's text, for every writer. */+ readonly maxBytes: number;+}++export type MemoryToolAccess = "read" | "write";++export type MemoryToolInputSchema = Readonly<Record<string, unknown>>;++/**+ * A tool an HTTP memory endpoint executes. The model sees it as+ * `memory_<name>` with the reserved `memory` argument naming the resource, so+ * `input` may not declare a `memory` property of its own.+ */+export interface HttpMemoryToolDefinition {+ readonly name: string;+ readonly description: string;+ readonly access: MemoryToolAccess;+ /**+ * Only an idempotent write is retried after a transport failure or timeout.+ * Declare it only when the endpoint deduplicates `(partition, operationId)`.+ */+ readonly idempotent: boolean;+ readonly input: MemoryToolInputSchema;+}++/** Recall and tools served by another service through a declared connection. */+export interface HttpMemoryProvider {+ readonly kind: "http";+ readonly connection: string;+ readonly path: string;+ /** Maximum UTF-8 size of recalled text. */+ readonly maxBytes: number;+ readonly tools: readonly HttpMemoryToolDefinition[];+}++export type MemoryProvider = DocumentMemoryProvider | HttpMemoryProvider;++/**+ * A memory resource, registered by the compiler and admitted per session.+ * The same id in every agent of a project names the same resource.+ */+export interface MemoryDefinition extends MemoryReference {+ readonly version: 1;+ /** Model-facing guidance, shown in the resource's tool descriptions. */+ readonly description: string;+ readonly provider: MemoryProvider;+}++export interface MemorySource {+ readonly id: string;+ readonly title?: string;+ readonly revision?: string;+ readonly updatedAt?: string;+}++/**+ * What this model request knows from one bound memory resource. The host+ * resolves it before the render; the shape is the same for every provider.+ * Provider read state stays with the host; it is not part of the projection.+ */+export interface MemoryProjection {+ readonly text: string;+ readonly sources: readonly MemorySource[];+ /** Whether this binding's save tool can commit right now. */+ readonly writable: boolean;+}++export interface DocumentMemoryInput {+ maxBytes?: number;+}++export interface HttpMemoryToolInput {+ name: string;+ description: string;+ access: MemoryToolAccess;+ idempotent?: boolean;+ input: MemoryToolInputSchema;+}++/** A `defineConnection()` result, or the policy the compiler resolved for it. */+export interface HttpMemoryConnection {+ readonly kind: "connection";+ readonly id: string;+ readonly methods?: readonly string[];+ readonly pathPrefix?: string;+}++export interface HttpMemoryInput {+ connection: HttpMemoryConnection;+ path?: string;+ maxBytes?: number;+ tools?: readonly HttpMemoryToolInput[];+}++export interface MemoryDefinitionInput {+ id: string;+ description: string;+ provider?: MemoryProvider;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function deepFreeze<T>(value: T): T {+ if (value && typeof value === "object" && !Object.isFrozen(value)) {+ Object.freeze(value);+ for (const nested of Object.values(value as Record<string, unknown>)) {+ deepFreeze(nested);+ }+ }+ return value;+}++export function memoryId(value: unknown, kind: string): string {+ const id = typeof value === "string" ? value.trim() : "";+ if (!id) throw new Error(`${kind} requires a non-empty id`);+ if (!MEMORY_ID_PATTERN.test(id)) {+ throw new Error(+ `${kind} IDs must use lowercase letters, numbers, and single hyphens`,+ );+ }+ if (id.length > MEMORY_ID_MAX_LENGTH) {+ throw new Error(+ `${kind} IDs must contain at most ${MEMORY_ID_MAX_LENGTH} characters`,+ );+ }+ return id;+}++function memoryMaxBytes(value: unknown, label: string): number {+ if (value === undefined) return MEMORY_DEFAULT_MAX_BYTES;+ if (+ typeof value !== "number" ||+ !Number.isInteger(value) ||+ value < 1 ||+ value > MEMORY_MAX_BYTES_CEILING+ ) {+ throw new Error(+ `${label} maxBytes must be a whole number between 1 and ${MEMORY_MAX_BYTES_CEILING}`,+ );+ }+ return value;+}++function httpMemoryPath(value: unknown, label: string): string {+ if (value === undefined) return HTTP_MEMORY_DEFAULT_PATH;+ if (typeof value !== "string" || !HTTP_MEMORY_PATH_PATTERN.test(value)) {+ throw new Error(+ `${label} path must begin with a single / and contain no query or fragment`,+ );+ }+ return value;+}++function containsSchemaReference(value: unknown): boolean {+ if (Array.isArray(value)) return value.some(containsSchemaReference);+ if (!isRecord(value)) return false;+ return Object.entries(value).some(+ ([key, nested]) => key === "$ref" || containsSchemaReference(nested),+ );+}++function httpMemoryToolInput(+ value: unknown,+ label: string,+): MemoryToolInputSchema {+ if (!isRecord(value)) {+ throw new Error(`${label} input must be a JSON Schema object`);+ }+ if (value.type !== "object") {+ throw new Error(`${label} input must be a JSON Schema with type "object"`);+ }+ if (containsSchemaReference(value)) {+ throw new Error(`${label} input cannot use $ref`);+ }+ const properties = value.properties;+ if (properties !== undefined && !isRecord(properties)) {+ throw new Error(`${label} input properties must be an object`);+ }+ const required = value.required;+ if (+ required !== undefined &&+ (!Array.isArray(required) ||+ required.some((name) => typeof name !== "string"))+ ) {+ throw new Error(`${label} input required must be an array of strings`);+ }+ if (+ (properties &&+ Object.prototype.hasOwnProperty.call(+ properties,+ MEMORY_RESERVED_ARGUMENT,+ )) ||+ (Array.isArray(required) && required.includes(MEMORY_RESERVED_ARGUMENT))+ ) {+ throw new Error(+ `${label} input cannot declare the reserved ${MEMORY_RESERVED_ARGUMENT} argument; OpenComputer adds it to select the resource`,+ );+ }+ let serialized: string | undefined;+ try {+ serialized = JSON.stringify(value);+ } catch {+ serialized = undefined;+ }+ if (serialized === undefined) {+ throw new Error(`${label} input must be JSON-compatible`);+ }+ return deepFreeze(JSON.parse(serialized) as Record<string, unknown>);+}++function httpMemoryTools(+ value: unknown,+ label: string,+): readonly HttpMemoryToolDefinition[] {+ if (value === undefined) return Object.freeze([]);+ if (!Array.isArray(value)) {+ throw new Error(`${label} tools must be an array`);+ }+ if (value.length > HTTP_MEMORY_MAX_TOOLS) {+ throw new Error(+ `${label} may declare at most ${HTTP_MEMORY_MAX_TOOLS} tools`,+ );+ }+ const names = new Set<string>();+ const tools = value.map((tool: unknown): HttpMemoryToolDefinition => {+ if (!isRecord(tool)) {+ throw new Error(`${label} tools must contain tool objects`);+ }+ const name = typeof tool.name === "string" ? tool.name.trim() : "";+ if (!HTTP_MEMORY_TOOL_NAME_PATTERN.test(name)) {+ throw new Error(+ `${label} tool names must use 1 to 32 lowercase letters, numbers, and underscores`,+ );+ }+ const toolLabel = `${label} tool ${name}`;+ if (names.has(name)) {+ throw new Error(`${toolLabel} is declared more than once`);+ }+ names.add(name);+ const description =+ typeof tool.description === "string" ? tool.description.trim() : "";+ if (!description) throw new Error(`${toolLabel} requires a description`);+ if (tool.access !== "read" && tool.access !== "write") {+ throw new Error(`${toolLabel} access must be "read" or "write"`);+ }+ if (tool.idempotent !== undefined && typeof tool.idempotent !== "boolean") {+ throw new Error(`${toolLabel} idempotent must be true or false`);+ }+ return Object.freeze({+ name,+ description,+ access: tool.access,+ idempotent: tool.idempotent === true,+ input: httpMemoryToolInput(tool.input, toolLabel),+ });+ });+ return Object.freeze(tools);+}++/**+ * Normalizes a provider descriptor. Every descriptor a definition carries+ * passes through here, whether it came from `documentMemory()`,+ * `httpMemory()` or was written by hand.+ */+function memoryProvider(value: unknown, label: string): MemoryProvider {+ if (!isRecord(value)) {+ throw new Error(`${label} provider must be documentMemory() or httpMemory()`);+ }+ if (value.kind === "document") {+ return Object.freeze({+ kind: "document" as const,+ maxBytes: memoryMaxBytes(value.maxBytes, label),+ });+ }+ if (value.kind === "http") {+ const connection =+ typeof value.connection === "string" ? value.connection.trim() : "";+ if (!connection) {+ throw new Error(`${label} requires a defineConnection() connection`);+ }+ return Object.freeze({+ kind: "http" as const,+ connection,+ path: httpMemoryPath(value.path, label),+ maxBytes: memoryMaxBytes(value.maxBytes, label),+ tools: httpMemoryTools(value.tools, label),+ });+ }+ throw new Error(`${label} provider must be documentMemory() or httpMemory()`);+}++export function documentMemory(+ input: DocumentMemoryInput = {},+): DocumentMemoryProvider {+ const provider = memoryProvider(+ { kind: "document", maxBytes: input.maxBytes },+ "documentMemory",+ );+ return provider as DocumentMemoryProvider;+}++export function httpMemory(input: HttpMemoryInput): HttpMemoryProvider {+ const connection = input.connection;+ if (+ !isRecord(connection) ||+ typeof connection.id !== "string" ||+ !connection.id+ ) {+ throw new Error("httpMemory requires a defineConnection() connection");+ }+ const provider = memoryProvider(+ {+ kind: "http",+ connection: connection.id,+ path: input.path,+ maxBytes: input.maxBytes,+ tools: input.tools,+ },+ "httpMemory",+ ) as HttpMemoryProvider;+ const policy = connection as HttpMemoryConnection;+ if (policy.pathPrefix && !provider.path.startsWith(policy.pathPrefix)) {+ throw new Error(+ `httpMemory path ${provider.path} is outside connection ${provider.connection} pathPrefix ${policy.pathPrefix}`,+ );+ }+ if (policy.methods && !policy.methods.includes("POST")) {+ throw new Error(+ `httpMemory requires connection ${provider.connection} to allow POST`,+ );+ }+ return provider;+}++export function defineMemory(input: MemoryDefinitionInput): MemoryDefinition {+ const id = memoryId(input.id, "defineMemory");+ const description =+ typeof input.description === "string" ? input.description.trim() : "";+ if (!description) {+ throw new Error(`Memory ${id} requires a non-empty description`);+ }+ const provider =+ input.provider === undefined+ ? documentMemory()+ : memoryProvider(input.provider, `Memory ${id}`);+ return Object.freeze({+ kind: "memory" as const,+ version: 1 as const,+ id,+ description,+ provider,+ });+}++/** The model-facing tool names a provider reserves: `memory_<name>`. */+export function memoryToolNames(provider: MemoryProvider): string[] {+ const names =+ provider.kind === "document"+ ? DOCUMENT_MEMORY_TOOLS+ : provider.tools.map((tool) => tool.name);+ return names.map((name) => `${MEMORY_RESERVED_ARGUMENT}_${name}`);+}++/**+ * The projection the host resolved for the session's binding of `id`, or a+ * render failure when the session has no such binding.+ */+export function memoryProjection(id: string, value: unknown): MemoryProjection {+ if (+ !isRecord(value) ||+ typeof value.text !== "string" ||+ !Array.isArray(value.sources) ||+ typeof value.writable !== "boolean"+ ) {+ throw new Error(+ `Memory ${JSON.stringify(id)} is not bound to this session; create the session with a memory binding for it`,+ );+ }+ return value as unknown as MemoryProjection;+}diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex 5d049110..62f6512b 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -1167,7 +1167,7 @@ export default function Agent() {);await assert.rejects(build(REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory").replace("8_192", "16_385")),- /maxBytes must be a whole number literal between 1 and 16384/,+ /maxBytes must be a whole number between 1 and 16384/,);await assert.rejects(build(REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory").replace('"requirements"', '"Requirements"')),@@ -1210,3 +1210,285 @@ export default function Agent() {await rm(parent, { recursive: true, force: true });}});++test("the compiler rejects memory declarations it cannot register as written", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-memory-literal-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useMemory } from "@opencomputer/agent";+import { memory } from "./memory";++export default function Agent() {+ return useMemory(memory).text;+}+`,+ );+ const build = async (memorySource: string, extra?: [string, string]) => {+ await writeFile(resolve(initialized.agentRoot, "memory.ts"), memorySource);+ if (extra) await writeFile(resolve(initialized.agentRoot, extra[0]), extra[1]);+ return buildAgentArtifact(initialized.agentRoot);+ };+ const declaration = (provider: string) =>+ ` id: "requirements",\n description: "Requirements.",\n provider: ${provider},\n`;++ // Review reproduction: an aliased callee executed a definition the+ // compiler never registered, so the artifact declared no memory.+ await assert.rejects(+ build(`import { defineMemory as declareMemory, documentMemory } from "@opencomputer/agent";++export const memory = declareMemory({+${declaration("documentMemory({ maxBytes: 4_096 })")}});+`),+ /memory\.ts imports defineMemory as declareMemory; the compiler registers memory only from a direct defineMemory\(\) call, so keep its name/,+ );+ await assert.rejects(+ build(+ `import { declareMemory } from "./lib";++export const memory = declareMemory({+${declaration("undefined")}});+`,+ ["lib.ts", 'export { defineMemory as declareMemory } from "@opencomputer/agent";\n'],+ ),+ /lib\.ts exports defineMemory as declareMemory; the compiler registers memory only from a direct defineMemory\(\) call/,+ );+ await rm(resolve(initialized.agentRoot, "lib.ts"));+ await assert.rejects(+ build(`import * as oc from "@opencomputer/agent";++export const memory = oc.defineMemory({+${declaration("oc.documentMemory({ maxBytes: 4_096 })")}});+`),+ /memory\.ts calls oc\.defineMemory\(\); the compiler registers memory only from a direct defineMemory\(\) call, so import defineMemory by name from @opencomputer\/agent/,+ );+ await assert.rejects(+ build(`import { defineMemory } from "@opencomputer/agent";++const declare = defineMemory;+export const memory = declare({+${declaration("undefined")}});+`),+ /memory\.ts uses defineMemory other than as a direct defineMemory\(\) call; the compiler registers memory only from that call, so do not alias, wrap, or shadow it/,+ );++ // Review reproduction: spreading options into the provider registered+ // the default limit while the definition kept 4096.+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++const options = { maxBytes: 4_096 };+export const memory = defineMemory({+${declaration("documentMemory({ ...options })")}});+`),+ /memory\.ts Memory requirements documentMemory\(\) cannot spread options; write each option as a literal property/,+ );++ // Review reproduction: spreading the provider into the declaration+ // registered the default provider.+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++const provider = { provider: documentMemory({ maxBytes: 4_096 }) };+export const memory = defineMemory({+ id: "requirements",+ description: "Requirements.",+ ...provider,+});+`),+ /memory\.ts defineMemory\(\) cannot spread provider; write each option as a literal property/,+ );++ // The same silent default through a shorthand, an accessor, a computed+ // name, or a non-literal argument.+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++const provider = documentMemory({ maxBytes: 4_096 });+export const memory = defineMemory({ id: "requirements", description: "Requirements.", provider });+`),+ /memory\.ts defineMemory\(\) cannot use the shorthand property provider; write provider as a literal property/,+ );+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++export const memory = defineMemory({+ id: "requirements",+ description: "Requirements.",+ get provider() { return documentMemory({ maxBytes: 4_096 }); },+});+`),+ /memory\.ts defineMemory\(\) cannot use methods or accessors/,+ );+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++export const memory = defineMemory({+ id: "requirements",+ description: "Requirements.",+ ["provider"]: documentMemory({ maxBytes: 4_096 }),+});+`),+ /memory\.ts defineMemory\(\) must use static property names/,+ );+ await assert.rejects(+ build(`import { defineMemory } from "@opencomputer/agent";++const options = { id: "requirements", description: "Requirements." };+export const memory = defineMemory(options);+`),+ /memory\.ts defineMemory\(\) requires one object literal argument/,+ );+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++const options = { maxBytes: 4_096 };+export const memory = defineMemory({+${declaration("documentMemory(options)")}});+`),+ /memory\.ts Memory requirements documentMemory\(\) requires one object literal argument/,+ );+ await assert.rejects(+ build(`import { defineMemory, documentMemory } from "@opencomputer/agent";++const LIMIT = 4_096;+export const memory = defineMemory({+${declaration("documentMemory({ maxBytes: LIMIT })")}});+`),+ /memory\.ts Memory requirements documentMemory\(\) maxBytes must be a static JSON value/,+ );++ // Type-only references and unaliased re-exports do not change what runs.+ await writeFile(+ resolve(initialized.agentRoot, "lib.ts"),+ 'export { defineMemory, documentMemory } from "@opencomputer/agent";\n',+ );+ const built = await build(`import type { MemoryDefinition } from "@opencomputer/agent";+import { defineMemory, documentMemory } from "./lib";++type Declared = typeof defineMemory;+export const memory: MemoryDefinition = defineMemory({+${declaration("documentMemory({ maxBytes: 4_096 })")}});+export const declared: Declared | undefined = undefined;+`);+ assert.deepEqual(built.memory, [+ {+ id: "requirements",+ description: "Requirements.",+ provider: { kind: "document", maxBytes: 4096 },+ },+ ]);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("a registered memory declaration is the definition the artifact executes", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-memory-parity-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await writeFile(resolve(initialized.agentRoot, "knowledge.ts"), KNOWLEDGE_MEMORY);+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { defineMemory, documentMemory, useMemory } from "@opencomputer/agent";+export { knowledge } from "./knowledge";++export const requirements = defineMemory({+ id: "requirements",+ description: " Verified requirements and decisions for a workshop, kept for later work. ",+ provider: documentMemory({ maxBytes: 8_192 }),+});+export const notes = defineMemory({ id: "notes", description: "Notes." });++export default function Agent() {+ return useMemory(requirements).text;+}+`,+ );+ const built = await buildAgentArtifact(initialized.agentRoot);+ const runtime = resolve(initialized.agentRoot, ".opencomputer", "runtime");+ const module = (await import(+ `${pathToFileURL(resolve(runtime, "agent.js")).href}?test=${crypto.randomUUID()}`+ )) as Record<string, { kind: string; version: number; id: string; description: string; provider: unknown }>;+ const executed = ["knowledge", "notes", "requirements"].map((name) => {+ const definition = module[name]!;+ assert.equal(definition.kind, "memory");+ assert.equal(definition.version, 1);+ assert.ok(Object.isFrozen(definition));+ assert.ok(Object.isFrozen(definition.provider));+ return JSON.parse(+ JSON.stringify({+ id: definition.id,+ description: definition.description,+ provider: definition.provider,+ }),+ ) as unknown;+ });+ assert.deepEqual(built.memory, executed);+ assert.deepEqual(built.memory, [+ KNOWLEDGE_DECLARATION,+ { id: "notes", description: "Notes.", provider: { kind: "document", maxBytes: 8192 } },+ REQUIREMENTS_DECLARATION,+ ]);++ // The runtime rejects what the compiler rejects: the shim is the same+ // contract module, so a declaration that would not compile does not run.+ const shim = (await import(+ `${pathToFileURL(resolve(runtime, "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`+ )) as {+ defineMemory: (input: unknown) => { provider: { tools?: Array<{ input: Record<string, unknown> }> } };+ documentMemory: (input?: unknown) => unknown;+ httpMemory: (input: unknown) => unknown;+ };+ assert.throws(+ () => shim.documentMemory({ maxBytes: 16_385 }),+ /documentMemory maxBytes must be a whole number between 1 and 16384/,+ );+ assert.throws(+ () => shim.defineMemory({ id: "Requirements", description: "R." }),+ /defineMemory IDs must use lowercase letters, numbers, and single hyphens/,+ );+ assert.throws(+ () =>+ shim.httpMemory({+ connection: { kind: "connection", id: "memory-service", methods: ["GET"] },+ }),+ /httpMemory requires connection memory-service to allow POST/,+ );+ const definition = shim.defineMemory({+ id: "knowledge",+ description: "Facts.",+ provider: shim.httpMemory({+ connection: { kind: "connection", id: "memory-service" },+ tools: [+ {+ name: "remember",+ description: "Save.",+ access: "write",+ input: { type: "object", properties: { fact: { type: "string" } } },+ },+ ],+ }),+ });+ const schema = definition.provider.tools![0]!.input;+ assert.ok(Object.isFrozen(schema));+ assert.ok(Object.isFrozen(schema.properties));+ assert.ok(Object.isFrozen((schema.properties as Record<string, unknown>).fact));+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the CLI's memory contract is the agent package's module", async () => {+ const repo = resolve(import.meta.dirname, "..", "..");+ const packageModule = resolve(repo, "agent", "src", "memory.ts");+ const cliModule = resolve(repo, "cli", "src", "memory.ts");+ assert.equal(+ await readFile(cliModule, "utf8"),+ await readFile(packageModule, "utf8"),+ "cli/src/memory.ts must stay byte-identical to agent/src/memory.ts; the compiler, the runtime shim and @opencomputer/agent share it",+ );+});diff --git a/cli/src/project.ts b/cli/src/project.tsindex 70d12d87..988ed78c 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -8,11 +8,26 @@ import {rm,writeFile,} from "node:fs/promises";+import { readFileSync } from "node:fs";import { basename, dirname, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";import { Cron } from "croner";import { build as bundle } from "esbuild";import ts from "typescript";+import {+ defineMemory,+ documentMemory,+ httpMemory,+ memoryToolNames,+ type DocumentMemoryInput,+ type HttpMemoryConnection,+ type HttpMemoryInput,+ type MemoryDefinition,+ type MemoryDefinitionInput,+ type MemoryProvider,+} from "./memory.js";+export interface AgentManifest {schema: 1;id: string;@@ -31,33 +46,16 @@ export interface BuiltAgentArtifact {elapsedMs: number;}-export interface HttpToolDeclaration {- name: string;- description: string;- access: "read" | "write";- idempotent: boolean;- input: Record<string, unknown>;-}--export type MemoryProviderDeclaration =- | { kind: "document"; maxBytes: number }- | {- kind: "http";- connection: string;- path: string;- maxBytes: number;- tools: HttpToolDeclaration[];- };-/**- * A memory resource as registered with the deployment. The same id in every- * agent of a project names the same resource, so declarations sharing an id- * must agree on the provider and its configuration.+ * A memory resource as registered with the deployment: the executable+ * definition without its `kind` and `version`. The same id in every agent of+ * a project names the same resource, so declarations sharing an id must agree+ * on the provider and its configuration.*/export interface MemoryDeclaration {id: string;description: string;- provider: MemoryProviderDeclaration;+ provider: MemoryProvider;}export interface HttpConnectionManifest {@@ -878,218 +876,215 @@ function definedMcpServers(return definitions.sort((left, right) => left.id.localeCompare(right.id));}-const MEMORY_DEFAULT_MAX_BYTES = 8_192;-const MEMORY_MAX_BYTES_CEILING = 16_384;-const MEMORY_ID_MAX_LENGTH = 128;-const HTTP_MEMORY_DEFAULT_PATH = "/memory";-const HTTP_MEMORY_MAX_TOOLS = 8;-const HTTP_MEMORY_TOOL_NAME_PATTERN = /^[a-z0-9_]{1,32}$/;-/** Injected into every memory tool's model-facing schema to select the resource. */-const MEMORY_RESERVED_ARGUMENT = "memory";-/** The built-in document provider's fixed tools, exposed as `memory_<name>`. */-const DOCUMENT_MEMORY_TOOLS = ["save", "read", "list"];--/** The identifier a property references, for `connection: name` and `{ connection }` alike. */-function objectPropertyIdentifier(- object: ts.ObjectLiteralExpression,- name: string,-): string | undefined {- for (const property of object.properties) {- if (- ts.isShorthandPropertyAssignment(property) &&- property.name.text === name- ) {- return property.name.text;- }- }- const expression = objectProperty(object, name);- return expression && ts.isIdentifier(expression) ? expression.text : undefined;-}--function memoryMaxBytesValue(- expression: ts.Expression | undefined,- label: string,-): number {- if (!expression) return MEMORY_DEFAULT_MAX_BYTES;- const value = ts.isNumericLiteral(expression)- ? Number(expression.text)- : Number.NaN;- if (!Number.isInteger(value) || value < 1 || value > MEMORY_MAX_BYTES_CEILING) {- throw new Error(- `${label} maxBytes must be a whole number literal between 1 and ${MEMORY_MAX_BYTES_CEILING}`,- );- }- return value;-}+/**+ * The memory authoring functions the compiler registers from. A declaration+ * only counts when one of them is called directly by its own name on literal+ * arguments: that is what lets the compiler run the same `defineMemory()` the+ * artifact runs and emit the executable definition itself. Any other use+ * (an alias, a namespace member, a wrapper, a re-export under another name)+ * would let the definition execute without being registered, or register+ * something the definition does not mean, so the build rejects it.+ */+const MEMORY_AUTHORING_FUNCTIONS = new Set([+ "defineMemory",+ "documentMemory",+ "httpMemory",+]);-function containsSchemaReference(value: unknown): boolean {- if (Array.isArray(value)) return value.some(containsSchemaReference);- if (!value || typeof value !== "object") return false;- return Object.entries(value as Record<string, unknown>).some(- ([key, nested]) => key === "$ref" || containsSchemaReference(nested),+function isTypeOnlyContext(node: ts.Node): boolean {+ return (+ ts.isTypeNode(node) ||+ (ts.isImportDeclaration(node) && !!node.importClause?.isTypeOnly) ||+ (ts.isExportDeclaration(node) && node.isTypeOnly) ||+ (ts.isImportSpecifier(node) && node.isTypeOnly) ||+ (ts.isExportSpecifier(node) && node.isTypeOnly));}-function isRecord(value: unknown): value is Record<string, unknown> {- return !!value && typeof value === "object" && !Array.isArray(value);+/**+ * Rejects every use of a memory authoring function other than an unaliased+ * import or export and a direct call, so a definition that executes is one+ * the compiler registered and vice versa.+ */+function assertMemoryFunctionsCalledDirectly(+ file: ts.SourceFile,+ path: string,+): void {+ const visit = (node: ts.Node): void => {+ if (isTypeOnlyContext(node)) return;+ if (ts.isIdentifier(node) && MEMORY_AUTHORING_FUNCTIONS.has(node.text)) {+ const name = node.text;+ const parent = node.parent;+ const direct =+ (ts.isCallExpression(parent) && parent.expression === node) ||+ ((ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent)) &&+ parent.name === node &&+ parent.propertyName === undefined);+ if (!direct) {+ if (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent)) {+ const verb = ts.isImportSpecifier(parent) ? "imports" : "exports";+ const imported = (parent.propertyName ?? parent.name).text;+ throw new Error(+ `${path} ${verb} ${imported} as ${parent.name.text}; the compiler registers memory only from a direct ${name}() call, so keep its name`,+ );+ }+ if (ts.isPropertyAccessExpression(parent) && parent.name === node) {+ throw new Error(+ `${path} calls ${parent.expression.getText(file)}.${name}(); the compiler registers memory only from a direct ${name}() call, so import ${name} by name from @opencomputer/agent`,+ );+ }+ throw new Error(+ `${path} uses ${name} other than as a direct ${name}() call; the compiler registers memory only from that call, so do not alias, wrap, or shadow it`,+ );+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(file);}-function httpMemoryTools(value: unknown, label: string): HttpToolDeclaration[] {- if (value === undefined) return [];- if (!Array.isArray(value)) {- throw new Error(`${label} tools must be an array literal`);- }- if (value.length > HTTP_MEMORY_MAX_TOOLS) {- throw new Error(`${label} may declare at most ${HTTP_MEMORY_MAX_TOOLS} tools`);- }- const names = new Set<string>();- return value.map((entry): HttpToolDeclaration => {- if (!isRecord(entry)) {- throw new Error(`${label} tools must contain object literals`);- }- const name = typeof entry.name === "string" ? entry.name.trim() : "";- if (!HTTP_MEMORY_TOOL_NAME_PATTERN.test(name)) {+/**+ * The properties of an object literal as name/value pairs, rejecting every+ * form whose value the compiler cannot read: spreads, shorthand, methods,+ * accessors and computed names. `identifiers` names properties whose value is+ * an identifier reference rather than a literal, allowed in shorthand form.+ */+function literalObjectEntries(+ object: ts.ObjectLiteralExpression,+ label: string,+ identifiers: readonly string[] = [],+): Array<[string, ts.Expression]> {+ return object.properties.map((property): [string, ts.Expression] => {+ if (ts.isSpreadAssignment(property)) {throw new Error(- `${label} tool names must use 1 to 32 lowercase letters, numbers, and underscores`,+ `${label} cannot spread ${property.expression.getText()}; write each option as a literal property`,);}- const toolLabel = `${label} tool ${name}`;- if (names.has(name)) {- throw new Error(`${toolLabel} is declared more than once`);- }- names.add(name);- const description =- typeof entry.description === "string" ? entry.description.trim() : "";- if (!description) throw new Error(`${toolLabel} requires a description`);- if (entry.access !== "read" && entry.access !== "write") {- throw new Error(`${toolLabel} access must be "read" or "write"`);- }- if (entry.idempotent !== undefined && typeof entry.idempotent !== "boolean") {- throw new Error(`${toolLabel} idempotent must be true or false`);- }- const input = entry.input;- if (!isRecord(input)) {- throw new Error(`${toolLabel} input must be a JSON Schema object`);- }- if (input.type !== "object") {+ if (ts.isShorthandPropertyAssignment(property)) {+ const name = property.name.text;+ if (identifiers.includes(name)) return [name, property.name];throw new Error(- `${toolLabel} input must be a JSON Schema with type "object"`,+ `${label} cannot use the shorthand property ${name}; write ${name} as a literal property`,);}- if (containsSchemaReference(input)) {- throw new Error(`${toolLabel} input cannot use $ref`);- }- if (input.properties !== undefined && !isRecord(input.properties)) {- throw new Error(`${toolLabel} input properties must be an object`);- }- if (- input.required !== undefined &&- (!Array.isArray(input.required) ||- input.required.some((item) => typeof item !== "string"))- ) {- throw new Error(`${toolLabel} input required must be an array of strings`);- }- if (- (isRecord(input.properties) &&- Object.prototype.hasOwnProperty.call(- input.properties,- MEMORY_RESERVED_ARGUMENT,- )) ||- (Array.isArray(input.required) &&- input.required.includes(MEMORY_RESERVED_ARGUMENT))- ) {+ if (!ts.isPropertyAssignment(property)) {throw new Error(- `${toolLabel} input cannot declare the reserved ${MEMORY_RESERVED_ARGUMENT} argument; OpenComputer adds it to select the resource`,+ `${label} cannot use methods or accessors; write each option as a literal property`,);}- return {- name,- description,- access: entry.access,- idempotent: entry.idempotent === true,- input,- };+ return [+ staticPropertyName(property.name, label),+ property.initializer,+ ];});}-function memoryProviderDeclaration(- expression: ts.Expression | undefined,- id: string,- connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,-): MemoryProviderDeclaration {- const label = `Memory ${id}`;- if (!expression) {- return { kind: "document", maxBytes: MEMORY_DEFAULT_MAX_BYTES };- }+/** The single object-literal argument of an authoring call, or none. */+function literalCallArgument(+ call: ts.CallExpression,+ label: string,+): ts.ObjectLiteralExpression | undefined {+ if (call.arguments.length === 0) return undefined;+ const argument = call.arguments[0];if (- !ts.isCallExpression(expression) ||- !ts.isIdentifier(expression.expression) ||- (expression.expression.text !== "documentMemory" &&- expression.expression.text !== "httpMemory")+ call.arguments.length !== 1 ||+ !argument ||+ !ts.isObjectLiteralExpression(argument)) {- throw new Error(- `${label} provider must be an inline documentMemory() or httpMemory() call`,- );- }- const provider = expression.expression.text;- const input = expression.arguments[0];- if (input !== undefined && !ts.isObjectLiteralExpression(input)) {- throw new Error(`${label} ${provider}() requires an object literal`);+ throw new Error(`${label} requires one object literal argument`);}- if (provider === "documentMemory") {- return {- kind: "document",- maxBytes: memoryMaxBytesValue(- input && objectProperty(input, "maxBytes"),- label,- ),- };- }- if (!input) {- throw new Error(`${label} httpMemory() requires a connection`);- }- const connectionName = objectPropertyIdentifier(input, "connection");- if (!connectionName) {+ return argument;+}++function memoryConnectionPolicy(+ expression: ts.Expression,+ label: string,+ connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,+): HttpMemoryConnection {+ if (!ts.isIdentifier(expression)) {throw new Error(`${label} connection must reference a defineConnection() binding`,);}- const connection = connectionBindings.get(connectionName);+ const connection = connectionBindings.get(expression.text);if (!connection) {throw new Error(- `${label} references unknown connection ${connectionName}`,+ `${label} references unknown connection ${expression.text}`,);}- const pathExpression = objectProperty(input, "path");- const path = pathExpression- ? literalStringValue(pathExpression, `${label} path`)- : HTTP_MEMORY_DEFAULT_PATH;- if (!/^\/(?!\/)[^?#\s]*$/.test(path)) {+ return {+ kind: "connection",+ id: connection.id,+ ...(connection.methods ? { methods: connection.methods } : {}),+ ...(connection.pathPrefix ? { pathPrefix: connection.pathPrefix } : {}),+ };+}++/** Runs a contract function on compile-time input, naming the file on error. */+function inSourceFile<T>(path: string, evaluate: () => T): T {+ try {+ return evaluate();+ } catch (error) {throw new Error(- `${label} path must begin with a single / and contain no query or fragment`,+ `${path} ${error instanceof Error ? error.message : String(error)}`,);}- if (connection.pathPrefix && !path.startsWith(connection.pathPrefix)) {+}++/**+ * The provider a declaration names, produced by running `documentMemory()`+ * or `httpMemory()` on the literal options at the call site.+ */+function memoryProviderValue(+ expression: ts.Expression,+ path: string,+ declaration: string,+ connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,+): MemoryProvider {+ if (+ !ts.isCallExpression(expression) ||+ !ts.isIdentifier(expression.expression) ||+ (expression.expression.text !== "documentMemory" &&+ expression.expression.text !== "httpMemory")+ ) {throw new Error(- `${label} path ${path} is outside connection ${connection.id} pathPrefix ${connection.pathPrefix}`,+ `${path} ${declaration} provider must be an inline documentMemory() or httpMemory() call`,);}- if (connection.methods && !connection.methods.includes("POST")) {+ const callee = expression.expression.text;+ const label = `${path} ${declaration} ${callee}()`;+ const argument = literalCallArgument(expression, label);+ if (callee === "documentMemory") {+ const input: Record<string, unknown> = {};+ for (const [name, value] of argument+ ? literalObjectEntries(argument, label)+ : []) {+ input[name] = staticJsonValue(value, `${label} ${name}`);+ }+ return inSourceFile(path, () =>+ documentMemory(input as DocumentMemoryInput),+ );+ }+ if (!argument) {+ throw new Error(`${label} requires a connection`);+ }+ const input: Record<string, unknown> = {};+ for (const [name, value] of literalObjectEntries(argument, label, [+ "connection",+ ])) {+ input[name] =+ name === "connection"+ ? memoryConnectionPolicy(value, label, connectionBindings)+ : staticJsonValue(value, `${label} ${name}`);+ }+ if (!input.connection) {throw new Error(- `${label} requires connection ${connection.id} to allow POST`,+ `${label} connection must reference a defineConnection() binding`,);}- const toolsExpression = objectProperty(input, "tools");- return {- kind: "http",- connection: connection.id,- path,- maxBytes: memoryMaxBytesValue(objectProperty(input, "maxBytes"), label),- tools: httpMemoryTools(- toolsExpression && staticJsonValue(toolsExpression, `${label} tools`),- label,- ),- };+ return inSourceFile(path, () =>+ httpMemory(input as unknown as HttpMemoryInput),+ );}function definedMemory(@@ -1098,6 +1093,7 @@ function definedMemory(connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,): MemoryDeclaration[] {const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ assertMemoryFunctionsCalledDirectly(file, path);const declarations: MemoryDeclaration[] = [];const visit = (node: ts.Node): void => {if (@@ -1105,31 +1101,32 @@ function definedMemory(ts.isIdentifier(node.expression) &&node.expression.text === "defineMemory") {- const input = node.arguments[0];- if (!input || !ts.isObjectLiteralExpression(input)) {- throw new Error(`${path} defineMemory() requires an object literal`);- }- const id = literalStringValue(objectProperty(input, "id"), "memory id");- if (!AGENT_ID_PATTERN.test(id) || id.length > MEMORY_ID_MAX_LENGTH) {- throw new Error(- `Memory id ${JSON.stringify(id)} must use lowercase letters, numbers, and single hyphens, at most ${MEMORY_ID_MAX_LENGTH} characters`,- );+ const label = `${path} defineMemory()`;+ const argument = literalCallArgument(node, label);+ if (!argument) {+ throw new Error(`${label} requires one object literal argument`);}- const description = literalStringValue(- objectProperty(input, "description"),- `Memory ${id} description`,- ).trim();- if (!description) {- throw new Error(`Memory ${id} requires a non-empty description`);+ const input: Record<string, unknown> = {};+ const entries = literalObjectEntries(argument, label);+ const idEntry = entries.find(([name]) => name === "id");+ const id = idEntry+ ? staticJsonValue(idEntry[1], `${label} id`)+ : undefined;+ const declaration =+ typeof id === "string" && id ? `Memory ${id}` : "defineMemory()";+ for (const [name, value] of entries) {+ input[name] =+ name === "provider"+ ? memoryProviderValue(value, path, declaration, connectionBindings)+ : staticJsonValue(value, `${label} ${name}`);}+ const definition: MemoryDefinition = inSourceFile(path, () =>+ defineMemory(input as unknown as MemoryDefinitionInput),+ );declarations.push({- id,- description,- provider: memoryProviderDeclaration(- objectProperty(input, "provider"),- id,- connectionBindings,- ),+ id: definition.id,+ description: definition.description,+ provider: definition.provider,});}ts.forEachChild(node, visit);@@ -1138,15 +1135,6 @@ function definedMemory(return declarations;}-/** The model-facing tool names a declaration reserves. */-export function memoryToolNames(declaration: MemoryDeclaration): string[] {- const names =- declaration.provider.kind === "document"- ? DOCUMENT_MEMORY_TOOLS- : declaration.provider.tools.map((tool) => tool.name);- return names.map((name) => `${MEMORY_RESERVED_ARGUMENT}_${name}`);-}-/*** Deduplicates declarations by id. Declarations sharing an id name the same* resource, so they must agree byte for byte; a difference is a build error@@ -2085,8 +2073,18 @@ function staticModelSelections();}+/**+ * The compiled memory contract, inlined into the runtime so the artifact's+ * defineMemory() is the same code the compiler ran on the declaration.+ */+const MEMORY_CONTRACT_SOURCE = readFileSync(+ fileURLToPath(new URL("./memory.js", import.meta.url)),+ "utf8",+).replace(/^\/\/# sourceMappingURL=.*$/m, "");+function agentApiRuntimeSource(): string {- return `function hooks() {+ return `${MEMORY_CONTRACT_SOURCE}+function hooks() {const value = globalThis[Symbol.for("opencomputer.agent-hooks")];if (!value) throw new Error("OpenComputer hooks can only run while rendering an agent");return value;@@ -2179,35 +2177,13 @@ export const publishOutbox = async (outbox, input) => {if (!response.ok) throw new Error("Outbox publish failed with status " + response.status);return await response.json();};-// Memory declarations are validated by the compiler before this runs; the-// runtime only normalizes defaults so a definition equals its manifest entry.-const MEMORY_DEFAULT_MAX_BYTES = 8192;-export const documentMemory = (input = {}) => Object.freeze({ kind: "document", maxBytes: input.maxBytes ?? MEMORY_DEFAULT_MAX_BYTES });-export const httpMemory = (input) => Object.freeze({- kind: "http",- connection: id(input.connection && input.connection.id, "httpMemory connection"),- path: input.path || "/memory",- maxBytes: input.maxBytes ?? MEMORY_DEFAULT_MAX_BYTES,- tools: Object.freeze((input.tools || []).map((tool) => Object.freeze({ ...tool, idempotent: tool.idempotent === true }))),-});-export const defineMemory = (input) => Object.freeze({- kind: "memory",- version: 1,- id: id(input.id, "defineMemory"),- description: String(input.description).trim(),- provider: input.provider || documentMemory(),-});// The host resolves every session binding before the render and exposes the// projections on its render scope as scope.memory[id]; the hook returns one// and the host records the id in scope.selectedMemory, returned to it as// selectedMemory next to enabledTools. An unbound id fails the render here.export const useMemory = (memory) => {- const memoryId = id(typeof memory === "string" ? memory : memory && memory.id, "useMemory");- const projection = hooks().useMemory(memoryId);- if (!projection || typeof projection !== "object" || typeof projection.text !== "string" || !Array.isArray(projection.sources) || typeof projection.writable !== "boolean") {- throw new Error("Memory " + JSON.stringify(memoryId) + " is not bound to this session; create the session with a memory binding for it");- }- return projection;+ const resource = memoryId(typeof memory === "string" ? memory : memory && memory.id, "useMemory");+ return memoryProjection(resource, hooks().useMemory(resource));};export const useInput = () => hooks().useInput();export const useCurrentInput = useInput;@@ -2504,7 +2480,7 @@ the product or support surface presented to users.}}for (const declaration of memory) {- const collision = memoryToolNames(declaration).find((name) =>+ const collision = memoryToolNames(declaration.provider).find((name) =>tools.includes(name),);if (collision) {