Skip to content

An open-source, faster Devin alternative

TypeScript

agent: defineMemory, documentMemory, httpMemory and useMemory

Igor Zalutskif21fd34f3ede
diff --git a/.github/workflows/publish-opencomputer-packages.yml b/.github/workflows/publish-opencomputer-packages.yml
index 9f5faf11..bb472bda 100644
--- a/.github/workflows/publish-opencomputer-packages.yml
+++ b/.github/workflows/publish-opencomputer-packages.yml
@@ -47,11 +47,11 @@ jobs:
- name: Verify package version contract
run: node scripts/check-opencomputer-package-contract.mjs
- - name: Install and build agent package
+ - name: Install and test agent package
working-directory: agent
run: |
npm ci
- npm run build
+ npm test
- name: Install and test CLI package
working-directory: cli
diff --git a/agent/README.md b/agent/README.md
index 7178109b..bcd0a796 100644
--- a/agent/README.md
+++ b/agent/README.md
@@ -26,6 +26,10 @@ describe that call; they do not perform I/O or run the durable agent loop.
- `useTool()` and `useSubagent()` select declared capabilities.
- `useSessionData()` reads the current durable session-data snapshot.
- `useMcpServer()` conditionally selects a declared MCP server.
+- `useMemory()` reads the projection of a memory resource bound to the
+ session (`text`, `sources`, `writable`) and selects its tools. Declare the
+ resource with `defineMemory()`; `documentMemory()` is the default provider
+ and `httpMemory()` delegates recall and tools to a declared connection.
Use `defineMcpServer()` for stable MCP declarations. Never put credentials
directly in these declarations: OpenComputer resolves referenced secrets
diff --git a/agent/package-lock.json b/agent/package-lock.json
index 9297feb4..2b732f73 100644
--- a/agent/package-lock.json
+++ b/agent/package-lock.json
@@ -1,22 +1,33 @@
{
"name": "@opencomputer/agent",
- "version": "0.5.2",
+ "version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/agent",
- "version": "0.5.2",
+ "version": "0.6.0",
"dependencies": {
"croner": "^9.1.0"
},
"devDependencies": {
+ "@types/node": "^24.0.0",
"typescript": "^5.9.0"
},
"engines": {
"node": ">=22.0.0"
}
},
+ "node_modules/@types/node": {
+ "version": "24.13.4",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.4.tgz",
+ "integrity": "sha512-YJ7EqCstVTzIr0fMr7qul/977en+pQHrfmuKIo6Zr9i75Be21dr3MovcfvGtyvi2HAUrRerWps5sMO9I7WaxDw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.18.0"
+ }
+ },
"node_modules/croner": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/croner/-/croner-9.1.0.tgz",
@@ -39,6 +50,13 @@
"engines": {
"node": ">=14.17"
}
+ },
+ "node_modules/undici-types": {
+ "version": "7.18.2",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+ "dev": true,
+ "license": "MIT"
}
}
}
diff --git a/agent/package.json b/agent/package.json
index 96d76d5e..07eb1b0d 100644
--- a/agent/package.json
+++ b/agent/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/agent",
- "version": "0.5.3",
+ "version": "0.6.0",
"description": "Reactive agent authoring API for OpenComputer.",
"type": "module",
"main": "./dist/index.js",
@@ -17,7 +17,8 @@
],
"scripts": {
"build": "tsc -p tsconfig.json",
- "prepack": "npm run build"
+ "prepack": "npm run build",
+ "test": "npm run build && node --test dist/*.test.js"
},
"engines": {
"node": ">=22.0.0"
@@ -31,7 +32,8 @@
"directory": "agent"
},
"devDependencies": {
- "typescript": "^5.9.0"
+ "typescript": "^5.9.0",
+ "@types/node": "^24.0.0"
},
"dependencies": {
"croner": "^9.1.0"
diff --git a/agent/src/index.test.ts b/agent/src/index.test.ts
new file mode 100644
index 00000000..1209ddf2
--- /dev/null
+++ b/agent/src/index.test.ts
@@ -0,0 +1,320 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ bearer,
+ defineConnection,
+ defineMemory,
+ documentMemory,
+ httpMemory,
+ useMemory,
+ useSecret,
+ type MemoryProjection,
+} from "./index.js";
+
+const HOOKS = Symbol.for("opencomputer.agent-hooks");
+
+/**
+ * Mirrors the host's render worker: a per-render scope with the projections
+ * the host resolved, keyed by resource id, and the ids the render selected.
+ */
+function renderWith<T>(
+ memory: Record<string, MemoryProjection>,
+ render: () => T,
+): { result: T; selectedMemory: string[] } {
+ const scope = { memory, selectedMemory: new Set<string>() };
+ const globals = globalThis as Record<PropertyKey, unknown>;
+ globals[HOOKS] = {
+ useMemory(id: string) {
+ const projection = scope.memory[id];
+ if (projection) scope.selectedMemory.add(id);
+ return projection;
+ },
+ };
+ try {
+ return { result: render(), selectedMemory: [...scope.selectedMemory].sort() };
+ } finally {
+ delete globals[HOOKS];
+ }
+}
+
+test("defineMemory returns a frozen document declaration by default", () => {
+ const memory = defineMemory({
+ id: "requirements",
+ description: " Verified requirements for a workshop. ",
+ });
+ assert.deepEqual(memory, {
+ kind: "memory",
+ version: 1,
+ id: "requirements",
+ description: "Verified requirements for a workshop.",
+ provider: { kind: "document", maxBytes: 8192 },
+ });
+ assert.ok(Object.isFrozen(memory));
+ assert.ok(Object.isFrozen(memory.provider));
+ assert.equal(JSON.parse(JSON.stringify(memory)).provider.maxBytes, 8192);
+});
+
+test("documentMemory validates maxBytes at definition time", () => {
+ assert.deepEqual(documentMemory({ maxBytes: 16_384 }), {
+ kind: "document",
+ maxBytes: 16_384,
+ });
+ for (const maxBytes of [0, -1, 1.5, 16_385, Number.NaN]) {
+ assert.throws(
+ () => documentMemory({ maxBytes }),
+ /maxBytes must be a whole number between 1 and 16384/,
+ );
+ }
+});
+
+test("defineMemory applies the framework identifier rules", () => {
+ for (const id of ["", " ", "Requirements", "notes_v2", "-notes", "a--b"]) {
+ assert.throws(() => defineMemory({ id, description: "x" }));
+ }
+ assert.throws(
+ () => defineMemory({ id: "a".repeat(129), description: "x" }),
+ /at most 128 characters/,
+ );
+ assert.throws(
+ () => defineMemory({ id: "notes", description: " " }),
+ /requires a non-empty description/,
+ );
+});
+
+const connection = defineConnection({
+ id: "memory-service",
+ origin: "https://memory.example.com",
+ methods: ["POST"],
+ pathPrefix: "/oc-memory",
+ headers: { Authorization: bearer(useSecret("MEMORY_TOKEN")) },
+});
+
+test("httpMemory serializes the connection id, path, limit, and tools", () => {
+ const provider = httpMemory({
+ connection,
+ path: "/oc-memory",
+ tools: [
+ {
+ name: "remember",
+ description: "Save a verified fact for future work.",
+ access: "write",
+ input: {
+ type: "object",
+ properties: { fact: { type: "string", maxLength: 2_000 } },
+ required: ["fact"],
+ additionalProperties: false,
+ },
+ },
+ ],
+ });
+ assert.deepEqual(JSON.parse(JSON.stringify(provider)), {
+ kind: "http",
+ connection: "memory-service",
+ path: "/oc-memory",
+ maxBytes: 8192,
+ tools: [
+ {
+ name: "remember",
+ description: "Save a verified fact for future work.",
+ access: "write",
+ idempotent: false,
+ input: {
+ type: "object",
+ properties: { fact: { type: "string", maxLength: 2_000 } },
+ required: ["fact"],
+ additionalProperties: false,
+ },
+ },
+ ],
+ });
+ assert.ok(Object.isFrozen(provider.tools));
+ assert.ok(Object.isFrozen(provider.tools[0]));
+});
+
+test("httpMemory defaults the path and tools and keeps them inside the connection", () => {
+ const open = defineConnection({
+ id: "open-memory",
+ origin: "https://memory.example.com",
+ });
+ assert.deepEqual(httpMemory({ connection: open }), {
+ kind: "http",
+ connection: "open-memory",
+ path: "/memory",
+ maxBytes: 8192,
+ tools: [],
+ });
+ assert.throws(
+ () => httpMemory({ connection }),
+ /outside connection memory-service pathPrefix \/oc-memory/,
+ );
+ const readOnly = defineConnection({
+ id: "read-only",
+ origin: "https://memory.example.com",
+ methods: ["GET"],
+ });
+ assert.throws(
+ () => httpMemory({ connection: readOnly }),
+ /requires connection read-only to allow POST/,
+ );
+ for (const path of ["memory", "//memory", "/memory?x=1", "/memory#top", "/a b"]) {
+ assert.throws(
+ () => httpMemory({ connection: open, path }),
+ /must begin with a single \/ and contain no query or fragment/,
+ );
+ }
+ assert.throws(
+ () => httpMemory({ connection: open, maxBytes: 20_000 }),
+ /maxBytes must be a whole number between 1 and 16384/,
+ );
+ assert.throws(
+ () => httpMemory({ connection: undefined as never }),
+ /requires a defineConnection\(\) connection/,
+ );
+});
+
+test("httpMemory validates tool declarations", () => {
+ const open = defineConnection({
+ id: "open-memory",
+ origin: "https://memory.example.com",
+ });
+ const tool: Record<string, unknown> = {
+ name: "remember",
+ description: "Save a fact.",
+ access: "write",
+ input: { type: "object", properties: {} },
+ };
+ const declare = (tools: Array<Record<string, unknown>>) =>
+ httpMemory({ connection: open, tools: tools as never });
+ for (const name of ["", "Remember", "re-member", "a".repeat(33)]) {
+ assert.throws(
+ () => declare([{ ...tool, name }]),
+ /tool names must use 1 to 32 lowercase letters, numbers, and underscores/,
+ );
+ }
+ assert.throws(() => declare([tool, tool]), /remember is declared more than once/);
+ assert.throws(
+ () => declare(Array.from({ length: 9 }, (_, i) => ({ ...tool, name: `t${i}` }))),
+ /at most 8 tools/,
+ );
+ assert.throws(() => declare([{ ...tool, description: " " }]), /requires a description/);
+ assert.throws(
+ () => declare([{ ...tool, access: "admin" }]),
+ /access must be "read" or "write"/,
+ );
+ assert.throws(
+ () => declare([{ ...tool, idempotent: "yes" }]),
+ /idempotent must be true or false/,
+ );
+ assert.equal(declare([{ ...tool, idempotent: true }]).tools[0]!.idempotent, true);
+ assert.throws(
+ () => declare([{ ...tool, input: { type: "string" } }]),
+ /input must be a JSON Schema with type "object"/,
+ );
+ assert.throws(() => declare([{ ...tool, input: undefined }]), /input must be a JSON Schema object/);
+ assert.throws(
+ () => declare([{ ...tool, input: { type: "object", properties: { a: { $ref: "#/x" } } } }]),
+ /input cannot use \$ref/,
+ );
+});
+
+test("httpMemory rejects the reserved memory argument in tool input", () => {
+ const open = defineConnection({
+ id: "open-memory",
+ origin: "https://memory.example.com",
+ });
+ const reserved = /cannot declare the reserved memory argument/;
+ assert.throws(
+ () =>
+ httpMemory({
+ connection: open,
+ tools: [
+ {
+ name: "search",
+ description: "Search.",
+ access: "read",
+ input: {
+ type: "object",
+ properties: { memory: { type: "string" }, query: { type: "string" } },
+ },
+ },
+ ],
+ }),
+ reserved,
+ );
+ assert.throws(
+ () =>
+ httpMemory({
+ connection: open,
+ tools: [
+ {
+ name: "search",
+ description: "Search.",
+ access: "read",
+ input: { type: "object", required: ["memory"] },
+ },
+ ],
+ }),
+ reserved,
+ );
+});
+
+test("defineMemory rejects providers that are not descriptors", () => {
+ assert.throws(
+ () =>
+ defineMemory({
+ id: "notes",
+ description: "Notes.",
+ provider: { kind: "redis" } as never,
+ }),
+ /provider must be documentMemory\(\) or httpMemory\(\)/,
+ );
+});
+
+test("useMemory reads the host projection and records the selection", () => {
+ const requirements = defineMemory({
+ id: "requirements",
+ description: "Requirements.",
+ });
+ const projection: MemoryProjection = {
+ text: "Node.js 22, no paid services.",
+ sources: [
+ {
+ id: "workshop",
+ title: "Workshop requirements",
+ revision: "r2",
+ updatedAt: "2026-09-10T12:00:00.000Z",
+ },
+ ],
+ writable: true,
+ };
+ const { result, selectedMemory } = renderWith(
+ { requirements: projection, budget: { text: "", sources: [], writable: false } },
+ () => useMemory(requirements),
+ );
+ assert.equal(result, projection);
+ assert.deepEqual(selectedMemory, ["requirements"]);
+ assert.deepEqual(
+ renderWith({ requirements: projection }, () => useMemory("requirements")).result,
+ projection,
+ );
+});
+
+test("useMemory fails a render whose session has no binding for the resource", () => {
+ assert.throws(
+ () => renderWith({}, () => useMemory("requirements")),
+ /Memory "requirements" is not bound to this session/,
+ );
+ assert.throws(
+ () =>
+ renderWith(
+ { requirements: { text: "x" } as never },
+ () => useMemory("requirements"),
+ ),
+ /Memory "requirements" is not bound to this session/,
+ );
+ assert.throws(() => renderWith({}, () => useMemory("Not Valid")));
+ assert.throws(
+ () => useMemory("requirements"),
+ /hooks can only run while rendering an agent/,
+ );
+});
diff --git a/agent/src/index.ts b/agent/src/index.ts
index 841f15da..3da96294 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -287,7 +287,10 @@ export type ToolInputSchema = Readonly<Record<string, unknown>>;
export interface ToolExecutionContext {
readonly input: Record<string, unknown>;
readonly sessionId: string;
+ /** The assistant message that emitted this call. */
readonly messageId: string;
+ /** The host-assigned id of this tool call, unique within the session. */
+ readonly toolCallId: string;
readonly agentId: string;
readonly signal?: AbortSignal;
reportProgress(metadata: Readonly<Record<string, DataValue>>): Promise<void>;
@@ -305,6 +308,95 @@ export interface ToolDefinition<
run(context: ToolExecutionContext): Output | Promise<Output>;
}
+export interface MemoryReference extends ResourceReference {
+ readonly kind: "memory";
+}
+
+/** 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";
+
+/**
+ * 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: ToolInputSchema;
+}
+
+/** 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.
+ */
+export interface MemoryProjection {
+ readonly text: string;
+ readonly sources: readonly MemorySource[];
+ /** Provider read state the host retains for this request's tools; opaque. */
+ readonly cursor?: string;
+ /** Whether this binding's save tool can commit right now. */
+ readonly writable: boolean;
+}
+
+/**
+ * Implemented by the host that renders the agent. The host renders inside an
+ * isolated worker with a per-render `scope`, sets this object on
+ * `globalThis[Symbol.for("opencomputer.agent-hooks")]`, and clears the scope
+ * when the render returns. The scope fields each hook reads or writes:
+ *
+ * - `useInput()` reads `scope.input`.
+ * - `useSessionData(key)` reads `scope.state[key]`.
+ * - `useTool(id)` adds to `scope.tools`; returned as `enabledTools`.
+ * - `useMemory(id)` reads `scope.memory[id]`, the projection the host
+ * resolved for the session binding with that resource id (absent when the
+ * session has no binding for it), and adds the id to
+ * `scope.selectedMemory`, returned sorted as `selectedMemory` next to
+ * `enabledTools`. The selection is what routes memory tools and their
+ * `memory` argument for the model request this render produced.
+ */
interface AgentHooks {
useInput(): Readonly<AgentInput>;
useModel(model: ModelSelection): void;
@@ -312,6 +404,7 @@ interface AgentHooks {
useSubagent(agent: string | ResourceReference): void;
useSessionData<T extends DataValue>(key: string): T | undefined;
useMcpServer(server: string | ResourceReference): void;
+ useMemory(memory: string): MemoryProjection | undefined;
}
function hooks(): AgentHooks {
@@ -870,6 +963,240 @@ export function defineTool<Output extends DataValue = DataValue>(input: {
});
}
+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";
+
+function memoryMaxBytes(value: number | undefined, label: string): number {
+ if (value === undefined) return MEMORY_DEFAULT_MAX_BYTES;
+ if (
+ !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 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 httpMemoryToolInput(value: unknown, label: string): ToolInputSchema {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`${label} input must be a JSON Schema object`);
+ }
+ const schema = value as Record<string, unknown>;
+ if (schema.type !== "object") {
+ throw new Error(`${label} input must be a JSON Schema with type "object"`);
+ }
+ if (containsSchemaReference(schema)) {
+ throw new Error(`${label} input cannot use $ref`);
+ }
+ const properties = schema.properties;
+ if (
+ properties !== undefined &&
+ (!properties || typeof properties !== "object" || Array.isArray(properties))
+ ) {
+ throw new Error(`${label} input properties must be an object`);
+ }
+ const required = schema.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(schema);
+ } catch {
+ serialized = undefined;
+ }
+ if (serialized === undefined) {
+ throw new Error(`${label} input must be JSON-compatible`);
+ }
+ return Object.freeze(JSON.parse(serialized) as Record<string, unknown>);
+}
+
+export interface HttpMemoryToolInput {
+ name: string;
+ description: string;
+ access: MemoryToolAccess;
+ idempotent?: boolean;
+ input: ToolInputSchema;
+}
+
+export function documentMemory(
+ input: { maxBytes?: number } = {},
+): DocumentMemoryProvider {
+ return Object.freeze({
+ kind: "document" as const,
+ maxBytes: memoryMaxBytes(input.maxBytes, "documentMemory"),
+ });
+}
+
+export function httpMemory(input: {
+ connection: ConnectionReference;
+ path?: string;
+ maxBytes?: number;
+ tools?: readonly HttpMemoryToolInput[];
+}): HttpMemoryProvider {
+ const connection = input.connection;
+ if (!connection || typeof connection !== "object" || !connection.id) {
+ throw new Error("httpMemory requires a defineConnection() connection");
+ }
+ const path = input.path ?? HTTP_MEMORY_DEFAULT_PATH;
+ if (!/^\/(?!\/)[^?#\s]*$/.test(path)) {
+ throw new Error(
+ "httpMemory path must begin with a single / and contain no query or fragment",
+ );
+ }
+ const policy = connection as Partial<HttpConnectionDefinition>;
+ if (policy.pathPrefix && !path.startsWith(policy.pathPrefix)) {
+ throw new Error(
+ `httpMemory path ${path} is outside connection ${connection.id} pathPrefix ${policy.pathPrefix}`,
+ );
+ }
+ if (policy.methods && !policy.methods.includes("POST")) {
+ throw new Error(
+ `httpMemory requires connection ${connection.id} to allow POST`,
+ );
+ }
+ const tools = input.tools ?? [];
+ if (tools.length > HTTP_MEMORY_MAX_TOOLS) {
+ throw new Error(
+ `httpMemory may declare at most ${HTTP_MEMORY_MAX_TOOLS} tools`,
+ );
+ }
+ const names = new Set<string>();
+ const normalized = tools.map((tool) => {
+ const name = typeof tool.name === "string" ? tool.name.trim() : "";
+ if (!HTTP_MEMORY_TOOL_NAME_PATTERN.test(name)) {
+ throw new Error(
+ "httpMemory tool names must use 1 to 32 lowercase letters, numbers, and underscores",
+ );
+ }
+ const label = `httpMemory tool ${name}`;
+ if (names.has(name)) throw new Error(`${label} is declared more than once`);
+ names.add(name);
+ const description =
+ typeof tool.description === "string" ? tool.description.trim() : "";
+ if (!description) throw new Error(`${label} requires a description`);
+ if (tool.access !== "read" && tool.access !== "write") {
+ throw new Error(`${label} access must be "read" or "write"`);
+ }
+ if (tool.idempotent !== undefined && typeof tool.idempotent !== "boolean") {
+ throw new Error(`${label} idempotent must be true or false`);
+ }
+ return Object.freeze({
+ name,
+ description,
+ access: tool.access,
+ idempotent: tool.idempotent ?? false,
+ input: httpMemoryToolInput(tool.input, label),
+ });
+ });
+ return Object.freeze({
+ kind: "http" as const,
+ connection: connection.id,
+ path,
+ maxBytes: memoryMaxBytes(input.maxBytes, "httpMemory"),
+ tools: Object.freeze(normalized),
+ });
+}
+
+function memoryIdentifier(value: string, kind: string): string {
+ const id = resourceIdentifier(value, kind);
+ if (id.length > MEMORY_ID_MAX_LENGTH) {
+ throw new Error(
+ `${kind} IDs must contain at most ${MEMORY_ID_MAX_LENGTH} characters`,
+ );
+ }
+ return id;
+}
+
+export function defineMemory(input: {
+ id: string;
+ description: string;
+ provider?: MemoryProvider;
+}): MemoryDefinition {
+ const id = memoryIdentifier(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 ?? documentMemory();
+ if (provider.kind !== "document" && provider.kind !== "http") {
+ throw new Error(
+ `Memory ${id} provider must be documentMemory() or httpMemory()`,
+ );
+ }
+ return Object.freeze({
+ kind: "memory" as const,
+ version: 1 as const,
+ id,
+ description,
+ provider,
+ });
+}
+
+function isMemoryProjection(value: unknown): value is MemoryProjection {
+ if (!value || typeof value !== "object") return false;
+ const projection = value as Record<string, unknown>;
+ return (
+ typeof projection.text === "string" &&
+ Array.isArray(projection.sources) &&
+ typeof projection.writable === "boolean"
+ );
+}
+
+/**
+ * The projection the host recalled for this session's binding of `memory`.
+ * It never fetches: a session without that binding fails the render here,
+ * before inference. Calling it also selects the binding's permitted tools for
+ * this model request; omitting it exposes none of them.
+ */
+export function useMemory(memory: string | ResourceReference): MemoryProjection {
+ const id = memoryIdentifier(
+ typeof memory === "string" ? memory : memory.id,
+ "useMemory",
+ );
+ const projection = hooks().useMemory(id);
+ if (!isMemoryProjection(projection)) {
+ throw new Error(
+ `Memory ${JSON.stringify(id)} is not bound to this session; create the session with a memory binding for it`,
+ );
+ }
+ return projection;
+}
+
export const useInput = (): Readonly<AgentInput> => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model: ModelSelection): void =>