Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

feat: migrate agentmemory to iii v0.11 and add upgrade command (#116)

Rohit Ghumare5d70ecfb3c24
diff --git a/AGENTS.md b/AGENTS.md
index ee13ce45..5aa9f562 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,7 +45,7 @@ agentmemory is a persistent memory system for AI coding agents, built on iii-eng
### Function Registration
```typescript
sdk.registerFunction(
- { id: "mem::your-function" },
+ "mem::your-function",
async (data: { ... }) => {
// validate inputs
// do work via kv.get/kv.set/kv.list
@@ -57,12 +57,15 @@ sdk.registerFunction(
### REST Endpoint Registration
```typescript
-sdk.registerFunction({ id: "api::your-endpoint" }, async (req: ApiRequest) => {
+sdk.registerFunction("api::your-endpoint", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
// validate + whitelist fields (never pass raw body to sdk.trigger)
- const result = await sdk.trigger("mem::your-function", { ... });
+ const result = await sdk.trigger({
+ function_id: "mem::your-function",
+ payload: { ... },
+ });
return { status_code: 200, body: result };
});
sdk.registerTrigger({
@@ -77,7 +80,10 @@ sdk.registerTrigger({
case "memory_your_tool": {
// validate args with typeof checks
// parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean)
- const result = await sdk.trigger("mem::your-function", { ... });
+ const result = await sdk.trigger({
+ function_id: "mem::your-function",
+ payload: { ... },
+ });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
}
```
@@ -98,16 +104,16 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Testing
-- All tests must pass before PR: `npm test` (613+ tests)
+- All tests must pass before PR: `npm test` (699+ tests)
- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`
- Test files go in `test/` with `.test.ts` extension
- Follow existing patterns in `test/crystallize.test.ts` for function tests
-## Current Stats (v0.7.0)
+## Current Stats (v0.8.9)
- 43 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)
- 103 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 4 skills
- 50+ iii functions
-- 627 tests
+- 699 tests
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 586c3787..64889abb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,13 @@ All notable changes to agentmemory will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Changed
+
+- Upgraded `iii-sdk` dependency from `^0.11.0-next.8` to stable `^0.11.0`.
+- Aligned stream send payloads with v0.11 wire format by using `type` for `stream::send` events in observe/compress/session-activity paths.
+- Updated migration guidance/examples and diagnostics plugin registration snippets to v0.11 function registration and trigger request shapes.
## [0.8.10] — 2026-04-15
**Behavior change**: the PreToolUse and SessionStart hooks no longer run enrichment by default. SessionStart saves ~1-2K input tokens per session you start (the only path that was actually reaching the model, per the [Claude Code hook docs](https://code.claude.com/docs/en/hooks.md)). PreToolUse stops spawning a Node process and POSTing to `/agentmemory/enrich` on every file-touching tool call — a pure resource cleanup, not a token fix. If you were relying on either path, set `AGENTMEMORY_INJECT_CONTEXT=true` in `~/.agentmemory/.env` and restart. Observations are still captured via PostToolUse regardless.
diff --git a/README.md b/README.md
index 7ffc7112..b980b2e2 100644
--- a/README.md
+++ b/README.md
@@ -286,6 +286,8 @@ npx @agentmemory/agentmemory
<h2 id="quick-start"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-quickstart.svg"><img src="assets/tags/section-quickstart.svg" alt="Quick Start" height="32" /></picture></h2>
+Compatibility: this release targets stable `iii-sdk` `^0.11.0` and iii-engine v0.11.x.
+
### Try it in 30 seconds
```bash
@@ -300,6 +302,18 @@ npx @agentmemory/agentmemory demo
Open `http://localhost:3113` to watch the memory build live.
+### Upgrade / Maintenance
+
+Use the maintenance command when you intentionally want to update your local runtime:
+
+```bash
+npx @agentmemory/agentmemory upgrade
+```
+
+Warning: this command mutates the current workspace/runtime. It can update JavaScript dependencies, may run `cargo install iii-engine --force`, and may pull Docker images.
+
+Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cli.ts:544-595` region).
+
### Claude Code (one block, paste it)
```
diff --git a/iii-config.docker.yaml b/iii-config.docker.yaml
index 3aecf8a8..bc53c825 100644
--- a/iii-config.docker.yaml
+++ b/iii-config.docker.yaml
@@ -1,13 +1,5 @@
-modules:
- - class: modules::state::StateModule
- config:
- adapter:
- class: modules::state::adapters::KvStore
- config:
- store_method: file_based
- file_path: ./data/state_store.db
-
- - class: modules::api::RestApiModule
+workers:
+ - name: iii-http
config:
port: 3111
host: 0.0.0.0
@@ -15,35 +7,44 @@ modules:
cors:
allowed_origins: ["http://localhost:3111", "http://localhost:3113", "http://127.0.0.1:3111", "http://127.0.0.1:3113"]
allowed_methods: [GET, POST, PUT, DELETE, OPTIONS]
-
- - class: modules::queue::QueueModule
+ - name: iii-state
config:
adapter:
- class: modules::queue::BuiltinQueueAdapter
-
- - class: modules::pubsub::PubSubModule
+ name: kv
+ config:
+ store_method: file_based
+ file_path: ./data/state_store.db
+ - name: iii-queue
+ config:
+ adapter:
+ name: builtin
+ - name: iii-pubsub
config:
adapter:
- class: modules::pubsub::LocalAdapter
-
- - class: modules::cron::CronModule
+ name: local
+ - name: iii-cron
config:
adapter:
- class: modules::cron::KvCronAdapter
-
- - class: modules::stream::StreamModule
+ name: kv
+ - name: iii-stream
config:
port: 3112
host: 0.0.0.0
-
- - class: modules::observability::OtelModule
+ adapter:
+ name: kv
+ config:
+ store_method: file_based
+ file_path: ./data/stream_store
+ - name: iii-observability
config:
enabled: true
service_name: agentmemory
exporter: memory
+ sampling_ratio: 1.0
+ metrics_enabled: true
logs_enabled: true
-
- - class: modules::shell::ExecModule
+ logs_console_output: true
+ - name: iii-exec
config:
watch:
- src/**/*.ts
diff --git a/iii-config.yaml b/iii-config.yaml
index adb05b5a..f7e0f188 100644
--- a/iii-config.yaml
+++ b/iii-config.yaml
@@ -1,13 +1,5 @@
-modules:
- - class: modules::state::StateModule
- config:
- adapter:
- class: modules::state::adapters::KvStore
- config:
- store_method: file_based
- file_path: ./data/state_store.db
-
- - class: modules::api::RestApiModule
+workers:
+ - name: iii-http
config:
port: 3111
host: 127.0.0.1
@@ -15,35 +7,44 @@ modules:
cors:
allowed_origins: ["http://localhost:3111", "http://localhost:3113", "http://127.0.0.1:3111", "http://127.0.0.1:3113"]
allowed_methods: [GET, POST, PUT, DELETE, OPTIONS]
-
- - class: modules::queue::QueueModule
+ - name: iii-state
config:
adapter:
- class: modules::queue::BuiltinQueueAdapter
-
- - class: modules::pubsub::PubSubModule
+ name: kv
+ config:
+ store_method: file_based
+ file_path: ./data/state_store.db
+ - name: iii-queue
+ config:
+ adapter:
+ name: builtin
+ - name: iii-pubsub
config:
adapter:
- class: modules::pubsub::LocalAdapter
-
- - class: modules::cron::CronModule
+ name: local
+ - name: iii-cron
config:
adapter:
- class: modules::cron::KvCronAdapter
-
- - class: modules::stream::StreamModule
+ name: kv
+ - name: iii-stream
config:
port: 3112
host: 127.0.0.1
-
- - class: modules::observability::OtelModule
+ adapter:
+ name: kv
+ config:
+ store_method: file_based
+ file_path: ./data/stream_store
+ - name: iii-observability
config:
enabled: true
service_name: agentmemory
exporter: memory
+ sampling_ratio: 1.0
+ metrics_enabled: true
logs_enabled: true
-
- - class: modules::shell::ExecModule
+ logs_console_output: true
+ - name: iii-exec
config:
watch:
- src/**/*.ts
diff --git a/package-lock.json b/package-lock.json
index ee09c28e..531b1a51 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,7 +13,7 @@
"@anthropic-ai/sdk": "^0.39.0",
"@clack/prompts": "^1.2.0",
"dotenv": "^16.4.7",
- "iii-sdk": "^0.3.0",
+ "iii-sdk": "^0.11.0",
"zod": "^4.0.0"
},
"bin": {
@@ -3082,9 +3082,9 @@
"optional": true
},
"node_modules/iii-sdk": {
- "version": "0.3.0",
- "resolved": "https://registry.npmjs.org/iii-sdk/-/iii-sdk-0.3.0.tgz",
- "integrity": "sha512-v0lV72aXlVMSehYDYVx6rqy8EDXkzUtAM17TBNRI9HRZnRlMON6hgmm/pIkb+rULUujaaaQxTv+WVxJMlmzEDA==",
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/iii-sdk/-/iii-sdk-0.11.0.tgz",
+ "integrity": "sha512-/eY0Fo5HA9fLSD8PrGMNVgRYNk0TRuqKMFD8sdOsySp5+z6Sd3xh33BjuvlzEJUlwp3+jClxr02wL/Tfr+QscQ==",
"license": "Apache-2.0",
"dependencies": {
"@opentelemetry/api": "^1.9.0",
diff --git a/package.json b/package.json
index cf71405b..14569303 100644
--- a/package.json
+++ b/package.json
@@ -58,7 +58,7 @@
"@anthropic-ai/sdk": "^0.39.0",
"@clack/prompts": "^1.2.0",
"dotenv": "^16.4.7",
- "iii-sdk": "^0.3.0",
+ "iii-sdk": "^0.11.0",
"zod": "^4.0.0"
},
"optionalDependencies": {
diff --git a/plugin/scripts/diagnostics.mjs b/plugin/scripts/diagnostics.mjs
index 4cd61d11..96d6dada 100644
--- a/plugin/scripts/diagnostics.mjs
+++ b/plugin/scripts/diagnostics.mjs
@@ -62,7 +62,7 @@ const ALL_CATEGORIES = [
const TWENTY_FOUR_HOURS_MS = 1440 * 60 * 1e3;
const ONE_HOUR_MS = 3600 * 1e3;
function registerDiagnosticsFunction(sdk, kv) {
- sdk.registerFunction({ id: "mem::diagnose" }, async (data) => {
+ sdk.registerFunction("mem::diagnose", async (data) => {
const categories = data.categories && data.categories.length > 0 ? data.categories.filter((c) => ALL_CATEGORIES.includes(c)) : ALL_CATEGORIES;
const checks = [];
const now = Date.now();
@@ -333,7 +333,7 @@ function registerDiagnosticsFunction(sdk, kv) {
}
};
});
- sdk.registerFunction({ id: "mem::heal" }, async (data) => {
+ sdk.registerFunction("mem::heal", async (data) => {
const dryRun = data.dryRun ?? false;
const categories = data.categories && data.categories.length > 0 ? data.categories.filter((c) => ALL_CATEGORIES.includes(c)) : ALL_CATEGORIES;
let fixed = 0;
diff --git a/src/cli.ts b/src/cli.ts
index 100a4b6a..69f7c91a 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,6 +1,11 @@
#!/usr/bin/env node
-import { spawn, execFileSync, type ChildProcess } from "node:child_process";
+import {
+ spawn,
+ execFileSync,
+ spawnSync,
+ type ChildProcess,
+} from "node:child_process";
import { existsSync } from "node:fs";
import { join, dirname, delimiter as PATH_DELIMITER } from "node:path";
import { fileURLToPath } from "node:url";
@@ -27,6 +32,7 @@ Commands:
(default) Start agentmemory worker
status Show connection status, memory count, and health
demo Seed sample sessions and show recall in action
+ upgrade Upgrade local deps + iii runtime (best effort)
mcp Start standalone MCP server (no engine required)
Options:
@@ -40,6 +46,7 @@ Quick start:
npx @agentmemory/agentmemory # start with local iii-engine or Docker
npx @agentmemory/agentmemory status # check health
npx @agentmemory/agentmemory demo # try it in 30 seconds (needs server running)
+ npx @agentmemory/agentmemory upgrade # upgrade agentmemory + iii runtime
npx @agentmemory/agentmemory mcp # standalone MCP server (no engine)
npx @agentmemory/mcp # same as above (shim package)
`);
@@ -664,6 +671,129 @@ async function runDemo() {
p.log.success("agentmemory is working. Point your agent at it and get back to coding.");
}
+function runCommand(
+ command: string,
+ commandArgs: string[],
+ options: { cwd?: string; label: string; optional?: boolean } = { label: "command" },
+): boolean {
+ const spinner = p.spinner();
+ spinner.start(options.label);
+ const result = spawnSync(command, commandArgs, {
+ cwd: options.cwd || process.cwd(),
+ stdio: "pipe",
+ encoding: "utf-8",
+ });
+
+ if (result.status === 0) {
+ spinner.stop(`${options.label} ✓`);
+ return true;
+ }
+
+ const stderr = (result.stderr || "").toString().trim();
+ const stdout = (result.stdout || "").toString().trim();
+ const msg = stderr || stdout || "unknown error";
+
+ if (options.optional) {
+ spinner.stop(`${options.label} (skipped)`);
+ p.log.warn(msg.slice(0, 300));
+ return false;
+ }
+
+ spinner.stop(`${options.label} ✗`);
+ p.log.error(msg.slice(0, 300));
+ return false;
+}
+
+async function runUpgrade() {
+ p.intro("agentmemory upgrade");
+
+ const cwd = process.cwd();
+ const hasPackageJson = existsSync(join(cwd, "package.json"));
+ const hasPnpmLock = existsSync(join(cwd, "pnpm-lock.yaml"));
+
+ const pnpmBin = whichBinary("pnpm");
+ const npmBin = whichBinary("npm");
+ const cargoBin = whichBinary("cargo");
+ const dockerBin = whichBinary("docker");
+
+ p.log.info(`Working directory: ${cwd}`);
+ const requireSuccess = (ok: boolean, label: string): void => {
+ if (!ok) {
+ p.log.error(`Upgrade aborted: ${label} failed.`);
+ process.exit(1);
+ }
+ };
+
+ if (hasPackageJson) {
+ const usePnpm = !!pnpmBin && hasPnpmLock;
+ if (usePnpm && pnpmBin) {
+ const installOk = runCommand(pnpmBin, ["install"], {
+ label: "Refreshing dependencies (pnpm install)",
+ });
+ requireSuccess(installOk, "pnpm install");
+ runCommand(pnpmBin, ["up", "iii-sdk@latest"], {
+ label: "Upgrading iii-sdk to latest",
+ optional: true,
+ });
+ } else if (npmBin) {
+ const installOk = runCommand(npmBin, ["install"], {
+ label: "Refreshing dependencies (npm install)",
+ });
+ requireSuccess(installOk, "npm install");
+ runCommand(npmBin, ["install", "iii-sdk@latest"], {
+ label: "Upgrading iii-sdk to latest",
+ optional: true,
+ });
+ } else {
+ p.log.warn("No package manager found (pnpm/npm). Skipping JS dependency upgrade.");
+ }
+ } else {
+ p.log.warn("No package.json in current directory. Skipping JS dependency upgrade.");
+ }
+
+ if (cargoBin) {
+ const upgradeEngine = await p.confirm({
+ message: "Upgrade iii-engine via cargo install --force?",
+ initialValue: true,
+ });
+ if (p.isCancel(upgradeEngine)) {
+ p.cancel("Cancelled.");
+ return process.exit(0);
+ }
+ if (upgradeEngine === true) {
+ const cargoOk = runCommand(cargoBin, ["install", "iii-engine", "--force"], {
+ label: "Upgrading iii-engine (cargo)",
+ });
+ requireSuccess(cargoOk, "cargo install iii-engine --force");
+ } else {
+ p.log.info("Skipped cargo-based iii-engine upgrade.");
+ }
+ } else {
+ p.log.warn("Cargo not found. Skipping iii-engine binary upgrade.");
+ }
+
+ if (dockerBin) {
+ runCommand(dockerBin, ["pull", "iiidev/iii:latest"], {
+ label: "Pulling latest iii Docker image",
+ optional: true,
+ });
+ } else {
+ p.log.info("Docker not found. Skipping Docker image refresh.");
+ }
+
+ p.note(
+ [
+ "Upgrade flow completed.",
+ "",
+ "Recommended next steps:",
+ " 1) agentmemory status",
+ " 2) npm/pnpm test",
+ " 3) restart agentmemory process",
+ ].join("\n"),
+ "agentmemory upgrade",
+ );
+}
+
async function runMcp(): Promise<void> {
await import("./mcp/standalone.js");
}
@@ -671,6 +801,7 @@ async function runMcp(): Promise<void> {
const commands: Record<string, () => Promise<void>> = {
status: runStatus,
demo: runDemo,
+ upgrade: runUpgrade,
mcp: runMcp,
};
diff --git a/src/functions/actions.ts b/src/functions/actions.ts
index 54a6f3b7..12d12df3 100644
--- a/src/functions/actions.ts
+++ b/src/functions/actions.ts
@@ -3,10 +3,10 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge } from "../types.js";
+import { recordAudit } from "./audit.js";
export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::action-create" },
+ sdk.registerFunction("mem::action-create",
async (data: {
title: string;
description?: string;
@@ -82,6 +82,11 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
}
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_create", "mem::action-create", [action.id], {
+ actor: data.createdBy || "unknown",
+ action,
+ edges: pendingEdges,
+ });
for (const edge of pendingEdges) {
await kv.set(KV.actionEdges, edge.id, edge);
@@ -92,8 +97,7 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::action-update" },
+ sdk.registerFunction("mem::action-update",
async (data: {
actionId: string;
status?: Action["status"];
@@ -113,6 +117,7 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
if (!action) {
return { success: false, error: "action not found" };
}
+ const before = { ...action };
if (data.status !== undefined) action.status = data.status;
if (data.title !== undefined) action.title = data.title.trim();
@@ -126,6 +131,11 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::action-update", [action.id], {
+ actor: data.assignedTo || "unknown",
+ before,
+ after: action,
+ });
if (data.status === "done") {
await propagateCompletion(kv, action.id);
@@ -136,8 +146,7 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::action-edge-create" },
+ sdk.registerFunction("mem::action-edge-create",
async (data: {
sourceActionId: string;
targetActionId: string;
@@ -184,12 +193,15 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.actionEdges, edge.id, edge);
+ await recordAudit(kv, "action_create", "mem::action-edge-create", [edge.id], {
+ actor: "unknown",
+ edge,
+ });
return { success: true, edge };
},
);
- sdk.registerFunction(
- { id: "mem::action-list" },
+ sdk.registerFunction("mem::action-list",
async (data: {
status?: string;
project?: string;
@@ -224,8 +236,7 @@ export function registerActionsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::action-get" },
+ sdk.registerFunction("mem::action-get",
async (data: { actionId: string }) => {
if (!data.actionId) {
return { success: false, error: "actionId is required" };
diff --git a/src/functions/audit.ts b/src/functions/audit.ts
index 3827d3cc..228b7f37 100644
--- a/src/functions/audit.ts
+++ b/src/functions/audit.ts
@@ -1,3 +1,4 @@
+import { getContext } from "iii-sdk";
import type { AuditEntry } from "../types.js";
import { KV, generateId } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
@@ -25,6 +26,30 @@ export async function recordAudit(
return entry;
}
+export async function safeAudit(
+ kv: StateKV,
+ operation: AuditEntry["operation"],
+ functionId: string,
+ targetIds: string[],
+ details: Record<string, unknown> = {},
+ qualityScore?: number,
+ userId?: string,
+): Promise<void> {
+ try {
+ await recordAudit(kv, operation, functionId, targetIds, details, qualityScore, userId);
+ } catch (err) {
+ try {
+ const ctx = getContext();
+ ctx.logger.warn("audit write failed", {
+ functionId,
+ operation,
+ targetIds,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } catch {}
+ }
+}
+
export async function queryAudit(
kv: StateKV,
filter?: {
diff --git a/src/functions/auto-forget.ts b/src/functions/auto-forget.ts
index a4009ca9..f55171c1 100644
--- a/src/functions/auto-forget.ts
+++ b/src/functions/auto-forget.ts
@@ -3,6 +3,7 @@ import { getContext } from "iii-sdk";
import type { Memory, CompressedObservation, Session } from "../types.js";
import { KV, jaccardSimilarity } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
import { deleteAccessLog } from "./access-tracker.js";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -20,12 +21,7 @@ interface AutoForgetResult {
}
export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::auto-forget",
- description:
- "Auto-forget expired (TTL), contradictory, and low-value data",
- },
+ sdk.registerFunction("mem::auto-forget",
async (data: { dryRun?: boolean }): Promise<AutoForgetResult> => {
const ctx = getContext();
const dryRun = data?.dryRun ?? false;
@@ -48,6 +44,11 @@ export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {
deletedIds.add(mem.id);
if (!dryRun) {
await kv.delete(KV.memories, mem.id);
+ await recordAudit(kv, "delete", "mem::auto-forget", [mem.id], {
+ resource: "memory",
+ reason: "auto-forget TTL",
+ timestamp: mem.forgetAfter,
+ });
await deleteAccessLog(kv, mem.id);
}
}
@@ -125,6 +126,12 @@ export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {
: memB;
older.isLatest = false;
await kv.set(KV.memories, older.id, older);
+ await recordAudit(kv, "forget", "mem::auto-forget", [older.id], {
+ resource: "memory",
+ reason: "auto-forget contradiction",
+ olderId: older.id,
+ similarity: sim,
+ });
}
}
}
@@ -154,6 +161,12 @@ export function registerAutoForgetFunction(sdk: ISdk, kv: StateKV): void {
await kv
.delete(KV.observations(sessions[i].id), obs.id)
.catch(() => {});
+ await recordAudit(kv, "delete", "mem::auto-forget", [obs.id], {
+ resource: "observation",
+ reason: "auto-forget low-value observation",
+ sessionId: sessions[i].id,
+ timestamp: obs.timestamp,
+ });
}
}
}
diff --git a/src/functions/branch-aware.ts b/src/functions/branch-aware.ts
index 35e86f26..d0240f43 100644
--- a/src/functions/branch-aware.ts
+++ b/src/functions/branch-aware.ts
@@ -19,8 +19,7 @@ function execAsync(
}
export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::detect-worktree" },
+ sdk.registerFunction("mem::detect-worktree",
async (data: { cwd: string }) => {
if (!data.cwd) {
return { success: false, error: "cwd is required" };
@@ -77,8 +76,7 @@ export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::list-worktrees" },
+ sdk.registerFunction("mem::list-worktrees",
async (data: { cwd: string }) => {
if (!data.cwd) {
return { success: false, error: "cwd is required" };
@@ -124,8 +122,7 @@ export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::branch-sessions" },
+ sdk.registerFunction("mem::branch-sessions",
async (data: { cwd: string; branch?: string }) => {
if (!data.cwd) {
return { success: false, error: "cwd is required" };
@@ -139,7 +136,7 @@ export function registerBranchAwareFunction(sdk: ISdk, kv: StateKV): void {
mainRepoRoot: string;
branch: string | null;
}
- >("mem::detect-worktree", { cwd: data.cwd });
+ >({ function_id: "mem::detect-worktree", payload: { cwd: data.cwd } });
const projectRoot = worktreeInfo.mainRepoRoot || data.cwd;
const branch = data.branch || worktreeInfo.branch;
diff --git a/src/functions/cascade.ts b/src/functions/cascade.ts
index 08d3864e..fb979e65 100644
--- a/src/functions/cascade.ts
+++ b/src/functions/cascade.ts
@@ -2,10 +2,10 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV } from "../state/schema.js";
import type { Memory, GraphNode, GraphEdge } from "../types.js";
+import { recordAudit } from "./audit.js";
export function registerCascadeFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::cascade-update" },
+ sdk.registerFunction("mem::cascade-update",
async (data: { supersededMemoryId: string }) => {
if (!data.supersededMemoryId || typeof data.supersededMemoryId !== "string") {
return { success: false, error: "supersededMemoryId is required" };
@@ -32,6 +32,11 @@ export function registerCascadeFunction(sdk: ISdk, kv: StateKV): void {
node.stale = true;
node.updatedAt = now;
await kv.set(KV.graphNodes, node.id, node);
+ await recordAudit(kv, "consolidate", "mem::cascade-update", [node.id], {
+ resourceType: "GraphNode",
+ change: "marked stale from superseded memory",
+ supersededMemoryId: data.supersededMemoryId,
+ });
flaggedNodes++;
}
}
@@ -43,6 +48,11 @@ export function registerCascadeFunction(sdk: ISdk, kv: StateKV): void {
if (overlap) {
edge.stale = true;
await kv.set(KV.graphEdges, edge.id, edge);
+ await recordAudit(kv, "consolidate", "mem::cascade-update", [edge.id], {
+ resourceType: "GraphEdge",
+ change: "marked stale from superseded memory",
+ supersededMemoryId: data.supersededMemoryId,
+ });
flaggedEdges++;
}
}
diff --git a/src/functions/checkpoints.ts b/src/functions/checkpoints.ts
index 1d3759c5..efb3957a 100644
--- a/src/functions/checkpoints.ts
+++ b/src/functions/checkpoints.ts
@@ -3,10 +3,10 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge, Checkpoint } from "../types.js";
+import { recordAudit } from "./audit.js";
export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::checkpoint-create" },
+ sdk.registerFunction("mem::checkpoint-create",
async (data: {
name: string;
description?: string;
@@ -47,6 +47,11 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
}
await kv.set(KV.checkpoints, checkpoint.id, checkpoint);
+ await recordAudit(kv, "checkpoint_resolve", "mem::checkpoint-create", [checkpoint.id], {
+ action: "create",
+ type: checkpoint.type,
+ name: checkpoint.name,
+ });
if (data.linkedActionIds && data.linkedActionIds.length > 0) {
for (const actionId of data.linkedActionIds) {
@@ -61,9 +66,16 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
const action = await kv.get<Action>(KV.actions, actionId);
if (action && action.status === "pending") {
+ const previousStatus = action.status;
action.status = "blocked";
action.updatedAt = now.toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::checkpoint-create", [action.id], {
+ action: "status-change",
+ previousStatus,
+ newStatus: action.status,
+ checkpointId: checkpoint.id,
+ });
}
}
}
@@ -72,8 +84,7 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::checkpoint-resolve" },
+ sdk.registerFunction("mem::checkpoint-resolve",
async (data: {
checkpointId: string;
status: "passed" | "failed";
@@ -110,12 +121,20 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
checkpoint.result = data.result;
await kv.set(KV.checkpoints, checkpoint.id, checkpoint);
+ await recordAudit(kv, "checkpoint_resolve", "mem::checkpoint-resolve", [checkpoint.id], {
+ action: "resolve",
+ resolvedBy: data.resolvedBy,
+ result: data.result,
+ newStatus: checkpoint.status,
+ });
let unblockedCount = 0;
if (data.status === "passed" && checkpoint.linkedActionIds.length > 0) {
const allEdges = await kv.list<ActionEdge>(KV.actionEdges);
const allCheckpoints = await kv.list<Checkpoint>(KV.checkpoints);
+ const allActions = await kv.list<Action>(KV.actions);
const cpMap = new Map(allCheckpoints.map((c) => [c.id, c]));
+ const actionMap = new Map(allActions.map((a) => [a.id, a]));
for (const actionId of checkpoint.linkedActionIds) {
await withKeyedLock(`mem:action:${actionId}`, async () => {
@@ -131,16 +150,21 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
const requires = allEdges.filter(
(e) => e.sourceActionId === actionId && e.type === "requires",
);
- const allActions = await kv.list<Action>(KV.actions);
- const actionMap = new Map(allActions.map((a) => [a.id, a]));
const allRequiresMet = requires.every((r) => {
const dep = actionMap.get(r.targetActionId);
return dep && dep.status === "done";
});
if (allGatesPassed && allRequiresMet) {
+ const previousStatus = action.status;
action.status = "pending";
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::checkpoint-resolve", [action.id], {
+ action: "unblock",
+ checkpointId: checkpoint.id,
+ previousStatus,
+ newStatus: action.status,
+ });
unblockedCount++;
}
}
@@ -154,8 +178,7 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::checkpoint-list" },
+ sdk.registerFunction("mem::checkpoint-list",
async (data: { status?: string; type?: string }) => {
let checkpoints = await kv.list<Checkpoint>(KV.checkpoints);
@@ -175,8 +198,7 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::checkpoint-expire" },
+ sdk.registerFunction("mem::checkpoint-expire",
async () => {
const checkpoints = await kv.list<Checkpoint>(KV.checkpoints);
const now = Date.now();
@@ -196,6 +218,11 @@ export function registerCheckpointsFunction(sdk: ISdk, kv: StateKV): void {
fresh.status = "expired";
fresh.resolvedAt = new Date().toISOString();
await kv.set(KV.checkpoints, fresh.id, fresh);
+ await recordAudit(kv, "checkpoint_resolve", "mem::checkpoint-expire", [fresh.id], {
+ action: "expire",
+ previousStatus: "pending",
+ newStatus: "expired",
+ });
return true;
},
);
diff --git a/src/functions/claude-bridge.ts b/src/functions/claude-bridge.ts
index 149bc938..667c141b 100644
--- a/src/functions/claude-bridge.ts
+++ b/src/functions/claude-bridge.ts
@@ -74,8 +74,7 @@ export function registerClaudeBridgeFunction(
kv: StateKV,
config: ClaudeBridgeConfig,
): void {
- sdk.registerFunction(
- { id: "mem::claude-bridge-read" },
+ sdk.registerFunction("mem::claude-bridge-read",
async () => {
const ctx = getContext();
if (!config.enabled || !config.memoryFilePath) {
@@ -94,6 +93,11 @@ export function registerClaudeBridgeFunction(
sections: Object.fromEntries(sections),
lineCount: content.split("\n").length,
});
+ await recordAudit(kv, "export", "mem::claude-bridge-read", ["last-read"], {
+ timestamp: new Date().toISOString(),
+ sections: Object.keys(Object.fromEntries(sections)),
+ lineCount: content.split("\n").length,
+ });
ctx.logger.info("Claude bridge: read MEMORY.md", {
path: config.memoryFilePath,
@@ -108,8 +112,7 @@ export function registerClaudeBridgeFunction(
},
);
- sdk.registerFunction(
- { id: "mem::claude-bridge-sync" },
+ sdk.registerFunction("mem::claude-bridge-sync",
async () => {
const ctx = getContext();
if (!config.enabled || !config.memoryFilePath) {
diff --git a/src/functions/compress.ts b/src/functions/compress.ts
index 74f32387..c33e2376 100644
--- a/src/functions/compress.ts
+++ b/src/functions/compress.ts
@@ -1,5 +1,4 @@
-import type { ISdk } from "iii-sdk";
-import { getContext } from "iii-sdk";
+import { TriggerAction, getContext, type ISdk } from "iii-sdk";
import type {
RawObservation,
CompressedObservation,
@@ -66,11 +65,7 @@ export function registerCompressFunction(
provider: MemoryProvider,
metricsStore?: MetricsStore,
): void {
- sdk.registerFunction(
- {
- id: "mem::compress",
- description: "Compress a raw observation using LLM",
- },
+ sdk.registerFunction("mem::compress",
async (data: {
observationId: string;
sessionId: string;
@@ -140,23 +135,44 @@ export function registerCompressFunction(
getSearchIndex().add(compressed);
- sdk.triggerVoid("stream::set", {
- stream_name: STREAM.name,
- group_id: STREAM.group(data.sessionId),
- item_id: data.observationId,
- data: { type: "compressed", observation: compressed },
- });
-
- sdk.triggerVoid("stream::set", {
- stream_name: STREAM.name,
- group_id: STREAM.viewerGroup,
- item_id: data.observationId,
- data: {
- type: "compressed",
- observation: compressed,
- sessionId: data.sessionId,
- },
- });
+ const streamResults = await Promise.allSettled([
+ sdk.trigger({
+ function_id: "stream::set",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.group(data.sessionId),
+ item_id: data.observationId,
+ data: { type: "compressed", observation: compressed },
+ },
+ }),
+ sdk.trigger({
+ function_id: "stream::send",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ id: `compressed-${data.observationId}`,
+ type: "compressed_observation",
+ data: {
+ type: "compressed",
+ observation: compressed,
+ sessionId: data.sessionId,
+ },
+ },
+ action: TriggerAction.Void(),
+ }),
+ ]);
+ for (const result of streamResults) {
+ if (result.status === "rejected") {
+ ctx.logger.warn("Non-fatal stream publish failure after compress", {
+ sessionId: data.sessionId,
+ observationId: data.observationId,
+ error:
+ result.reason instanceof Error
+ ? result.reason.message
+ : String(result.reason),
+ });
+ }
+ }
const latencyMs = Date.now() - startMs;
if (metricsStore) {
diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts
index 72f9ed0f..7d56c2ae 100644
--- a/src/functions/consolidate.ts
+++ b/src/functions/consolidate.ts
@@ -8,6 +8,7 @@ import type {
} from "../types.js";
import { KV, generateId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory.
@@ -66,8 +67,7 @@ export function registerConsolidateFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::consolidate" },
+ sdk.registerFunction("mem::consolidate",
async (data: { project?: string; minObservations?: number }) => {
const ctx = getContext();
const minObs = data.minObservations ?? 10;
@@ -162,6 +162,10 @@ export function registerConsolidateFunction(
if (existingMatch) {
existingMatch.isLatest = false;
await kv.set(KV.memories, existingMatch.id, existingMatch);
+ await recordAudit(kv, "evolve", "mem::consolidate", [existingMatch.id], {
+ action: "mark_non_latest",
+ concept,
+ });
const evolved: Memory = {
id: generateId("mem"),
@@ -178,6 +182,12 @@ export function registerConsolidateFunction(
isLatest: true,
};
await kv.set(KV.memories, evolved.id, evolved);
+ await recordAudit(kv, "evolve", "mem::consolidate", [evolved.id], {
+ action: "evolve_memory",
+ oldId: existingMatch.id,
+ newId: evolved.id,
+ concept,
+ });
existingTitles.add(evolved.title.toLowerCase());
consolidated++;
} else {
@@ -191,6 +201,10 @@ export function registerConsolidateFunction(
isLatest: true,
};
await kv.set(KV.memories, memory.id, memory);
+ await recordAudit(kv, "remember", "mem::consolidate", [memory.id], {
+ action: "create_memory",
+ concept,
+ });
existingTitles.add(memory.title.toLowerCase());
consolidated++;
}
diff --git a/src/functions/consolidation-pipeline.ts b/src/functions/consolidation-pipeline.ts
index 34d032d4..2f8e6c1d 100644
--- a/src/functions/consolidation-pipeline.ts
+++ b/src/functions/consolidation-pipeline.ts
@@ -47,8 +47,7 @@ export function registerConsolidationPipelineFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::consolidate-pipeline" },
+ sdk.registerFunction("mem::consolidate-pipeline",
async (data?: { tier?: string; force?: boolean; project?: string }) => {
if (!data?.force && !isConsolidationEnabled()) {
return { success: false, skipped: true, reason: "CONSOLIDATION_ENABLED is not set to true" };
@@ -137,10 +136,10 @@ export function registerConsolidationPipelineFunction(
if (tier === "all" || tier === "reflect") {
try {
- const reflectResult = await sdk.trigger("mem::reflect", {
+ const reflectResult = await sdk.trigger({ function_id: "mem::reflect", payload: {
maxClusters: 10,
project: data?.project,
- });
+ } });
results.reflect = reflectResult;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -251,7 +250,7 @@ export function registerConsolidationPipelineFunction(
if (process.env["OBSIDIAN_AUTO_EXPORT"] === "true") {
try {
- await sdk.trigger("mem::obsidian-export", {});
+ await sdk.trigger({ function_id: "mem::obsidian-export", payload: {} });
results.obsidianExport = { success: true };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
diff --git a/src/functions/context.ts b/src/functions/context.ts
index 19063a76..798e9ff1 100644
--- a/src/functions/context.ts
+++ b/src/functions/context.ts
@@ -28,11 +28,7 @@ export function registerContextFunction(
kv: StateKV,
tokenBudget: number,
): void {
- sdk.registerFunction(
- {
- id: "mem::context",
- description: "Generate context for session injection",
- },
+ sdk.registerFunction("mem::context",
async (data: { sessionId: string; project: string; budget?: number }) => {
const ctx = getContext();
const budget = data.budget || tokenBudget;
diff --git a/src/functions/crystallize.ts b/src/functions/crystallize.ts
index e44e2662..1f0b8431 100644
--- a/src/functions/crystallize.ts
+++ b/src/functions/crystallize.ts
@@ -20,8 +20,7 @@ export function registerCrystallizeFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::crystallize" },
+ sdk.registerFunction("mem::crystallize",
async (data: {
actionIds: string[];
sessionId?: string;
@@ -74,15 +73,20 @@ export function registerCrystallizeFunction(
await Promise.all(
digest.lessons.map((lesson) =>
- sdk.trigger("mem::lesson-save", {
- content: lesson,
- context: crystal.narrative,
- confidence: 0.6,
- project: data.project,
- tags: [],
- source: "crystal",
- sourceIds: [crystal.id],
- }).catch(() => {}),
+ sdk
+ .trigger({
+ function_id: "mem::lesson-save",
+ payload: {
+ content: lesson,
+ context: crystal.narrative,
+ confidence: 0.6,
+ project: data.project,
+ tags: [],
+ source: "crystal",
+ sourceIds: [crystal.id],
+ },
+ })
+ .catch(() => {}),
),
);
@@ -101,8 +105,7 @@ export function registerCrystallizeFunction(
},
);
- sdk.registerFunction(
- { id: "mem::crystal-list" },
+ sdk.registerFunction("mem::crystal-list",
async (data: {
project?: string;
sessionId?: string;
@@ -127,8 +130,7 @@ export function registerCrystallizeFunction(
},
);
- sdk.registerFunction(
- { id: "mem::crystal-get" },
+ sdk.registerFunction("mem::crystal-get",
async (data: { crystalId: string }) => {
if (!data.crystalId) {
return { success: false, error: "crystalId is required" };
@@ -143,8 +145,7 @@ export function registerCrystallizeFunction(
},
);
- sdk.registerFunction(
- { id: "mem::auto-crystallize" },
+ sdk.registerFunction("mem::auto-crystallize",
async (data: {
olderThanDays?: number;
project?: string;
@@ -205,10 +206,10 @@ export function registerCrystallizeFunction(
const project = groupActions[0].project;
try {
- const result = (await sdk.trigger("mem::crystallize", {
+ const result = (await sdk.trigger({ function_id: "mem::crystallize", payload: {
actionIds,
project,
- })) as { success: boolean; crystal?: Crystal };
+ } })) as { success: boolean; crystal?: Crystal };
if (result.success && result.crystal) {
crystalIds.push(result.crystal.id);
diff --git a/src/functions/diagnostics.ts b/src/functions/diagnostics.ts
index 9d298bc7..42f822cb 100644
--- a/src/functions/diagnostics.ts
+++ b/src/functions/diagnostics.ts
@@ -2,6 +2,7 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { recordAudit } from "./audit.js";
import type {
Action,
ActionEdge,
@@ -31,8 +32,7 @@ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
const ONE_HOUR_MS = 60 * 60 * 1000;
export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::diagnose" },
+ sdk.registerFunction("mem::diagnose",
async (data: { categories?: string[] }) => {
const categories = data.categories && data.categories.length > 0
? data.categories.filter((c) => ALL_CATEGORIES.includes(c))
@@ -407,8 +407,7 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::heal" },
+ sdk.registerFunction("mem::heal",
async (data: { categories?: string[]; dryRun?: boolean }) => {
const dryRun = data.dryRun ?? false;
const categories = data.categories && data.categories.length > 0
@@ -465,6 +464,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
fresh.status = "pending";
fresh.updatedAt = new Date().toISOString();
await kv.set(KV.actions, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ reason: "blocked-deps-done",
+ previousStatus: "blocked",
+ newStatus: "pending",
+ });
return true;
},
);
@@ -519,6 +523,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
fresh.status = "blocked";
fresh.updatedAt = new Date().toISOString();
await kv.set(KV.actions, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ reason: "pending-unsatisfied-deps",
+ previousStatus: "pending",
+ newStatus: "blocked",
+ });
return true;
},
);
@@ -554,7 +563,7 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
continue;
}
const didFix = await withKeyedLock(
- `mem:lease:${lease.actionId}`,
+ `mem:action:${lease.actionId}`,
async () => {
const fresh = await kv.get<Lease>(KV.leases, lease.id);
if (
@@ -566,6 +575,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
fresh.status = "expired";
await kv.set(KV.leases, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ entityType: "lease",
+ reason: "expired-lease",
+ newStatus: "expired",
+ });
const action = await kv.get<Action>(KV.actions, fresh.actionId);
if (
@@ -577,6 +591,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
action.assignedTo = undefined;
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "heal", "mem::heal", [action.id], {
+ entityType: "action",
+ reason: "release-expired-lease",
+ newStatus: "pending",
+ });
}
return true;
},
@@ -601,6 +620,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
continue;
}
await kv.delete(KV.leases, lease.id);
+ await recordAudit(kv, "heal", "mem::heal", [lease.id], {
+ entityType: "lease",
+ reason: "orphaned-lease",
+ action: "delete",
+ });
details.push(`Deleted orphaned lease ${lease.id}`);
fixed++;
}
@@ -639,6 +663,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
}
fresh.status = "expired";
await kv.set(KV.sentinels, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ entityType: "sentinel",
+ reason: "expired-sentinel",
+ newStatus: "expired",
+ });
return true;
},
);
@@ -689,15 +718,30 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
actionIdSet.has(edge.targetActionId)
) {
await kv.delete(KV.actionEdges, edge.id);
+ await recordAudit(kv, "heal", "mem::heal", [edge.id], {
+ entityType: "actionEdge",
+ reason: "sketch-gc-discard",
+ action: "delete",
+ });
}
}
for (const actionId of fresh.actionIds) {
await kv.delete(KV.actions, actionId);
+ await recordAudit(kv, "heal", "mem::heal", [actionId], {
+ entityType: "action",
+ reason: "sketch-gc-discard",
+ action: "delete",
+ });
}
fresh.status = "discarded";
fresh.discardedAt = new Date().toISOString();
await kv.set(KV.sketches, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ entityType: "sketch",
+ reason: "expired-sketch",
+ newStatus: "discarded",
+ });
return true;
},
);
@@ -729,6 +773,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
continue;
}
await kv.delete(KV.signals, signal.id);
+ await recordAudit(kv, "heal", "mem::heal", [signal.id], {
+ entityType: "signal",
+ reason: "expired-signal",
+ action: "delete",
+ });
details.push(`Deleted expired signal ${signal.id}`);
fixed++;
}
@@ -764,6 +813,11 @@ export function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {
fresh.isLatest = false;
fresh.updatedAt = new Date().toISOString();
await kv.set(KV.memories, fresh.id, fresh);
+ await recordAudit(kv, "heal", "mem::heal", [fresh.id], {
+ entityType: "memory",
+ reason: "superseded-memory-mark-non-latest",
+ action: "update",
+ });
return true;
},
);
diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts
index bce4d654..f853a7b1 100644
--- a/src/functions/enrich.ts
+++ b/src/functions/enrich.ts
@@ -16,12 +16,7 @@ function escapeXml(s: string): string {
}
export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::enrich",
- description:
- "Aggregate file context, relevant observations, and bug memories for pre-tool enrichment",
- },
+ sdk.registerFunction("mem::enrich",
async (data: {
sessionId: string;
files: string[];
@@ -32,13 +27,13 @@ export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
const parts: string[] = [];
const fileContextPromise = sdk
- .trigger<{ sessionId: string; files: string[] }, { context: string }>(
- "mem::file-context",
- {
+ .trigger<{ sessionId: string; files: string[] }, { context: string }>({
+ function_id: "mem::file-context",
+ payload: {
sessionId: data.sessionId,
files: data.files,
},
- )
+ })
.catch(() => ({ context: "" }));
const searchQueries: string[] = [
@@ -52,9 +47,12 @@ export function registerEnrichFunction(sdk: ISdk, kv: StateKV): void {
.trigger<
{ query: string; limit: number },
{ results: Array<{ observation: { narrative: string } }> }
- >("mem::search", {
- query: searchQueries.join(" "),
- limit: 5,
+ >({
+ function_id: "mem::search",
+ payload: {
+ query: searchQueries.join(" "),
+ limit: 5,
+ },
})
.catch(() => ({ results: [] }))
: Promise.resolve({ results: [] });
diff --git a/src/functions/evict.ts b/src/functions/evict.ts
index c50ac353..1035c55e 100644
--- a/src/functions/evict.ts
+++ b/src/functions/evict.ts
@@ -8,6 +8,7 @@ import type {
} from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
import { deleteAccessLog } from "./access-tracker.js";
interface EvictionConfig {
@@ -36,11 +37,7 @@ interface EvictionStats {
}
export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::evict",
- description: "Evict stale memories based on age and importance",
- },
+ sdk.registerFunction("mem::evict",
async (data: { dryRun?: boolean }): Promise<EvictionStats> => {
const ctx = getContext();
const dryRun = data?.dryRun ?? false;
@@ -71,9 +68,25 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
const age = now - new Date(session.startedAt).getTime();
const staleDays = cfg.staleSessionDays * MS_PER_DAY;
if (age > staleDays && !summaryIds.has(session.id)) {
- stats.staleSessions++;
- if (!dryRun) {
- await kv.delete(KV.sessions, session.id).catch(() => {});
+ if (dryRun) {
+ stats.staleSessions++;
+ } else {
+ try {
+ await kv.delete(KV.sessions, session.id);
+ stats.staleSessions++;
+ } catch (err) {
+ ctx.logger.warn("Eviction delete failed", {
+ resource: "session",
+ id: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+ await recordAudit(kv, "delete", "mem::evict", [session.id], {
+ resource: "session",
+ reason: "stale_session_without_summary",
+ dryRun,
+ });
}
}
}
@@ -93,11 +106,27 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
age > maxAge &&
(o.importance ?? 5) < cfg.lowImportanceThreshold
) {
- stats.lowImportanceObs++;
- if (!dryRun) {
- await kv
- .delete(KV.observations(session.id), o.id)
- .catch(() => {});
+ if (dryRun) {
+ stats.lowImportanceObs++;
+ } else {
+ try {
+ await kv.delete(KV.observations(session.id), o.id);
+ stats.lowImportanceObs++;
+ } catch (err) {
+ ctx.logger.warn("Eviction delete failed", {
+ resource: "observation",
+ id: o.id,
+ sessionId: session.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+ await recordAudit(kv, "delete", "mem::evict", [o.id], {
+ resource: "observation",
+ reason: "low_importance_old_observation",
+ sessionId: session.id,
+ dryRun,
+ });
}
}
}
@@ -117,12 +146,28 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
0,
obs.length - cfg.maxObservationsPerProject,
);
- stats.capEvictions += toEvict.length;
- if (!dryRun) {
+ if (dryRun) {
+ stats.capEvictions += toEvict.length;
+ } else {
for (const o of toEvict) {
- await kv
- .delete(KV.observations(o.sessionId), o.id)
- .catch(() => {});
+ try {
+ await kv.delete(KV.observations(o.sessionId), o.id);
+ stats.capEvictions++;
+ } catch (err) {
+ ctx.logger.warn("Eviction delete failed", {
+ resource: "observation",
+ id: o.id,
+ sessionId: o.sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+ await recordAudit(kv, "delete", "mem::evict", [o.id], {
+ resource: "observation",
+ reason: "project_observation_cap",
+ sessionId: o.sessionId,
+ dryRun,
+ });
}
}
}
@@ -134,10 +179,28 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
if (mem.forgetAfter) {
const expiry = new Date(mem.forgetAfter).getTime();
if (now > expiry) {
- stats.expiredMemories++;
- evictedMemIds.add(mem.id);
- if (!dryRun) {
- await kv.delete(KV.memories, mem.id).catch(() => {});
+ if (dryRun) {
+ stats.expiredMemories++;
+ evictedMemIds.add(mem.id);
+ } else {
+ try {
+ await kv.delete(KV.memories, mem.id);
+ stats.expiredMemories++;
+ evictedMemIds.add(mem.id);
+ } catch (err) {
+ ctx.logger.warn("Eviction delete failed", {
+ resource: "memory",
+ id: mem.id,
+ reason: "expired_memory",
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+ await recordAudit(kv, "delete", "mem::evict", [mem.id], {
+ resource: "memory",
+ reason: "expired_memory",
+ dryRun,
+ });
await deleteAccessLog(kv, mem.id);
}
}
@@ -150,9 +213,26 @@ export function registerEvictFunction(sdk: ISdk, kv: StateKV): void {
) {
const age = now - new Date(mem.createdAt).getTime();
if (age > cfg.lowImportanceMaxDays * MS_PER_DAY) {
- stats.nonLatestMemories++;
- if (!dryRun) {
- await kv.delete(KV.memories, mem.id).catch(() => {});
+ if (dryRun) {
+ stats.nonLatestMemories++;
+ } else {
+ try {
+ await kv.delete(KV.memories, mem.id);
+ stats.nonLatestMemories++;
+ } catch (err) {
+ ctx.logger.warn("Eviction delete failed", {
+ resource: "memory",
+ id: mem.id,
+ reason: "old_non_latest_memory",
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+ await recordAudit(kv, "delete", "mem::evict", [mem.id], {
+ resource: "memory",
+ reason: "old_non_latest_memory",
+ dryRun,
+ });
await deleteAccessLog(kv, mem.id);
}
}
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index cc97a8ca..4b26e727 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -29,10 +29,10 @@ import { normalizeAccessLog } from "./access-tracker.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { VERSION } from "../version.js";
+import { recordAudit } from "./audit.js";
export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::export", description: "Export all memory data as JSON" },
+ sdk.registerFunction("mem::export",
async (data?: { maxSessions?: number; offset?: number }) => {
const ctx = getContext();
const rawMax = Number(data?.maxSessions);
@@ -162,16 +162,19 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- {
- id: "mem::import",
- description: "Import memory data from JSON export",
- },
+ sdk.registerFunction("mem::import",
async (data: {
exportData: ExportData;
strategy?: "merge" | "replace" | "skip";
}) => {
const ctx = getContext();
+ if (
+ !data?.exportData ||
+ typeof data.exportData !== "object" ||
+ typeof (data.exportData as { version?: unknown }).version !== "string"
+ ) {
+ return { success: false, error: "exportData with string version is required" };
+ }
const strategy = data.strategy || "merge";
const importData = data.exportData;
@@ -326,6 +329,9 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
for (const p of await kv.list<{ id: string }>(KV.procedural).catch(() => [])) {
await kv.delete(KV.procedural, p.id);
}
+ for (const profile of await kv.list<ProjectProfile>(KV.profiles).catch(() => [])) {
+ await kv.delete(KV.profiles, profile.project);
+ }
for (const a of await kv.list<AccessLogExport>(KV.accessLog).catch(() => [])) {
await kv.delete(KV.accessLog, a.memoryId);
}
@@ -425,6 +431,20 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.procedural, proc.id, proc);
}
}
+ if (importData.profiles) {
+ for (const profile of importData.profiles) {
+ if (strategy === "skip") {
+ const existing = await kv
+ .get<ProjectProfile>(KV.profiles, profile.project)
+ .catch(() => null);
+ if (existing) {
+ stats.skipped++;
+ continue;
+ }
+ }
+ await kv.set(KV.profiles, profile.project, profile);
+ }
+ }
if (importData.actions) {
for (const action of importData.actions) {
@@ -555,6 +575,10 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
}
ctx.logger.info("Import complete", { strategy, ...stats });
+ await recordAudit(kv, "import", "mem::import", [], {
+ strategy,
+ stats,
+ });
return { success: true, strategy, ...stats };
},
);
diff --git a/src/functions/facets.ts b/src/functions/facets.ts
index 88f27446..cb5b37dc 100644
--- a/src/functions/facets.ts
+++ b/src/functions/facets.ts
@@ -4,8 +4,7 @@ import { KV, generateId } from "../state/schema.js";
import type { Facet } from "../types.js";
export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::facet-tag" },
+ sdk.registerFunction("mem::facet-tag",
async (data: {
targetId: string;
targetType: string;
@@ -68,8 +67,7 @@ export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::facet-untag" },
+ sdk.registerFunction("mem::facet-untag",
async (data: {
targetId: string;
dimension: string;
@@ -101,8 +99,7 @@ export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::facet-query" },
+ sdk.registerFunction("mem::facet-query",
async (data: {
matchAll?: string[];
matchAny?: string[];
@@ -168,8 +165,7 @@ export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::facet-get" },
+ sdk.registerFunction("mem::facet-get",
async (data: { targetId: string }) => {
if (!data.targetId) {
return { success: false, error: "targetId is required" };
@@ -197,8 +193,7 @@ export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::facet-stats" },
+ sdk.registerFunction("mem::facet-stats",
async (data: { targetType?: string }) => {
const all = await kv.list<Facet>(KV.facets);
const filtered = data.targetType
@@ -227,8 +222,7 @@ export function registerFacetsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::facet-dimensions" },
+ sdk.registerFunction("mem::facet-dimensions",
async () => {
const all = await kv.list<Facet>(KV.facets);
diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts
index 7143ee9a..cefb3f23 100644
--- a/src/functions/file-index.ts
+++ b/src/functions/file-index.ts
@@ -3,6 +3,7 @@ import { getContext } from "iii-sdk";
import type { CompressedObservation, Session } from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
import { recordAccessBatch } from "./access-tracker.js";
interface FileHistory {
@@ -19,16 +20,37 @@ interface FileHistory {
}
export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::file-context" },
- async (data: { sessionId: string; files: string[]; project?: string }) => {
+ sdk.registerFunction("mem::file-context",
+ async (
+ data: { sessionId?: string; files?: string[]; project?: string } | undefined,
+ ) => {
const ctx = getContext();
+ const sessionId =
+ data && typeof data.sessionId === "string" ? data.sessionId.trim() : "";
+ const normalizedProject =
+ typeof data?.project === "string" ? data.project.trim() : undefined;
+ const files = Array.isArray(data?.files)
+ ? data!.files
+ .map((file) => (typeof file === "string" ? file.trim() : ""))
+ .filter(Boolean)
+ : [];
+ if (files.length === 0) {
+ await recordAudit(kv, "observe", "mem::file-context", [sessionId || "unknown"], {
+ error: "invalid_payload",
+ hasSessionId: !!sessionId,
+ hasProject: !!normalizedProject,
+ fileCount: files.length,
+ });
+ return { context: "", files: [] };
+ }
const results: FileHistory[] = [];
const sessions = await kv.list<Session>(KV.sessions);
- let otherSessions = sessions.filter((s) => s.id !== data.sessionId);
- if (data.project) {
- otherSessions = otherSessions.filter((s) => s.project === data.project);
+ let otherSessions = sessionId
+ ? sessions.filter((s) => s.id !== sessionId)
+ : sessions;
+ if (normalizedProject) {
+ otherSessions = otherSessions.filter((s) => s.project === normalizedProject);
}
otherSessions = otherSessions
.sort(
@@ -45,7 +67,7 @@ export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {
);
}
- for (const file of data.files) {
+ for (const file of files) {
const history: FileHistory = { file, observations: [] };
const normalizedFile = file.replace(/^\.\//, "");
@@ -104,7 +126,7 @@ export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {
const context = lines.join("\n");
ctx.logger.info("File context generated", {
- files: data.files.length,
+ files: files.length,
results: results.length,
});
return { context };
diff --git a/src/functions/flow-compress.ts b/src/functions/flow-compress.ts
index 78adfd1a..d2eb5a31 100644
--- a/src/functions/flow-compress.ts
+++ b/src/functions/flow-compress.ts
@@ -2,6 +2,7 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import type { Action, ActionEdge, RoutineRun, MemoryProvider } from "../types.js";
+import { recordAudit } from "./audit.js";
const FLOW_COMPRESS_SYSTEM = `You are a workflow summarizer. Given a completed action chain, produce a concise summary capturing:
1. The overall goal and outcome
@@ -23,8 +24,7 @@ export function registerFlowCompressFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::flow-compress" },
+ sdk.registerFunction("mem::flow-compress",
async (data: { runId?: string; actionIds?: string[]; project?: string }) => {
let actionsToCompress: Action[] = [];
@@ -81,11 +81,12 @@ export function registerFlowCompressFunction(
prompt,
);
const summary = parseFlowSummary(response);
+ const ts = new Date().toISOString();
const memory = {
id: generateId("mem"),
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
+ createdAt: ts,
+ updatedAt: ts,
type: "workflow" as const,
title: summary.goal || `Workflow: ${doneActions.length} actions`,
content: formatSummary(summary),
@@ -103,6 +104,12 @@ export function registerFlowCompressFunction(
};
await kv.set(KV.memories, memory.id, memory);
+ await recordAudit(kv, "compress", "mem::flow-compress", [memory.id], {
+ action: "compress_flow",
+ flowCompressed: true,
+ actionCount: doneActions.length,
+ project: data.project,
+ });
return {
success: true,
diff --git a/src/functions/frontier.ts b/src/functions/frontier.ts
index 2040be6d..30f43fec 100644
--- a/src/functions/frontier.ts
+++ b/src/functions/frontier.ts
@@ -11,8 +11,7 @@ export interface FrontierItem {
}
export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::frontier" },
+ sdk.registerFunction("mem::frontier",
async (data: {
project?: string;
agentId?: string;
@@ -117,8 +116,7 @@ export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::next" },
+ sdk.registerFunction("mem::next",
async (data: { project?: string; agentId?: string }) => {
const result = await sdk.trigger<
{ project?: string; agentId?: string; limit?: number },
@@ -128,11 +126,11 @@ export function registerFrontierFunction(sdk: ISdk, kv: StateKV): void {
totalActions: number;
totalUnblocked: number;
}
- >("mem::frontier", {
+ >({ function_id: "mem::frontier", payload: {
project: data.project,
agentId: data.agentId,
limit: 1,
- });
+ } });
if (!result.success) {
return {
diff --git a/src/functions/governance.ts b/src/functions/governance.ts
index f6450741..8b89a6d5 100644
--- a/src/functions/governance.ts
+++ b/src/functions/governance.ts
@@ -3,12 +3,11 @@ import { getContext } from "iii-sdk";
import type { Memory, GovernanceFilter, AuditEntry } from "../types.js";
import { KV } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
-import { recordAudit, queryAudit } from "./audit.js";
+import { recordAudit, safeAudit, queryAudit } from "./audit.js";
import { deleteAccessLog } from "./access-tracker.js";
export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::governance-delete" },
+ sdk.registerFunction("mem::governance-delete",
async (data: { memoryIds: string[]; reason?: string }) => {
const ctx = getContext();
if (
@@ -48,8 +47,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::governance-bulk" },
+ sdk.registerFunction("mem::governance-bulk",
async (data: GovernanceFilter & { dryRun?: boolean }) => {
const ctx = getContext();
@@ -102,26 +100,64 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void {
};
}
- for (const mem of candidates) {
- await kv.delete(KV.memories, mem.id);
- await deleteAccessLog(kv, mem.id);
+ const BATCH_SIZE = 50;
+ const successfulIds: string[] = [];
+ const failures: Array<{ id: string; error: string }> = [];
+ for (let i = 0; i < candidates.length; i += BATCH_SIZE) {
+ const batch = candidates.slice(i, i + BATCH_SIZE);
+ const results = await Promise.allSettled(
+ batch.map(async (mem) => {
+ await kv.delete(KV.memories, mem.id);
+ await deleteAccessLog(kv, mem.id);
+ }),
+ );
+ results.forEach((result, j) => {
+ const mem = batch[j];
+ if (result.status === "fulfilled") {
+ successfulIds.push(mem.id);
+ } else {
+ ctx.logger.warn("Governance bulk delete failed", {
+ memoryId: mem.id,
+ error:
+ result.reason instanceof Error
+ ? result.reason.message
+ : String(result.reason),
+ });
+ failures.push({
+ id: mem.id,
+ error: "delete_failed",
+ });
+ }
+ });
}
- await recordAudit(
+ await safeAudit(
kv,
"delete",
"mem::governance-bulk",
- candidates.map((m) => m.id),
- { filter: data, deleted: candidates.length },
+ successfulIds,
+ {
+ filter: data,
+ deleted: successfulIds.length,
+ failed: failures.length,
+ failures: failures.length > 0 ? failures : undefined,
+ },
);
- ctx.logger.info("Governance bulk delete", { deleted: candidates.length });
- return { success: true, deleted: candidates.length };
+ ctx.logger.info("Governance bulk delete", {
+ deleted: successfulIds.length,
+ failed: failures.length,
+ });
+ return {
+ success: failures.length === 0,
+ deleted: successfulIds.length,
+ failed: failures.length,
+ failures: failures.length > 0 ? failures : undefined,
+ };
},
);
- sdk.registerFunction(
- { id: "mem::audit-query" },
+ sdk.registerFunction("mem::audit-query",
async (data?: {
operation?: AuditEntry["operation"];
dateFrom?: string;
diff --git a/src/functions/graph.ts b/src/functions/graph.ts
index afb7d201..84c295a2 100644
--- a/src/functions/graph.ts
+++ b/src/functions/graph.ts
@@ -84,8 +84,7 @@ export function registerGraphFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::graph-extract" },
+ sdk.registerFunction("mem::graph-extract",
async (data: { observations: CompressedObservation[] }) => {
const ctx = getContext();
if (!data.observations || data.observations.length === 0) {
@@ -173,8 +172,7 @@ export function registerGraphFunction(
},
);
- sdk.registerFunction(
- { id: "mem::graph-query" },
+ sdk.registerFunction("mem::graph-query",
async (data: {
startNodeId?: string;
nodeType?: string;
@@ -251,7 +249,7 @@ export function registerGraphFunction(
},
);
- sdk.registerFunction({ id: "mem::graph-stats" }, async () => {
+ sdk.registerFunction("mem::graph-stats", async () => {
const nodes = await kv.list<GraphNode>(KV.graphNodes);
const edges = await kv.list<GraphEdge>(KV.graphEdges);
diff --git a/src/functions/leases.ts b/src/functions/leases.ts
index c68168ab..1a2de33b 100644
--- a/src/functions/leases.ts
+++ b/src/functions/leases.ts
@@ -3,13 +3,13 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, Lease } from "../types.js";
+import { recordAudit } from "./audit.js";
const DEFAULT_LEASE_TTL_MS = 10 * 60 * 1000;
const MAX_LEASE_TTL_MS = 60 * 60 * 1000;
export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::lease-acquire" },
+ sdk.registerFunction("mem::lease-acquire",
async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
if (!data.actionId || !data.agentId) {
return { success: false, error: "actionId and agentId are required" };
@@ -68,19 +68,28 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.leases, lease.id, lease);
+ await recordAudit(kv, "lease_acquire", "mem::lease-acquire", [lease.id], {
+ actionId: data.actionId,
+ agentId: data.agentId,
+ expiresAt: lease.expiresAt,
+ });
+ const before = { ...action };
action.status = "active";
action.assignedTo = data.agentId;
action.updatedAt = now.toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::lease-acquire", [action.id], {
+ before,
+ after: action,
+ });
return { success: true, lease, renewed: false };
});
},
);
- sdk.registerFunction(
- { id: "mem::lease-release" },
+ sdk.registerFunction("mem::lease-release",
async (data: { actionId: string; agentId: string; result?: string }) => {
if (!data.actionId || !data.agentId) {
return { success: false, error: "actionId and agentId are required" };
@@ -102,9 +111,15 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
activeLease.status = "released";
await kv.set(KV.leases, activeLease.id, activeLease);
+ await recordAudit(kv, "lease_release", "mem::lease-release", [activeLease.id], {
+ actionId: data.actionId,
+ agentId: data.agentId,
+ status: "released",
+ });
const action = await kv.get<Action>(KV.actions, data.actionId);
if (action && action.status === "active" && action.assignedTo === data.agentId) {
+ const before = { ...action };
if (data.result) {
action.status = "done";
action.result = data.result;
@@ -114,6 +129,11 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
action.assignedTo = undefined;
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::lease-release", [action.id], {
+ before,
+ after: action,
+ agentId: data.agentId,
+ });
}
return { success: true, released: true };
@@ -121,8 +141,7 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::lease-renew" },
+ sdk.registerFunction("mem::lease-renew",
async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
if (!data.actionId || !data.agentId) {
return { success: false, error: "actionId and agentId are required" };
@@ -149,17 +168,23 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
const now = new Date();
const base = Math.max(now.getTime(), new Date(activeLease.expiresAt).getTime());
+ const beforeLease = { ...activeLease };
activeLease.expiresAt = new Date(base + ttl).toISOString();
activeLease.renewedAt = now.toISOString();
await kv.set(KV.leases, activeLease.id, activeLease);
+ await recordAudit(kv, "lease_renew", "mem::lease-renew", [activeLease.id], {
+ actionId: data.actionId,
+ agentId: data.agentId,
+ before: beforeLease,
+ after: activeLease,
+ });
return { success: true, lease: activeLease };
});
},
);
- sdk.registerFunction(
- { id: "mem::lease-cleanup" },
+ sdk.registerFunction("mem::lease-cleanup",
async () => {
const leases = await kv.list<Lease>(KV.leases);
const now = Date.now();
@@ -183,6 +208,11 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
}
currentLease.status = "expired";
await kv.set(KV.leases, currentLease.id, currentLease);
+ await recordAudit(kv, "lease_release", "mem::lease-cleanup", [currentLease.id], {
+ action: "expire",
+ actionId: currentLease.actionId,
+ agentId: currentLease.agentId,
+ });
const action = await kv.get<Action>(KV.actions, currentLease.actionId);
const otherActiveLease = (await kv.list<Lease>(KV.leases)).some(
@@ -202,6 +232,11 @@ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
action.assignedTo = undefined;
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::lease-cleanup", [action.id], {
+ action: "status-change",
+ newStatus: action.status,
+ actionId: action.id,
+ });
}
return true;
},
diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts
index 2329391e..9e69f464 100644
--- a/src/functions/lessons.ts
+++ b/src/functions/lessons.ts
@@ -16,8 +16,7 @@ function reinforceLesson(lesson: Lesson): void {
}
export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::lesson-save" },
+ sdk.registerFunction("mem::lesson-save",
async (data: {
content: string;
context?: string;
@@ -87,8 +86,7 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::lesson-recall" },
+ sdk.registerFunction("mem::lesson-recall",
async (data: {
query: string;
project?: string;
@@ -152,8 +150,7 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::lesson-list" },
+ sdk.registerFunction("mem::lesson-list",
async (data: {
project?: string;
source?: string;
@@ -181,8 +178,7 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::lesson-strengthen" },
+ sdk.registerFunction("mem::lesson-strengthen",
async (data: { lessonId: string }) => {
if (!data.lessonId) {
return { success: false, error: "lessonId is required" };
@@ -207,8 +203,7 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::lesson-decay-sweep" },
+ sdk.registerFunction("mem::lesson-decay-sweep",
async () => {
const lessons = await kv.list<Lesson>(KV.lessons);
let decayed = 0;
@@ -216,6 +211,14 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
const now = Date.now();
const timestamp = new Date().toISOString();
const dirty: Lesson[] = [];
+ const auditEvents: Array<{
+ id: string;
+ action: "decay" | "soft-delete";
+ beforeConfidence: number;
+ afterConfidence: number;
+ beforeDeleted: boolean;
+ afterDeleted: boolean;
+ }> = [];
for (const lesson of lessons) {
if (lesson.deleted) continue;
@@ -230,6 +233,8 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
const newConfidence = Math.max(0.05, lesson.confidence - decay);
if (newConfidence !== lesson.confidence) {
+ const beforeConfidence = lesson.confidence;
+ const beforeDeleted = !!lesson.deleted;
lesson.confidence = Math.round(newConfidence * 1000) / 1000;
lesson.lastDecayedAt = timestamp;
lesson.updatedAt = timestamp;
@@ -242,10 +247,35 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void {
}
dirty.push(lesson);
+ auditEvents.push({
+ id: lesson.id,
+ action: lesson.deleted ? "soft-delete" : "decay",
+ beforeConfidence,
+ afterConfidence: lesson.confidence,
+ beforeDeleted,
+ afterDeleted: !!lesson.deleted,
+ });
}
}
await Promise.all(dirty.map((l) => kv.set(KV.lessons, l.id, l)));
+ await Promise.all(
+ auditEvents.map((event) =>
+ recordAudit(kv, "lesson_strengthen", "mem::lesson-decay-sweep", [event.id], {
+ action: event.action,
+ actor: "system",
+ reason: "decay-sweep",
+ before: {
+ confidence: event.beforeConfidence,
+ deleted: event.beforeDeleted,
+ },
+ after: {
+ confidence: event.afterConfidence,
+ deleted: event.afterDeleted,
+ },
+ }),
+ ),
+ );
return { success: true, decayed, softDeleted, total: lessons.length };
},
diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts
index dd4c670b..ad52e5ea 100644
--- a/src/functions/mesh.ts
+++ b/src/functions/mesh.ts
@@ -2,6 +2,7 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { recordAudit } from "./audit.js";
import type {
MeshPeer,
Memory,
@@ -140,14 +141,16 @@ export function registerMeshFunction(
kv: StateKV,
meshAuthToken?: string,
): void {
- sdk.registerFunction(
- { id: "mem::mesh-register" },
+ sdk.registerFunction("mem::mesh-register",
async (data: {
url: string;
name: string;
sharedScopes?: string[];
syncFilter?: { project?: string };
}) => {
+ if (!data || typeof data !== "object") {
+ return { success: false, error: "payload required" };
+ }
if (!data.url || !data.name) {
return { success: false, error: "url and name are required" };
}
@@ -172,20 +175,25 @@ export function registerMeshFunction(
};
await kv.set(KV.mesh, peer.id, peer);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-register", [peer.id], {
+ action: "mesh.register",
+ peerId: peer.id,
+ name: peer.name,
+ url: peer.url,
+ sharedScopes: peer.sharedScopes,
+ });
return { success: true, peer };
},
);
- sdk.registerFunction(
- { id: "mem::mesh-list" },
+ sdk.registerFunction("mem::mesh-list",
async () => {
const peers = await kv.list<MeshPeer>(KV.mesh);
return { success: true, peers };
},
);
- sdk.registerFunction(
- { id: "mem::mesh-sync" },
+ sdk.registerFunction("mem::mesh-sync",
async (data: { peerId?: string; scopes?: string[]; direction?: "push" | "pull" | "both" }) => {
if (!meshAuthToken) {
return {
@@ -193,6 +201,9 @@ export function registerMeshFunction(
error: "mesh sync requires AGENTMEMORY_SECRET",
};
}
+ if (!data || typeof data !== "object") {
+ data = {};
+ }
const direction = data.direction || "both";
let peers: MeshPeer[];
@@ -224,6 +235,11 @@ export function registerMeshFunction(
peer.status = "syncing";
await kv.set(KV.mesh, peer.id, peer);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-sync", [peer.id], {
+ action: "mesh.sync.start",
+ direction,
+ scopes: data.scopes || peer.sharedScopes,
+ });
const scopes = data.scopes || peer.sharedScopes;
@@ -232,6 +248,10 @@ export function registerMeshFunction(
result.errors.push("peer URL blocked: private/local address not allowed");
peer.status = "error";
await kv.set(KV.mesh, peer.id, peer);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-sync", [peer.id], {
+ action: "mesh.sync.error",
+ error: "peer URL blocked: private/local address not allowed",
+ });
results.push(result);
continue;
}
@@ -296,6 +316,15 @@ export function registerMeshFunction(
}
await kv.set(KV.mesh, peer.id, peer);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-sync", [peer.id], {
+ action: result.errors.length > 0 ? "mesh.sync.error" : "mesh.sync.complete",
+ direction,
+ scopes,
+ pushed: result.pushed,
+ pulled: result.pulled,
+ errors: result.errors,
+ lastSyncAt: peer.lastSyncAt,
+ });
results.push(result);
}
@@ -303,9 +332,11 @@ export function registerMeshFunction(
},
);
- sdk.registerFunction(
- { id: "mem::mesh-receive" },
+ sdk.registerFunction("mem::mesh-receive",
async (data: MeshSyncPayload) => {
+ if (!data || typeof data !== "object") {
+ return { success: false, error: "payload required" };
+ }
let accepted = 0;
accepted += await lwwMergeList(kv, KV.memories, data.memories, "mem:memory", "updatedAt");
@@ -320,6 +351,10 @@ export function registerMeshFunction(
const existing = await kv.get<MemoryRelation>(KV.relations, relKey);
if (!existing) {
await kv.set(KV.relations, relKey, rel);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-receive", [relKey], {
+ action: "mesh.receive.relation",
+ accepted: true,
+ });
accepted++;
}
});
@@ -327,18 +362,24 @@ export function registerMeshFunction(
}
accepted += await lwwMergeGraphNodes(kv, data.graphNodes);
accepted += await lwwMergeList(kv, KV.graphEdges, data.graphEdges, "mem:gedge", "createdAt");
+ await recordAudit(kv, "mesh_sync", "mem::mesh-receive", [], {
+ action: "mesh.receive",
+ accepted,
+ });
return { success: true, accepted };
},
);
- sdk.registerFunction(
- { id: "mem::mesh-remove" },
+ sdk.registerFunction("mem::mesh-remove",
async (data: { peerId: string }) => {
- if (!data.peerId) {
+ if (!data || typeof data !== "object" || !data.peerId) {
return { success: false, error: "peerId is required" };
}
await kv.delete(KV.mesh, data.peerId);
+ await recordAudit(kv, "mesh_sync", "mem::mesh-remove", [data.peerId], {
+ action: "mesh.remove",
+ });
return { success: true };
},
);
diff --git a/src/functions/migrate.ts b/src/functions/migrate.ts
index cb7f28ab..fc2a87c7 100644
--- a/src/functions/migrate.ts
+++ b/src/functions/migrate.ts
@@ -18,11 +18,7 @@ function isAllowedPath(dbPath: string): boolean {
}
export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::migrate",
- description: "Import data from SQLite database",
- },
+ sdk.registerFunction("mem::migrate",
async (data: { dbPath: string }) => {
const ctx = getContext();
ctx.logger.info("Migration started", { dbPath: data.dbPath });
@@ -51,8 +47,9 @@ export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
return { success: false, error: `Database not found: ${data.dbPath}` };
}
+ let db: any;
try {
- const db = Database(data.dbPath, { readonly: true });
+ db = Database(data.dbPath, { readonly: true });
let sessionCount = 0;
let obsCount = 0;
let summaryCount = 0;
@@ -136,7 +133,6 @@ export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
summaryCount++;
}
- db.close();
ctx.logger.info("Migration complete", {
sessionCount,
obsCount,
@@ -147,6 +143,10 @@ export function registerMigrateFunction(sdk: ISdk, kv: StateKV): void {
const msg = err instanceof Error ? err.message : String(err);
ctx.logger.error("Migration failed", { error: msg });
return { success: false, error: "Migration failed" };
+ } finally {
+ try {
+ if (db) db.close();
+ } catch {}
}
},
);
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index 74f74362..f4d2a036 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -1,6 +1,5 @@
-import type { ISdk } from "iii-sdk";
-import { getContext } from "iii-sdk";
-import type { RawObservation, HookPayload, Session } from "../types.js";
+import { TriggerAction, getContext, type ISdk } from "iii-sdk";
+import type { RawObservation, HookPayload } from "../types.js";
import { KV, STREAM, generateId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { stripPrivateData } from "./privacy.js";
@@ -16,11 +15,7 @@ export function registerObserveFunction(
dedupMap?: DedupMap,
maxObservationsPerSession?: number,
): void {
- sdk.registerFunction(
- {
- id: "mem::observe",
- description: "Capture and store a tool-use observation",
- },
+ sdk.registerFunction("mem::observe",
async (payload: HookPayload) => {
const ctx = getContext();
@@ -107,26 +102,41 @@ export function registerObserveFunction(
dedupMap.record(dedupHash);
}
- sdk.triggerVoid("stream::set", {
+ await sdk.trigger({
+ function_id: "stream::set",
+ payload: {
stream_name: STREAM.name,
group_id: STREAM.group(payload.sessionId),
item_id: obsId,
data: { type: "raw", observation: raw },
+ },
});
- sdk.triggerVoid("stream::set", {
- stream_name: STREAM.name,
- group_id: STREAM.viewerGroup,
- item_id: obsId,
- data: { type: "raw", observation: raw, sessionId: payload.sessionId },
+ await sdk.trigger({
+ function_id: "stream::send",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ id: `raw-${obsId}`,
+ type: "raw_observation",
+ data: { type: "raw", observation: raw, sessionId: payload.sessionId },
+ },
+ action: TriggerAction.Void(),
});
- const session = await kv.get<Session>(KV.sessions, payload.sessionId);
+ const session = await kv.get<{ observationCount?: number }>(
+ KV.sessions,
+ payload.sessionId,
+ );
if (session) {
- await kv.set(KV.sessions, payload.sessionId, {
- ...session,
- observationCount: (session.observationCount || 0) + 1,
- });
+ await kv.update(KV.sessions, payload.sessionId, [
+ { type: "set", path: "updatedAt", value: new Date().toISOString() },
+ {
+ type: "set",
+ path: "observationCount",
+ value: (session.observationCount || 0) + 1,
+ },
+ ]);
}
// Per-observation LLM compression is opt-in as of 0.8.8 (#138).
@@ -134,10 +144,14 @@ export function registerObserveFunction(
// and BM25 search still work without burning the user's Claude
// token allocation on every tool invocation.
if (isAutoCompressEnabled()) {
- sdk.triggerVoid("mem::compress", {
- observationId: obsId,
- sessionId: payload.sessionId,
- raw,
+ await sdk.trigger({
+ function_id: "mem::compress",
+ payload: {
+ observationId: obsId,
+ sessionId: payload.sessionId,
+ raw,
+ },
+ action: TriggerAction.Void(),
});
} else {
const synthetic = buildSyntheticCompression(raw);
@@ -147,20 +161,26 @@ export function registerObserveFunction(
synthetic,
);
getSearchIndex().add(synthetic);
- sdk.triggerVoid("stream::set", {
- stream_name: STREAM.name,
- group_id: STREAM.group(payload.sessionId),
- item_id: obsId,
- data: { type: "compressed", observation: synthetic },
+ await sdk.trigger({
+ function_id: "stream::set",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.group(payload.sessionId),
+ item_id: obsId,
+ data: { type: "compressed", observation: synthetic },
+ },
});
- sdk.triggerVoid("stream::set", {
- stream_name: STREAM.name,
- group_id: STREAM.viewerGroup,
- item_id: obsId,
- data: {
- type: "compressed",
- observation: synthetic,
- sessionId: payload.sessionId,
+ await sdk.trigger({
+ function_id: "stream::set",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ item_id: obsId,
+ data: {
+ type: "compressed",
+ observation: synthetic,
+ sessionId: payload.sessionId,
+ },
},
});
}
diff --git a/src/functions/obsidian-export.ts b/src/functions/obsidian-export.ts
index 6fabfb6f..c9a0d29f 100644
--- a/src/functions/obsidian-export.ts
+++ b/src/functions/obsidian-export.ts
@@ -197,9 +197,23 @@ export function registerObsidianExportFunction(
sdk: ISdk,
kv: StateKV,
): void {
- sdk.registerFunction(
- { id: "mem::obsidian-export" },
- async (data: { vaultDir?: string; types?: string[] }) => {
+ sdk.registerFunction("mem::obsidian-export",
+ async (data: { vaultDir?: string; types?: string[] } | undefined) => {
+ if (!data || typeof data !== "object") {
+ return { success: false, error: "payload is required" };
+ }
+ if (data.vaultDir !== undefined && typeof data.vaultDir !== "string") {
+ return { success: false, error: "vaultDir must be a string" };
+ }
+ if (data.types !== undefined) {
+ if (
+ !Array.isArray(data.types) ||
+ !data.types.every((t): t is string => typeof t === "string")
+ ) {
+ return { success: false, error: "types must be an array of strings" };
+ }
+ }
+
const vaultDir = resolveVaultDir(data.vaultDir);
if (!vaultDir) {
return {
@@ -208,7 +222,7 @@ export function registerObsidianExportFunction(
};
}
const exportTypes = new Set(
- data.types || ["memories", "lessons", "crystals", "sessions"],
+ data.types ?? ["memories", "lessons", "crystals", "sessions"],
);
const dirs = {
diff --git a/src/functions/patterns.ts b/src/functions/patterns.ts
index 97ef4345..d540501e 100644
--- a/src/functions/patterns.ts
+++ b/src/functions/patterns.ts
@@ -13,8 +13,7 @@ interface Pattern {
}
export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::patterns" },
+ sdk.registerFunction("mem::patterns",
async (data: { project?: string }) => {
const ctx = getContext();
const patterns: Pattern[] = [];
@@ -107,14 +106,13 @@ export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::generate-rules" },
+ sdk.registerFunction("mem::generate-rules",
async (data: { project?: string }) => {
const ctx = getContext();
const result = await sdk.trigger<
{ project?: string },
{ patterns: Pattern[] }
- >("mem::patterns", data);
+ >({ function_id: "mem::patterns", payload: data });
const rules: string[] = [];
diff --git a/src/functions/privacy.ts b/src/functions/privacy.ts
index 8731cea8..f28edd3e 100644
--- a/src/functions/privacy.ts
+++ b/src/functions/privacy.ts
@@ -29,12 +29,11 @@ export function stripPrivateData(input: string): string {
}
export function registerPrivacyFunction(sdk: ISdk): void {
- sdk.registerFunction(
- {
- id: "mem::privacy",
- description: "Strip private tags and secrets from input",
- },
- async (data: { input: string }) => {
+ sdk.registerFunction("mem::privacy",
+ async (data: { input?: unknown } | undefined) => {
+ if (!data || typeof data.input !== "string") {
+ return { output: "", error: "invalid input: expected string field 'input'" };
+ }
return { output: stripPrivateData(data.input) };
},
);
diff --git a/src/functions/profile.ts b/src/functions/profile.ts
index 245d012c..3769efe5 100644
--- a/src/functions/profile.ts
+++ b/src/functions/profile.ts
@@ -7,19 +7,20 @@ import type {
} from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
export function registerProfileFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::profile",
- description: "Generate or retrieve a project profile from aggregated data",
- },
- async (data: { project: string; refresh?: boolean }) => {
+ sdk.registerFunction("mem::profile",
+ async (data: { project: string; refresh?: boolean } | undefined) => {
const ctx = getContext();
+ if (!data || typeof data.project !== "string" || !data.project.trim()) {
+ return { success: false, error: "project is required" };
+ }
+ const project = data.project.trim();
if (!data.refresh) {
const cached = await kv
- .get<ProjectProfile>(KV.profiles, data.project)
+ .get<ProjectProfile>(KV.profiles, project)
.catch(() => null);
if (cached) {
const age = Date.now() - new Date(cached.updatedAt).getTime();
@@ -31,7 +32,7 @@ export function registerProfileFunction(sdk: ISdk, kv: StateKV): void {
const sessions = await kv.list<Session>(KV.sessions);
const projectSessions = sessions.filter(
- (s) => s.project === data.project,
+ (s) => s.project === project,
);
if (projectSessions.length === 0) {
@@ -98,7 +99,7 @@ export function registerProfileFunction(sdk: ISdk, kv: StateKV): void {
const uniqueErrors = [...new Set(errors)].slice(0, 10);
const profile: ProjectProfile = {
- project: data.project,
+ project,
updatedAt: new Date().toISOString(),
topConcepts,
topFiles,
@@ -109,10 +110,14 @@ export function registerProfileFunction(sdk: ISdk, kv: StateKV): void {
totalObservations: totalObs,
};
- await kv.set(KV.profiles, data.project, profile);
+ await kv.set(KV.profiles, project, profile);
+ await recordAudit(kv, "share", "mem::profile", [project], {
+ sessionCount: projectSessions.length,
+ totalObservations: totalObs,
+ });
ctx.logger.info("Profile generated", {
- project: data.project,
+ project,
sessions: projectSessions.length,
observations: totalObs,
});
diff --git a/src/functions/query-expansion.ts b/src/functions/query-expansion.ts
index ee2de879..10949628 100644
--- a/src/functions/query-expansion.ts
+++ b/src/functions/query-expansion.ts
@@ -70,20 +70,23 @@ export function registerQueryExpansionFunction(
sdk: ISdk,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- {
- id: "mem::expand-query",
- description:
- "Generate diverse query reformulations for improved recall",
- },
- async (data: { query: string; maxReformulations?: number }) => {
+ sdk.registerFunction("mem::expand-query",
+ async (data: { query: string; maxReformulations?: number } | undefined) => {
const ctx = getContext();
- const maxR = data.maxReformulations ?? 5;
+ if (!data || typeof data.query !== "string" || !data.query.trim()) {
+ ctx.logger.warn("Invalid expand-query payload");
+ return { success: false, error: "query must be a non-empty string" };
+ }
+ const rawMaxR = Number(data.maxReformulations);
+ const maxR = Number.isFinite(rawMaxR)
+ ? Math.max(1, Math.min(10, Math.floor(rawMaxR)))
+ : 5;
+ const query = data.query.trim();
try {
const response = await provider.compress(
QUERY_EXPANSION_SYSTEM,
- `Expand this query for memory retrieval:\n\n"${data.query}"`,
+ `Expand this query for memory retrieval:\n\n"${query}"`,
);
const parsed = parseExpansionXml(response);
@@ -92,7 +95,7 @@ export function registerQueryExpansionFunction(
return {
success: true,
expansion: {
- original: data.query,
+ original: query,
reformulations: [],
temporalConcretizations: [],
entityExtractions: [],
@@ -100,11 +103,11 @@ export function registerQueryExpansionFunction(
};
}
- parsed.original = data.query;
+ parsed.original = query;
parsed.reformulations = parsed.reformulations.slice(0, maxR);
ctx.logger.info("Query expanded", {
- original: data.query,
+ original: query,
reformulations: parsed.reformulations.length,
entities: parsed.entityExtractions.length,
});
@@ -116,7 +119,7 @@ export function registerQueryExpansionFunction(
return {
success: true,
expansion: {
- original: data.query,
+ original: query,
reformulations: [],
temporalConcretizations: [],
entityExtractions: [],
diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts
index a7c47852..3a2af829 100644
--- a/src/functions/reflect.ts
+++ b/src/functions/reflect.ts
@@ -165,8 +165,7 @@ export function registerReflectFunctions(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- { id: "mem::reflect" },
+ sdk.registerFunction("mem::reflect",
async (data: { maxClusters?: number; project?: string }) => {
const maxClusters = Math.min(data?.maxClusters ?? 10, 20);
const maxInsightsPerCluster = 5;
@@ -335,8 +334,7 @@ export function registerReflectFunctions(
},
);
- sdk.registerFunction(
- { id: "mem::insight-list" },
+ sdk.registerFunction("mem::insight-list",
async (data: {
project?: string;
minConfidence?: number;
@@ -360,8 +358,7 @@ export function registerReflectFunctions(
},
);
- sdk.registerFunction(
- { id: "mem::insight-search" },
+ sdk.registerFunction("mem::insight-search",
async (data: {
query: string;
project?: string;
@@ -425,8 +422,7 @@ export function registerReflectFunctions(
},
);
- sdk.registerFunction(
- { id: "mem::insight-decay-sweep" },
+ sdk.registerFunction("mem::insight-decay-sweep",
async () => {
const items = await kv.list<Insight>(KV.insights);
let decayed = 0;
@@ -467,6 +463,13 @@ export function registerReflectFunctions(
}
await Promise.all(dirty.map((i) => kv.set(KV.insights, i.id, i)));
+ await recordAudit(kv, "reflect", "mem::insight-decay-sweep", dirty.map((i) => i.id), {
+ event: "insight.decay",
+ decayed,
+ softDeleted,
+ total: items.length,
+ timestamp,
+ });
return { success: true, decayed, softDeleted, total: items.length };
},
diff --git a/src/functions/relations.ts b/src/functions/relations.ts
index 1ae5c25a..2636347b 100644
--- a/src/functions/relations.ts
+++ b/src/functions/relations.ts
@@ -4,6 +4,7 @@ import type { Memory, MemoryRelation } from "../types.js";
import { KV, generateId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { safeAudit } from "./audit.js";
import { recordAccessBatch } from "./access-tracker.js";
function computeConfidence(
@@ -36,11 +37,7 @@ function computeConfidence(
}
export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::relate",
- description: "Create a relationship between memories",
- },
+ sdk.registerFunction("mem::relate",
async (data: {
sourceId: string;
targetId: string;
@@ -49,60 +46,88 @@ export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {
}) => {
const ctx = getContext();
const [firstId, secondId] = [data.sourceId, data.targetId].sort();
-
- return withKeyedLock(`mem:${firstId}`, () =>
- withKeyedLock(`mem:${secondId}`, async () => {
- const source = await kv.get<Memory>(KV.memories, data.sourceId);
- const target = await kv.get<Memory>(KV.memories, data.targetId);
- if (!source || !target) {
- return {
- success: false,
- error: "source or target memory not found",
- };
- }
-
- const confidence =
- data.confidence !== undefined
- ? Math.max(0, Math.min(1, data.confidence))
- : computeConfidence(source, target, data.type);
-
- const relation: MemoryRelation = {
- type: data.type,
- sourceId: data.sourceId,
- targetId: data.targetId,
- createdAt: new Date().toISOString(),
- confidence,
+ const lockKey =
+ firstId === secondId ? `mem:${firstId}` : `mem:${firstId}:${secondId}`;
+
+ return withKeyedLock(lockKey, async () => {
+ const source = await kv.get<Memory>(KV.memories, data.sourceId);
+ const target = await kv.get<Memory>(KV.memories, data.targetId);
+ if (!source || !target) {
+ return {
+ success: false,
+ error: "source or target memory not found",
};
+ }
- const relationId = generateId("rel");
- await kv.set(KV.relations, relationId, relation);
+ const confidence =
+ data.confidence !== undefined
+ ? Math.max(0, Math.min(1, data.confidence))
+ : computeConfidence(source, target, data.type);
+
+ const relation: MemoryRelation = {
+ type: data.type,
+ sourceId: data.sourceId,
+ targetId: data.targetId,
+ createdAt: new Date().toISOString(),
+ confidence,
+ };
+
+ const relationId = generateId("rel");
+ await kv.set(KV.relations, relationId, relation);
+
+ if (!source.relatedIds) source.relatedIds = [];
+ let sourceUpdated = false;
+ if (!source.relatedIds.includes(data.targetId)) {
+ source.relatedIds.push(data.targetId);
+ await kv.set(KV.memories, data.sourceId, source);
+ sourceUpdated = true;
+ }
- if (!source.relatedIds) source.relatedIds = [];
- if (!source.relatedIds.includes(data.targetId)) {
- source.relatedIds.push(data.targetId);
- await kv.set(KV.memories, data.sourceId, source);
- }
+ if (!target.relatedIds) target.relatedIds = [];
+ let targetUpdated = false;
+ if (!target.relatedIds.includes(data.sourceId)) {
+ target.relatedIds.push(data.sourceId);
+ await kv.set(KV.memories, data.targetId, target);
+ targetUpdated = true;
+ }
- if (!target.relatedIds) target.relatedIds = [];
- if (!target.relatedIds.includes(data.sourceId)) {
- target.relatedIds.push(data.sourceId);
- await kv.set(KV.memories, data.targetId, target);
- }
+ await safeAudit(kv, "relation_create", "mem::relate", [relationId], {
+ type: data.type,
+ sourceId: data.sourceId,
+ targetId: data.targetId,
+ confidence,
+ });
+ if (sourceUpdated) {
+ await safeAudit(
+ kv,
+ "relation_update",
+ "mem::relate",
+ [data.sourceId],
+ { relationId, updatedRelatedId: data.targetId },
+ );
+ }
+ if (targetUpdated) {
+ await safeAudit(
+ kv,
+ "relation_update",
+ "mem::relate",
+ [data.targetId],
+ { relationId, updatedRelatedId: data.sourceId },
+ );
+ }
- ctx.logger.info("Memory relation created", {
- relationId,
- type: data.type,
- source: data.sourceId,
- target: data.targetId,
- });
- return { success: true, relationId, relation };
- }),
- );
+ ctx.logger.info("Memory relation created", {
+ relationId,
+ type: data.type,
+ source: data.sourceId,
+ target: data.targetId,
+ });
+ return { success: true, relationId, relation };
+ });
},
);
- sdk.registerFunction(
- { id: "mem::evolve", description: "Create a new version of a memory" },
+ sdk.registerFunction("mem::evolve",
async (data: {
memoryId: string;
newContent: string;
@@ -131,8 +156,19 @@ export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {
existing.isLatest = false;
await kv.set(KV.memories, existing.id, existing);
+ await safeAudit(kv, "evolve", "mem::evolve", [existing.id], {
+ operation: "evolve",
+ action: "mark_non_latest",
+ newId: evolved.id,
+ });
await kv.set(KV.memories, evolved.id, evolved);
+ await safeAudit(kv, "evolve", "mem::evolve", [evolved.id], {
+ operation: "evolve",
+ oldId: existing.id,
+ newId: evolved.id,
+ version: evolved.version,
+ });
const relation: MemoryRelation = {
type: "supersedes",
@@ -141,7 +177,13 @@ export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {
createdAt: now,
confidence: 1.0,
};
- await kv.set(KV.relations, generateId("rel"), relation);
+ const relationId = generateId("rel");
+ await kv.set(KV.relations, relationId, relation);
+ await safeAudit(kv, "evolve", "mem::evolve", [relationId], {
+ operation: "supersedes",
+ oldId: existing.id,
+ newId: evolved.id,
+ });
ctx.logger.info("Memory evolved", {
oldId: existing.id,
@@ -152,11 +194,7 @@ export function registerRelationsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- {
- id: "mem::get-related",
- description: "Get related memories within N hops",
- },
+ sdk.registerFunction("mem::get-related",
async (data: {
memoryId: string;
maxHops?: number;
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index c6b9bf47..29290fb4 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -1,5 +1,4 @@
-import type { ISdk } from "iii-sdk";
-import { getContext } from "iii-sdk";
+import { TriggerAction, getContext, type ISdk } from "iii-sdk";
import type { Memory } from "../types.js";
import { KV, generateId, jaccardSimilarity } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
@@ -7,8 +6,7 @@ import { withKeyedLock } from "../state/keyed-mutex.js";
import { deleteAccessLog } from "./access-tracker.js";
export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::remember" },
+ sdk.registerFunction("mem::remember",
async (data: {
content: string;
type?: string;
@@ -99,8 +97,12 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
await kv.set(KV.memories, memory.id, memory);
if (supersededId) {
- sdk.triggerVoid("mem::cascade-update", {
- supersededMemoryId: supersededId,
+ await sdk.trigger({
+ function_id: "mem::cascade-update",
+ payload: {
+ supersededMemoryId: supersededId,
+ },
+ action: TriggerAction.Void(),
});
}
@@ -113,8 +115,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::forget" },
+ sdk.registerFunction("mem::forget",
async (data: {
sessionId?: string;
observationIds?: string[];
diff --git a/src/functions/retention.ts b/src/functions/retention.ts
index 3dc0a6a5..5deb04b0 100644
--- a/src/functions/retention.ts
+++ b/src/functions/retention.ts
@@ -26,6 +26,41 @@ const DEFAULT_DECAY: DecayConfig = {
},
};
+function resolveDecayConfig(
+ input?: Partial<DecayConfig>,
+): { config: DecayConfig } | { error: string } {
+ const tierThresholds = {
+ ...DEFAULT_DECAY.tierThresholds,
+ ...(input?.tierThresholds ?? {}),
+ };
+ const config: DecayConfig = {
+ lambda:
+ typeof input?.lambda === "number" ? input.lambda : DEFAULT_DECAY.lambda,
+ sigma: typeof input?.sigma === "number" ? input.sigma : DEFAULT_DECAY.sigma,
+ tierThresholds,
+ };
+
+ if (!Number.isFinite(config.lambda) || config.lambda <= 0) {
+ return { error: "config.lambda must be a positive number" };
+ }
+ if (!Number.isFinite(config.sigma) || config.sigma < 0) {
+ return { error: "config.sigma must be a non-negative number" };
+ }
+ const { hot, warm, cold } = config.tierThresholds;
+ if (![hot, warm, cold].every((v) => Number.isFinite(v))) {
+ return {
+ error: "config.tierThresholds.hot/warm/cold must be finite numbers",
+ };
+ }
+ if (!(hot >= warm && warm >= cold && cold >= 0)) {
+ return {
+ error:
+ "config.tierThresholds must satisfy hot >= warm >= cold >= 0",
+ };
+ }
+ return { config };
+}
+
function computeReinforcementBoost(
accessTimestamps: number[],
sigma: number,
@@ -88,15 +123,14 @@ export function registerRetentionFunctions(
sdk: ISdk,
kv: StateKV,
): void {
- sdk.registerFunction(
- {
- id: "mem::retention-score",
- description:
- "Compute retention scores for all memories using time-frequency decay",
- },
+ sdk.registerFunction("mem::retention-score",
async (data: { config?: Partial<DecayConfig> }) => {
const ctx = getContext();
- const config = { ...DEFAULT_DECAY, ...data.config };
+ const resolved = resolveDecayConfig(data?.config);
+ if ("error" in resolved) {
+ return { success: false, error: resolved.error };
+ }
+ const { config } = resolved;
const [memories, semanticMems, allLogs] = await Promise.all([
kv.list<Memory>(KV.memories),
@@ -255,20 +289,22 @@ export function registerRetentionFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::retention-evict",
- description:
- "Evict memories below retention threshold (tiered storage)",
- },
- async (data: {
+ sdk.registerFunction("mem::retention-evict",
+ async (data?: {
threshold?: number;
dryRun?: boolean;
maxEvict?: number;
}) => {
const ctx = getContext();
- const threshold = data.threshold ?? DEFAULT_DECAY.tierThresholds.cold;
- const maxEvict = data.maxEvict ?? 50;
+ const threshold =
+ typeof data?.threshold === "number" && Number.isFinite(data.threshold)
+ ? data.threshold
+ : DEFAULT_DECAY.tierThresholds.cold;
+ const maxEvictRaw =
+ typeof data?.maxEvict === "number" && Number.isInteger(data.maxEvict)
+ ? data.maxEvict
+ : 50;
+ const maxEvict = Math.min(1000, Math.max(0, maxEvictRaw));
const allScores = await kv.list<RetentionScore>(KV.retentionScores);
const candidates = allScores
@@ -276,7 +312,7 @@ export function registerRetentionFunctions(
.sort((a, b) => a.score - b.score)
.slice(0, maxEvict);
- if (data.dryRun) {
+ if (data?.dryRun) {
return {
success: true,
dryRun: true,
diff --git a/src/functions/routines.ts b/src/functions/routines.ts
index e84f33c3..d1a9135a 100644
--- a/src/functions/routines.ts
+++ b/src/functions/routines.ts
@@ -3,10 +3,10 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, Routine, RoutineStep, RoutineRun } from "../types.js";
+import { recordAudit } from "./audit.js";
export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::routine-create" },
+ sdk.registerFunction("mem::routine-create",
async (data: {
name: string;
description?: string;
@@ -60,12 +60,15 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.routines, routine.id, routine);
+ await recordAudit(kv, "routine_run", "mem::routine-create", [routine.id], {
+ action: "routine.create",
+ stepCount: routine.steps.length,
+ });
return { success: true, routine };
},
);
- sdk.registerFunction(
- { id: "mem::routine-list" },
+ sdk.registerFunction("mem::routine-list",
async (data: { frozen?: boolean; tags?: string[] }) => {
let routines = await kv.list<Routine>(KV.routines);
if (data.frozen !== undefined) {
@@ -84,8 +87,7 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::routine-run" },
+ sdk.registerFunction("mem::routine-run",
async (data: {
routineId: string;
initiatedBy?: string;
@@ -171,6 +173,12 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.routineRuns, run.id, run);
+ await recordAudit(kv, "routine_run", "mem::routine-run", [run.id], {
+ action: "routine.run",
+ routineId: routine.id,
+ actionIds,
+ initiatedBy: data.initiatedBy || "unknown",
+ });
return {
success: true,
@@ -181,8 +189,7 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::routine-status" },
+ sdk.registerFunction("mem::routine-status",
async (data: { runId: string }) => {
if (!data.runId) {
return { success: false, error: "runId is required" };
@@ -250,6 +257,10 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
if (statusChanged) {
await kv.set(KV.routineRuns, run.id, run);
+ await recordAudit(kv, "routine_run", "mem::routine-status", [run.id], {
+ action: "routine.status",
+ status: run.status,
+ });
}
return {
@@ -268,8 +279,7 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::routine-freeze" },
+ sdk.registerFunction("mem::routine-freeze",
async (data: { routineId: string }) => {
if (!data.routineId) {
return { success: false, error: "routineId is required" };
@@ -282,6 +292,10 @@ export function registerRoutinesFunction(sdk: ISdk, kv: StateKV): void {
routine.frozen = true;
routine.updatedAt = new Date().toISOString();
await kv.set(KV.routines, routine.id, routine);
+ await recordAudit(kv, "routine_run", "mem::routine-freeze", [routine.id], {
+ action: "routine.freeze",
+ frozen: true,
+ });
return { success: true, routine };
});
},
diff --git a/src/functions/sentinels.ts b/src/functions/sentinels.ts
index f16c8147..ed29aee9 100644
--- a/src/functions/sentinels.ts
+++ b/src/functions/sentinels.ts
@@ -3,6 +3,7 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge, Checkpoint, CompressedObservation, FunctionMetrics, Sentinel, Session } from "../types.js";
+import { recordAudit } from "./audit.js";
const VALID_TYPES: Sentinel["type"][] = [
"webhook",
@@ -14,8 +15,7 @@ const VALID_TYPES: Sentinel["type"][] = [
];
export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::sentinel-create" },
+ sdk.registerFunction("mem::sentinel-create",
async (data: {
name: string;
type: Sentinel["type"];
@@ -108,6 +108,11 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.sentinels, sentinel.id, sentinel);
+ await recordAudit(kv, "sentinel_create", "mem::sentinel-create", [sentinel.id], {
+ action: "sentinel.create",
+ type: sentinel.type,
+ linkedActionIds: sentinel.linkedActionIds,
+ });
if (data.linkedActionIds && data.linkedActionIds.length > 0) {
for (const actionId of data.linkedActionIds) {
@@ -119,21 +124,35 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
createdAt: now.toISOString(),
};
await kv.set(KV.actionEdges, edge.id, edge);
+ await recordAudit(kv, "sentinel_create", "mem::sentinel-create", [edge.id], {
+ action: "sentinel.create.edge",
+ sentinelId: sentinel.id,
+ sourceActionId: actionId,
+ });
}
}
if (data.type === "timer") {
const durationMs = (data.config as { durationMs: number }).durationMs;
setTimeout(async () => {
- await withKeyedLock(`mem:sentinel:${sentinel.id}`, async () => {
- const fresh = await kv.get<Sentinel>(KV.sentinels, sentinel.id);
- if (!fresh || fresh.status !== "watching") return;
- fresh.status = "triggered";
- fresh.triggeredAt = new Date().toISOString();
- fresh.result = { reason: "timer_elapsed", durationMs };
- await kv.set(KV.sentinels, fresh.id, fresh);
- await unblockLinkedActions(kv, fresh);
- });
+ try {
+ await withKeyedLock(`mem:sentinel:${sentinel.id}`, async () => {
+ const fresh = await kv.get<Sentinel>(KV.sentinels, sentinel.id);
+ if (!fresh || fresh.status !== "watching") return;
+ fresh.status = "triggered";
+ fresh.triggeredAt = new Date().toISOString();
+ fresh.result = { reason: "timer_elapsed", durationMs };
+ await kv.set(KV.sentinels, fresh.id, fresh);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-create", [fresh.id], {
+ action: "sentinel.timer_trigger",
+ reason: "timer_elapsed",
+ durationMs,
+ });
+ await unblockLinkedActions(kv, fresh);
+ });
+ } catch (err) {
+ console.error("sentinel timer callback failed", sentinel.id, err);
+ }
}, durationMs);
}
@@ -141,8 +160,7 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sentinel-trigger" },
+ sdk.registerFunction("mem::sentinel-trigger",
async (data: { sentinelId: string; result?: unknown }) => {
if (!data.sentinelId) {
return { success: false, error: "sentinelId is required" };
@@ -170,6 +188,10 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
sentinel.result = data.result;
await kv.set(KV.sentinels, sentinel.id, sentinel);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-trigger", [sentinel.id], {
+ action: "sentinel.trigger",
+ result: data.result,
+ });
let unblockedCount = 0;
if (sentinel.linkedActionIds.length > 0) {
@@ -182,8 +204,7 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sentinel-check" },
+ sdk.registerFunction("mem::sentinel-check",
async () => {
const sentinels = await kv.list<Sentinel>(KV.sentinels);
const active = sentinels.filter((s) => s.status === "watching");
@@ -227,6 +248,10 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
operator: cfg.operator,
};
await kv.set(KV.sentinels, fresh.id, fresh);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-check", [fresh.id], {
+ action: "sentinel.threshold_trigger",
+ result: fresh.result,
+ });
await unblockLinkedActions(kv, fresh);
},
);
@@ -275,6 +300,10 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
matchedTitle: matchedObs!.title,
};
await kv.set(KV.sentinels, fresh.id, fresh);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-check", [fresh.id], {
+ action: "sentinel.pattern_trigger",
+ result: fresh.result,
+ });
await unblockLinkedActions(kv, fresh);
},
);
@@ -287,8 +316,7 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sentinel-cancel" },
+ sdk.registerFunction("mem::sentinel-cancel",
async (data: { sentinelId: string }) => {
if (!data.sentinelId) {
return { success: false, error: "sentinelId is required" };
@@ -313,6 +341,10 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
sentinel.status = "cancelled";
await kv.set(KV.sentinels, sentinel.id, sentinel);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-cancel", [sentinel.id], {
+ action: "sentinel.cancel",
+ status: "cancelled",
+ });
return { success: true, sentinel };
},
@@ -320,8 +352,7 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sentinel-list" },
+ sdk.registerFunction("mem::sentinel-list",
async (data: { status?: string; type?: string }) => {
let sentinels = await kv.list<Sentinel>(KV.sentinels);
@@ -341,8 +372,7 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sentinel-expire" },
+ sdk.registerFunction("mem::sentinel-expire",
async () => {
const sentinels = await kv.list<Sentinel>(KV.sentinels);
const now = Date.now();
@@ -365,6 +395,10 @@ export function registerSentinelsFunction(sdk: ISdk, kv: StateKV): void {
fresh.status = "expired";
fresh.triggeredAt = new Date().toISOString();
await kv.set(KV.sentinels, fresh.id, fresh);
+ await recordAudit(kv, "sentinel_trigger", "mem::sentinel-expire", [fresh.id], {
+ action: "sentinel.expire",
+ status: "expired",
+ });
return true;
},
);
@@ -407,6 +441,10 @@ async function unblockLinkedActions(
action.status = "pending";
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await recordAudit(kv, "action_update", "mem::sentinel-unblock", [action.id], {
+ action: "action.unblocked",
+ sentinelId: sentinel.id,
+ });
unblockedCount++;
}
}
diff --git a/src/functions/signals.ts b/src/functions/signals.ts
index 4a3b15b5..6abf746c 100644
--- a/src/functions/signals.ts
+++ b/src/functions/signals.ts
@@ -2,10 +2,10 @@ import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import type { Signal } from "../types.js";
+import { recordAudit } from "./audit.js";
export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::signal-send" },
+ sdk.registerFunction("mem::signal-send",
async (data: {
from: string;
to?: string;
@@ -46,13 +46,18 @@ export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.signals, signal.id, signal);
+ await recordAudit(kv, "signal_send", "mem::signal-send", [signal.id], {
+ action: "create",
+ from: data.from,
+ to: data.to,
+ type: signal.type,
+ });
return { success: true, signal };
},
);
- sdk.registerFunction(
- { id: "mem::signal-read" },
+ sdk.registerFunction("mem::signal-read",
async (data: {
agentId: string;
unreadOnly?: boolean;
@@ -95,7 +100,14 @@ export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
for (const sig of results) {
if (!sig.readAt && sig.to === data.agentId) {
+ const beforeReadAt = sig.readAt;
sig.readAt = new Date().toISOString();
+ await recordAudit(kv, "signal_send", "mem::signal-read", [sig.id], {
+ action: "signal.mark_read",
+ actor: data.agentId,
+ beforeReadAt,
+ afterReadAt: sig.readAt,
+ });
await kv.set(KV.signals, sig.id, sig);
}
}
@@ -104,8 +116,7 @@ export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::signal-threads" },
+ sdk.registerFunction("mem::signal-threads",
async (data: { agentId: string; limit?: number }) => {
if (!data.agentId) {
return { success: false, error: "agentId is required" };
@@ -166,8 +177,7 @@ export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::signal-cleanup" },
+ sdk.registerFunction("mem::signal-cleanup",
async () => {
const signals = await kv.list<Signal>(KV.signals);
const now = Date.now();
@@ -175,6 +185,11 @@ export function registerSignalsFunction(sdk: ISdk, kv: StateKV): void {
for (const sig of signals) {
if (sig.expiresAt && new Date(sig.expiresAt).getTime() <= now) {
+ await recordAudit(kv, "delete", "mem::signal-cleanup", [sig.id], {
+ action: "delete",
+ resource: "Signal",
+ before: sig,
+ });
await kv.delete(KV.signals, sig.id);
removed++;
}
diff --git a/src/functions/sketches.ts b/src/functions/sketches.ts
index d8b675ed..c617a298 100644
--- a/src/functions/sketches.ts
+++ b/src/functions/sketches.ts
@@ -3,10 +3,10 @@ import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
import type { Action, ActionEdge, Sketch } from "../types.js";
+import { safeAudit } from "./audit.js";
export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::sketch-create" },
+ sdk.registerFunction("mem::sketch-create",
async (data: {
title: string;
description?: string;
@@ -31,12 +31,15 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
};
await kv.set(KV.sketches, sketch.id, sketch);
+ await safeAudit(kv, "sketch_create", "mem::sketch-create", [sketch.id], {
+ action: "create",
+ title: sketch.title,
+ });
return { success: true, sketch };
},
);
- sdk.registerFunction(
- { id: "mem::sketch-add" },
+ sdk.registerFunction("mem::sketch-add",
async (data: {
sketchId: string;
title: string;
@@ -90,6 +93,10 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
}
await kv.set(KV.actions, action.id, action);
+ await safeAudit(kv, "sketch_create", "mem::sketch-add", [action.id], {
+ action: "add.action",
+ sketchId: sketch.id,
+ });
const createdEdges: ActionEdge[] = [];
if (data.dependsOn && data.dependsOn.length > 0) {
@@ -102,20 +109,27 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
createdAt: now,
};
await kv.set(KV.actionEdges, edge.id, edge);
+ await safeAudit(kv, "sketch_create", "mem::sketch-add", [edge.id], {
+ action: "add.edge",
+ sketchId: sketch.id,
+ });
createdEdges.push(edge);
}
}
sketch.actionIds.push(action.id);
await kv.set(KV.sketches, sketch.id, sketch);
+ await safeAudit(kv, "sketch_create", "mem::sketch-add", [sketch.id], {
+ action: "add.sketch-update",
+ addedActionId: action.id,
+ });
return { success: true, action, edges: createdEdges };
});
},
);
- sdk.registerFunction(
- { id: "mem::sketch-promote" },
+ sdk.registerFunction("mem::sketch-promote",
async (data: { sketchId: string; project?: string }) => {
if (!data.sketchId) {
return { success: false, error: "sketchId is required" };
@@ -140,6 +154,10 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
}
action.updatedAt = new Date().toISOString();
await kv.set(KV.actions, action.id, action);
+ await safeAudit(kv, "sketch_promote", "mem::sketch-promote", [action.id], {
+ action: "promote.action",
+ sketchId: sketch.id,
+ });
promotedIds.push(action.id);
}
}
@@ -147,14 +165,17 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
sketch.status = "promoted";
sketch.promotedAt = new Date().toISOString();
await kv.set(KV.sketches, sketch.id, sketch);
+ await safeAudit(kv, "sketch_promote", "mem::sketch-promote", [sketch.id], {
+ action: "promote.sketch",
+ promotedIds,
+ });
return { success: true, promotedIds };
});
},
);
- sdk.registerFunction(
- { id: "mem::sketch-discard" },
+ sdk.registerFunction("mem::sketch-discard",
async (data: { sketchId: string }) => {
if (!data.sketchId) {
return { success: false, error: "sketchId is required" };
@@ -178,24 +199,34 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
actionIdSet.has(edge.targetActionId)
) {
await kv.delete(KV.actionEdges, edge.id);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-discard", [edge.id], {
+ action: "discard.edge",
+ sketchId: sketch.id,
+ });
}
}
for (const actionId of sketch.actionIds) {
await kv.delete(KV.actions, actionId);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-discard", [actionId], {
+ action: "discard.action",
+ sketchId: sketch.id,
+ });
}
sketch.status = "discarded";
sketch.discardedAt = new Date().toISOString();
await kv.set(KV.sketches, sketch.id, sketch);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-discard", [sketch.id], {
+ action: "discard.sketch",
+ });
return { success: true, discardedCount: sketch.actionIds.length };
});
},
);
- sdk.registerFunction(
- { id: "mem::sketch-list" },
+ sdk.registerFunction("mem::sketch-list",
async (data: { status?: string; project?: string }) => {
let sketches = await kv.list<Sketch>(KV.sketches);
@@ -220,8 +251,7 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
},
);
- sdk.registerFunction(
- { id: "mem::sketch-gc" },
+ sdk.registerFunction("mem::sketch-gc",
async () => {
const sketches = await kv.list<Sketch>(KV.sketches);
const now = Date.now();
@@ -254,16 +284,27 @@ export function registerSketchesFunction(sdk: ISdk, kv: StateKV): void {
actionIdSet.has(edge.targetActionId)
) {
await kv.delete(KV.actionEdges, edge.id);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-gc", [edge.id], {
+ action: "gc.edge",
+ sketchId: current.id,
+ });
}
}
for (const actionId of current.actionIds) {
await kv.delete(KV.actions, actionId);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-gc", [actionId], {
+ action: "gc.action",
+ sketchId: current.id,
+ });
}
current.status = "discarded";
current.discardedAt = new Date().toISOString();
await kv.set(KV.sketches, current.id, current);
+ await safeAudit(kv, "sketch_discard", "mem::sketch-gc", [current.id], {
+ action: "gc.sketch",
+ });
collected++;
});
}
diff --git a/src/functions/skill-extract.ts b/src/functions/skill-extract.ts
index 60a3c505..c15d640d 100644
--- a/src/functions/skill-extract.ts
+++ b/src/functions/skill-extract.ts
@@ -105,12 +105,7 @@ export function registerSkillExtractFunctions(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- {
- id: "mem::skill-extract",
- description:
- "Extract a reusable skill document from a completed session",
- },
+ sdk.registerFunction("mem::skill-extract",
async (data: { sessionId: string }) => {
const ctx = getContext();
if (!data?.sessionId) {
@@ -246,11 +241,7 @@ export function registerSkillExtractFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::skill-list",
- description: "List extracted procedural skills",
- },
+ sdk.registerFunction("mem::skill-list",
async (data: { limit?: number }) => {
const limit = data?.limit ?? 50;
const skills = await kv.list<ProceduralMemory>(KV.procedural);
@@ -263,11 +254,7 @@ export function registerSkillExtractFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::skill-match",
- description: "Find skills relevant to a given task description",
- },
+ sdk.registerFunction("mem::skill-match",
async (data: { query: string; limit?: number }) => {
if (!data?.query?.trim()) {
return { success: false, error: "query is required" };
diff --git a/src/functions/sliding-window.ts b/src/functions/sliding-window.ts
index 772c0f66..3a0d407e 100644
--- a/src/functions/sliding-window.ts
+++ b/src/functions/sliding-window.ts
@@ -7,6 +7,7 @@ import type {
} from "../types.js";
import { KV, generateId } from "../state/schema.js";
import type { StateKV } from "../state/kv.js";
+import { recordAudit } from "./audit.js";
const SLIDING_WINDOW_SYSTEM = `You are a contextual enrichment engine. Given a primary observation and its surrounding context window (previous and next observations from the same session), produce an enriched version.
@@ -117,12 +118,7 @@ export function registerSlidingWindowFunction(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- {
- id: "mem::enrich-window",
- description:
- "Enrich observation using sliding window context for self-containment",
- },
+ sdk.registerFunction("mem::enrich-window",
async (data: {
observationId: string;
sessionId: string;
@@ -130,18 +126,29 @@ export function registerSlidingWindowFunction(
lookahead?: number;
}) => {
const ctx = getContext();
+ if (
+ !data ||
+ typeof data.sessionId !== "string" ||
+ !data.sessionId.trim() ||
+ typeof data.observationId !== "string" ||
+ !data.observationId.trim()
+ ) {
+ return { success: false, error: "sessionId and observationId are required" };
+ }
+ const sessionId = data.sessionId.trim();
+ const observationId = data.observationId.trim();
const hprev = data.lookback ?? 3;
const hnext = data.lookahead ?? 2;
const allObs = await kv.list<CompressedObservation>(
- KV.observations(data.sessionId),
+ KV.observations(sessionId),
);
allObs.sort(
(a, b) =>
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
);
- const primaryIdx = allObs.findIndex((o) => o.id === data.observationId);
+ const primaryIdx = allObs.findIndex((o) => o.id === observationId);
if (primaryIdx === -1) {
return { success: false, error: "Observation not found" };
}
@@ -175,8 +182,8 @@ export function registerSlidingWindowFunction(
const enriched: EnrichedChunk = {
id: generateId("ec"),
- originalObsId: data.observationId,
- sessionId: data.sessionId,
+ originalObsId: observationId,
+ sessionId,
content: parsed.content,
resolvedEntities: parsed.resolvedEntities,
preferences: parsed.preferences,
@@ -187,13 +194,18 @@ export function registerSlidingWindowFunction(
};
await kv.set(
- KV.enrichedChunks(data.sessionId),
- data.observationId,
+ KV.enrichedChunks(sessionId),
+ observationId,
enriched,
);
+ await recordAudit(kv, "observe", "mem::enrich-window", [enriched.id], {
+ action: "persist_enriched_chunk",
+ sessionId,
+ observationId,
+ });
ctx.logger.info("Observation enriched via sliding window", {
- obsId: data.observationId,
+ obsId: observationId,
entitiesResolved: Object.keys(parsed.resolvedEntities).length,
preferencesFound: parsed.preferences.length,
bridges: parsed.contextBridges.length,
@@ -208,11 +220,7 @@ export function registerSlidingWindowFunction(
},
);
- sdk.registerFunction(
- {
- id: "mem::enrich-session",
- description: "Enrich all observations in a session using sliding windows",
- },
+ sdk.registerFunction("mem::enrich-session",
async (data: {
sessionId: string;
lookback?: number;
@@ -220,8 +228,12 @@ export function registerSlidingWindowFunction(
minImportance?: number;
}) => {
const ctx = getContext();
+ if (!data || typeof data.sessionId !== "string" || !data.sessionId.trim()) {
+ return { success: false, error: "sessionId is required" };
+ }
+ const sessionId = data.sessionId.trim();
const allObs = await kv.list<CompressedObservation>(
- KV.observations(data.sessionId),
+ KV.observations(sessionId),
);
const minImp = data.minImportance ?? 4;
const toEnrich = allObs.filter((o) => o.importance >= minImp);
@@ -231,12 +243,12 @@ export function registerSlidingWindowFunction(
for (const obs of toEnrich) {
try {
- const result = (await sdk.trigger("mem::enrich-window", {
+ const result = (await sdk.trigger({ function_id: "mem::enrich-window", payload: {
observationId: obs.id,
- sessionId: data.sessionId,
+ sessionId,
lookback: data.lookback ?? 3,
lookahead: data.lookahead ?? 2,
- })) as { success?: boolean } | undefined;
+ } })) as { success?: boolean } | undefined;
if (result?.success) enriched++;
else failed++;
} catch {
@@ -245,7 +257,7 @@ export function registerSlidingWindowFunction(
}
ctx.logger.info("Session enrichment complete", {
- sessionId: data.sessionId,
+ sessionId,
total: toEnrich.length,
enriched,
failed,
diff --git a/src/functions/smart-search.ts b/src/functions/smart-search.ts
index fb614db2..3e821bb8 100644
--- a/src/functions/smart-search.ts
+++ b/src/functions/smart-search.ts
@@ -14,12 +14,7 @@ export function registerSmartSearchFunction(
kv: StateKV,
searchFn: (query: string, limit: number) => Promise<HybridSearchResult[]>,
): void {
- sdk.registerFunction(
- {
- id: "mem::smart-search",
- description:
- "Search with progressive disclosure: compact results first, expand specific IDs for full details",
- },
+ sdk.registerFunction("mem::smart-search",
async (data: {
query?: string;
expandIds?: Array<string | { obsId: string; sessionId: string }>;
diff --git a/src/functions/snapshot.ts b/src/functions/snapshot.ts
index cfd84f8f..11731728 100644
--- a/src/functions/snapshot.ts
+++ b/src/functions/snapshot.ts
@@ -41,13 +41,13 @@ export function registerSnapshotFunction(
kv: StateKV,
snapshotDir: string,
): void {
- sdk.registerFunction(
- { id: "mem::snapshot-create" },
+ sdk.registerFunction("mem::snapshot-create",
async (data?: { message?: string }) => {
const ctx = getContext();
try {
await ensureGitRepo(snapshotDir);
+ const ts = new Date().toISOString();
const sessions = await kv.list<Session>(KV.sessions);
const memories = await kv.list<Memory>(KV.memories);
@@ -68,7 +68,7 @@ export function registerSnapshotFunction(
const state = {
version: VERSION,
- timestamp: new Date().toISOString(),
+ timestamp: ts,
sessions,
memories,
graphNodes,
@@ -84,7 +84,7 @@ export function registerSnapshotFunction(
await gitExec(snapshotDir, ["add", "."]);
- const message = data?.message || `Snapshot ${new Date().toISOString()}`;
+ const message = data?.message || `Snapshot ${ts}`;
try {
await gitExec(snapshotDir, ["commit", "-m", message]);
} catch (commitErr) {
@@ -101,7 +101,7 @@ export function registerSnapshotFunction(
const meta: SnapshotMeta = {
id: generateId("snap"),
commitHash,
- createdAt: new Date().toISOString(),
+ createdAt: ts,
message,
stats: {
sessions: sessions.length,
@@ -129,7 +129,7 @@ export function registerSnapshotFunction(
},
);
- sdk.registerFunction({ id: "mem::snapshot-list" }, async () => {
+ sdk.registerFunction("mem::snapshot-list", async () => {
try {
if (!existsSync(join(snapshotDir, ".git"))) {
return { snapshots: [] };
@@ -154,11 +154,10 @@ export function registerSnapshotFunction(
}
});
- sdk.registerFunction(
- { id: "mem::snapshot-restore" },
- async (data: { commitHash: string }) => {
+ sdk.registerFunction("mem::snapshot-restore",
+ async (data: { commitHash: string } | undefined) => {
const ctx = getContext();
- if (!data.commitHash) {
+ if (!data || typeof data.commitHash !== "string" || !data.commitHash.trim()) {
return { success: false, error: "commitHash is required" };
}
if (!COMMIT_HASH_RE.test(data.commitHash)) {
diff --git a/src/functions/summarize.ts b/src/functions/summarize.ts
index a06068b7..784ca651 100644
--- a/src/functions/summarize.ts
+++ b/src/functions/summarize.ts
@@ -14,6 +14,7 @@ import { SummaryOutputSchema } from "../eval/schemas.js";
import { validateOutput } from "../eval/validator.js";
import { scoreSummary } from "../eval/quality.js";
import type { MetricsStore } from "../eval/metrics-store.js";
+import { safeAudit } from "./audit.js";
function parseSummaryXml(
xml: string,
@@ -43,28 +44,31 @@ export function registerSummarizeFunction(
provider: MemoryProvider,
metricsStore?: MetricsStore,
): void {
- sdk.registerFunction(
- { id: "mem::summarize", description: "Generate end-of-session summary" },
- async (data: { sessionId: string }) => {
+ sdk.registerFunction("mem::summarize",
+ async (data: { sessionId: string } | undefined) => {
const ctx = getContext();
const startMs = Date.now();
+ if (!data || typeof data.sessionId !== "string" || !data.sessionId.trim()) {
+ return { success: false, error: "sessionId is required" };
+ }
+ const sessionId = data.sessionId.trim();
- const session = await kv.get<Session>(KV.sessions, data.sessionId);
+ const session = await kv.get<Session>(KV.sessions, sessionId);
if (!session) {
ctx.logger.warn("Session not found for summarize", {
- sessionId: data.sessionId,
+ sessionId,
});
return { success: false, error: "session_not_found" };
}
const observations = await kv.list<CompressedObservation>(
- KV.observations(data.sessionId),
+ KV.observations(sessionId),
);
const compressed = observations.filter((o) => o.title);
if (compressed.length === 0) {
ctx.logger.info("No observations to summarize", {
- sessionId: data.sessionId,
+ sessionId,
});
return { success: false, error: "no_observations" };
}
@@ -74,7 +78,7 @@ export function registerSummarizeFunction(
const response = await provider.summarize(SUMMARY_SYSTEM, prompt);
const summary = parseSummaryXml(
response,
- data.sessionId,
+ sessionId,
session.project,
compressed.length,
);
@@ -85,7 +89,7 @@ export function registerSummarizeFunction(
await metricsStore.record("mem::summarize", latencyMs, false);
}
ctx.logger.warn("Failed to parse summary XML", {
- sessionId: data.sessionId,
+ sessionId,
});
return { success: false, error: "parse_failed" };
}
@@ -109,7 +113,7 @@ export function registerSummarizeFunction(
await metricsStore.record("mem::summarize", latencyMs, false);
}
ctx.logger.warn("Summary validation failed", {
- sessionId: data.sessionId,
+ sessionId,
errors: validation.result.errors,
});
return { success: false, error: "validation_failed" };
@@ -117,7 +121,11 @@ export function registerSummarizeFunction(
const qualityScore = scoreSummary(summaryForValidation);
- await kv.set(KV.summaries, data.sessionId, summary);
+ await kv.set(KV.summaries, sessionId, summary);
+ await safeAudit(kv, "compress", "mem::summarize", [sessionId], {
+ title: summary.title,
+ observationCount: compressed.length,
+ });
const latencyMs = Date.now() - startMs;
if (metricsStore) {
@@ -130,7 +138,7 @@ export function registerSummarizeFunction(
}
ctx.logger.info("Session summarized", {
- sessionId: data.sessionId,
+ sessionId,
title: summary.title,
decisions: summary.keyDecisions.length,
qualityScore,
@@ -145,7 +153,7 @@ export function registerSummarizeFunction(
await metricsStore.record("mem::summarize", latencyMs, false);
}
ctx.logger.error("Summarize failed", {
- sessionId: data.sessionId,
+ sessionId,
error: msg,
});
return { success: false, error: msg };
diff --git a/src/functions/team.ts b/src/functions/team.ts
index 4d976d6e..d4ffd237 100644
--- a/src/functions/team.ts
+++ b/src/functions/team.ts
@@ -17,8 +17,7 @@ export function registerTeamFunction(
kv: StateKV,
config: TeamConfig,
): void {
- sdk.registerFunction(
- { id: "mem::team-share" },
+ sdk.registerFunction("mem::team-share",
async (data: {
itemId: string;
itemType: "memory" | "pattern" | "observation";
@@ -26,6 +25,9 @@ export function registerTeamFunction(
project?: string;
}) => {
const ctx = getContext();
+ if (!data) {
+ return { success: false, error: "payload required" };
+ }
if (!data.itemId || !data.itemType) {
return { success: false, error: "itemId and itemType are required" };
}
@@ -75,10 +77,9 @@ export function registerTeamFunction(
},
);
- sdk.registerFunction(
- { id: "mem::team-feed" },
+ sdk.registerFunction("mem::team-feed",
async (data?: { limit?: number }) => {
- const limit = data?.limit || 20;
+ const limit = data?.limit ?? 20;
const items = await kv.list<TeamSharedItem>(KV.teamShared(config.teamId));
const filtered = items.filter((i) => i.visibility === "shared");
@@ -93,7 +94,7 @@ export function registerTeamFunction(
},
);
- sdk.registerFunction({ id: "mem::team-profile" }, async () => {
+ sdk.registerFunction("mem::team-profile", async () => {
const items = await kv.list<TeamSharedItem>(KV.teamShared(config.teamId));
const members = [...new Set(items.map((i) => i.sharedBy))];
@@ -142,6 +143,19 @@ export function registerTeamFunction(
};
await kv.set(KV.teamProfile(config.teamId), "profile", profile);
+ await recordAudit(
+ kv,
+ "share",
+ "mem::team-profile",
+ ["profile"],
+ {
+ teamId: config.teamId,
+ members: members.length,
+ totalSharedItems: items.length,
+ },
+ undefined,
+ config.userId,
+ );
return profile;
});
}
diff --git a/src/functions/temporal-graph.ts b/src/functions/temporal-graph.ts
index 71dcbe03..ff298afb 100644
--- a/src/functions/temporal-graph.ts
+++ b/src/functions/temporal-graph.ts
@@ -154,12 +154,7 @@ export function registerTemporalGraphFunctions(
kv: StateKV,
provider: MemoryProvider,
): void {
- sdk.registerFunction(
- {
- id: "mem::temporal-graph-extract",
- description:
- "Extract temporal knowledge graph with context metadata from observations",
- },
+ sdk.registerFunction("mem::temporal-graph-extract",
async (data: {
observations: Array<{
id: string;
@@ -280,12 +275,7 @@ export function registerTemporalGraphFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::temporal-query",
- description:
- "Query entity state at a specific point in time with full history",
- },
+ sdk.registerFunction("mem::temporal-query",
async (data: {
entityName: string;
asOf?: string;
@@ -363,12 +353,7 @@ export function registerTemporalGraphFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::differential-state",
- description:
- "Compute state changes between two entities over time",
- },
+ sdk.registerFunction("mem::differential-state",
async (data: {
entityName: string;
from?: string;
diff --git a/src/functions/timeline.ts b/src/functions/timeline.ts
index 0071155e..af707abd 100644
--- a/src/functions/timeline.ts
+++ b/src/functions/timeline.ts
@@ -10,11 +10,7 @@ import { StateKV } from "../state/kv.js";
import { recordAccessBatch } from "./access-tracker.js";
export function registerTimelineFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- {
- id: "mem::timeline",
- description: "Get chronological observations around an anchor point",
- },
+ sdk.registerFunction("mem::timeline",
async (data: {
anchor: string;
project?: string;
diff --git a/src/functions/verify.ts b/src/functions/verify.ts
index 74753b15..a6e393f6 100644
--- a/src/functions/verify.ts
+++ b/src/functions/verify.ts
@@ -8,8 +8,7 @@ import type {
} from "../types.js";
export function registerVerifyFunction(sdk: ISdk, kv: StateKV): void {
- sdk.registerFunction(
- { id: "mem::verify" },
+ sdk.registerFunction("mem::verify",
async (data: { id: string }) => {
if (!data.id || typeof data.id !== "string") {
return { success: false, error: "id is required" };
diff --git a/src/functions/working-memory.ts b/src/functions/working-memory.ts
index aa5fa170..19668e0b 100644
--- a/src/functions/working-memory.ts
+++ b/src/functions/working-memory.ts
@@ -36,11 +36,7 @@ export function registerWorkingMemoryFunctions(
kv: StateKV,
tokenBudget: number,
): void {
- sdk.registerFunction(
- {
- id: "mem::core-add",
- description: "Add a fact to core memory (always included in context)",
- },
+ sdk.registerFunction("mem::core-add",
async (data: {
content: string;
importance?: number;
@@ -73,11 +69,7 @@ export function registerWorkingMemoryFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::core-remove",
- description: "Remove a fact from core memory",
- },
+ sdk.registerFunction("mem::core-remove",
async (data: { id: string }) => {
if (!data?.id) return { success: false, error: "id is required" };
await kv.delete(CORE_SCOPE, data.id);
@@ -90,11 +82,7 @@ export function registerWorkingMemoryFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::core-list",
- description: "List all core memory entries",
- },
+ sdk.registerFunction("mem::core-list",
async () => {
const entries = await kv.list<CoreMemoryEntry>(CORE_SCOPE);
entries.sort((a, b) => b.importance - a.importance);
@@ -109,12 +97,7 @@ export function registerWorkingMemoryFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::working-context",
- description:
- "Build working context: core memory (pinned) + paged archival (by relevance/recency)",
- },
+ sdk.registerFunction("mem::working-context",
async (data: { budget?: number }) => {
const ctx = getContext();
const budget = data.budget || tokenBudget;
@@ -209,12 +192,7 @@ export function registerWorkingMemoryFunctions(
},
);
- sdk.registerFunction(
- {
- id: "mem::auto-page",
- description:
- "Automatically page low-value core memory entries to archival when over budget",
- },
+ sdk.registerFunction("mem::auto-page",
async (data: { budget?: number }) => {
const budget = data?.budget || tokenBudget;
const coreBudget = Math.floor(budget * 0.3);
diff --git a/src/health/monitor.ts b/src/health/monitor.ts
index be4b6c0b..641bb869 100644
--- a/src/health/monitor.ts
+++ b/src/health/monitor.ts
@@ -41,7 +41,7 @@ export function registerHealthMonitor(
const result = await sdk.trigger<
unknown,
{ workers?: HealthSnapshot["workers"] }
- >("engine::workers::list", {});
+ >({ function_id: "engine::workers::list", payload: {} });
if (result?.workers) workers = result.workers;
} catch {}
diff --git a/src/index.ts b/src/index.ts
index 03e645d6..18b4a59c 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,4 @@
-import { init } from "iii-sdk";
+import { registerWorker } from "iii-sdk";
import {
loadConfig,
getEnvVar,
@@ -85,6 +85,17 @@ import { registerHealthMonitor } from "./health/monitor.js";
import { initMetrics, OTEL_CONFIG } from "./telemetry/setup.js";
import { VERSION } from "./version.js";
+function hasGetMeter(
+ sdk: unknown,
+): sdk is { getMeter: (name: string) => unknown } {
+ return (
+ typeof sdk === "object" &&
+ sdk !== null &&
+ "getMeter" in sdk &&
+ typeof (sdk as { getMeter?: unknown }).getMeter === "function"
+ );
+}
+
async function main() {
const config = loadConfig();
const embeddingConfig = loadEmbeddingConfig();
@@ -114,7 +125,7 @@ async function main() {
);
console.log(`[agentmemory] Streams: ws://localhost:${config.streamsPort}`);
- const sdk = init(config.engineUrl, {
+ const sdk = registerWorker(config.engineUrl, {
workerName: "agentmemory",
otel: {
serviceName: OTEL_CONFIG.serviceName,
@@ -130,11 +141,11 @@ async function main() {
const vectorIndex = embeddingProvider ? new VectorIndex() : null;
- initMetrics(
- typeof (sdk as any).getMeter === "function"
- ? (sdk as any).getMeter.bind(sdk)
- : undefined,
- );
+ const meterAccessor = hasGetMeter(sdk)
+ ? (sdk.getMeter.bind(sdk) as (name: string) => unknown)
+ : undefined;
+
+ initMetrics(meterAccessor as ((name: string) => import("@opentelemetry/api").Meter) | undefined);
registerPrivacyFunction(sdk);
registerObserveFunction(sdk, kv, dedupMap, config.maxObservationsPerSession);
@@ -321,7 +332,7 @@ async function main() {
if (process.env.AUTO_FORGET_ENABLED !== "false") {
const autoForgetTimer = setInterval(async () => {
try {
- await sdk.trigger("mem::auto-forget", { dryRun: false });
+ await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun: false } });
} catch {}
}, autoForgetIntervalMs);
autoForgetTimer.unref();
@@ -331,7 +342,7 @@ async function main() {
if (process.env.LESSON_DECAY_ENABLED !== "false") {
const lessonDecayTimer = setInterval(async () => {
try {
- await sdk.trigger("mem::lesson-decay-sweep", {});
+ await sdk.trigger({ function_id: "mem::lesson-decay-sweep", payload: {} });
} catch {}
}, 86400000);
lessonDecayTimer.unref();
@@ -341,7 +352,7 @@ async function main() {
if (process.env.INSIGHT_DECAY_ENABLED !== "false") {
const insightDecayTimer = setInterval(async () => {
try {
- await sdk.trigger("mem::insight-decay-sweep", {});
+ await sdk.trigger({ function_id: "mem::insight-decay-sweep", payload: {} });
} catch {}
}, 86400000);
insightDecayTimer.unref();
@@ -350,7 +361,7 @@ async function main() {
if (isConsolidationEnabled()) {
const consolidationTimer = setInterval(async () => {
try {
- await sdk.trigger("mem::consolidate-pipeline", {});
+ await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: {} });
} catch {}
}, consolidationIntervalMs);
consolidationTimer.unref();
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index d565b698..b3086c7c 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -17,6 +17,28 @@ type McpResponse = {
body: unknown;
};
+function asNonEmptyString(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+function asNumber(value: unknown, fallback?: number): number | undefined {
+ const n = Number(value);
+ if (Number.isFinite(n)) return n;
+ return fallback;
+}
+
+function parseCsvList(value: unknown): string[] {
+ if (typeof value === "string") {
+ return value.split(",").map((v) => v.trim()).filter(Boolean);
+ }
+ if (Array.isArray(value)) {
+ return value
+ .map((v) => (typeof v === "string" ? v.trim() : ""))
+ .filter(Boolean);
+ }
+ return [];
+}
+
export function registerMcpEndpoints(
sdk: ISdk,
kv: StateKV,
@@ -35,8 +57,7 @@ export function registerMcpEndpoints(
return null;
}
- sdk.registerFunction(
- { id: "mcp::tools::list" },
+ sdk.registerFunction("mcp::tools::list",
async (req: ApiRequest): Promise<McpResponse> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -49,8 +70,7 @@ export function registerMcpEndpoints(
config: { api_path: "/agentmemory/mcp/tools", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "mcp::tools::call" },
+ sdk.registerFunction("mcp::tools::call",
async (
req: ApiRequest<{ name: string; arguments: Record<string, unknown> }>,
): Promise<McpResponse> => {
@@ -72,10 +92,10 @@ export function registerMcpEndpoints(
body: { error: "query is required for memory_recall" },
};
}
- const result = await sdk.trigger("mem::search", {
+ const result = await sdk.trigger({ function_id: "mem::search", payload: {
query: args.query,
- limit: (args.limit as number) || 10,
- });
+ limit: typeof args.limit === "number" ? args.limit : 10,
+ } });
return {
status_code: 200,
body: {
@@ -103,12 +123,12 @@ export function registerMcpEndpoints(
? args.files.split(",").map((f: string) => f.trim()).filter(Boolean)
: [];
- const result = await sdk.trigger("mem::remember", {
+ const result = await sdk.trigger({ function_id: "mem::remember", payload: {
content: args.content,
type,
concepts,
files,
- });
+ } });
return {
status_code: 200,
body: {
@@ -124,12 +144,19 @@ export function registerMcpEndpoints(
body: { error: "files is required for memory_file_history" },
};
}
- const fileList = (args.files as string)
- .split(",")
- .map((f: string) => f.trim());
- const result = await sdk.trigger("mem::file-context", {
- sessionId: (args.sessionId as string) || "",
- files: fileList,
+ const fileList = parseCsvList(args.files);
+ if (!fileList.length) {
+ return {
+ status_code: 400,
+ body: { error: "files must contain at least one valid path" },
+ };
+ }
+ const payload: { sessionId?: string; files: string[] } = { files: fileList };
+ const sessionId = asNonEmptyString(args.sessionId);
+ if (sessionId) payload.sessionId = sessionId;
+ const result = await sdk.trigger({
+ function_id: "mem::file-context",
+ payload,
});
return {
status_code: 200,
@@ -147,9 +174,9 @@ export function registerMcpEndpoints(
}
case "memory_patterns": {
- const result = await sdk.trigger("mem::patterns", {
+ const result = await sdk.trigger({ function_id: "mem::patterns", payload: {
project: args.project as string,
- });
+ } });
return {
status_code: 200,
body: {
@@ -179,14 +206,15 @@ export function registerMcpEndpoints(
body: { error: "query is required for memory_smart_search" },
};
}
- const expandIds =
- typeof args.expandIds === "string"
- ? args.expandIds.split(",").map((id: string) => id.trim()).slice(0, 20)
- : [];
- const result = await sdk.trigger("mem::smart-search", {
- query: args.query,
- expandIds,
- limit: (args.limit as number) || 10,
+ const expandIds = parseCsvList(args.expandIds).slice(0, 20);
+ const limit = Math.max(1, Math.min(100, asNumber(args.limit, 10) ?? 10));
+ const result = await sdk.trigger({
+ function_id: "mem::smart-search",
+ payload: {
+ query: args.query,
+ expandIds,
+ limit,
+ },
});
return {
status_code: 200,
@@ -205,12 +233,12 @@ export function registerMcpEndpoints(
body: { error: "anchor is required for memory_timeline" },
};
}
- const result = await sdk.trigger("mem::timeline", {
+ const result = await sdk.trigger({ function_id: "mem::timeline", payload: {
anchor: args.anchor,
project: (args.project as string) || undefined,
before: (args.before as number) || 5,
after: (args.after as number) || 5,
- });
+ } });
return {
status_code: 200,
body: {
@@ -228,10 +256,10 @@ export function registerMcpEndpoints(
body: { error: "project is required for memory_profile" },
};
}
- const result = await sdk.trigger("mem::profile", {
+ const result = await sdk.trigger({ function_id: "mem::profile", payload: {
project: args.project,
- refresh: args.refresh === "true",
- });
+ refresh: args.refresh === true || args.refresh === "true",
+ } });
return {
status_code: 200,
body: {
@@ -243,7 +271,7 @@ export function registerMcpEndpoints(
}
case "memory_export": {
- const result = await sdk.trigger("mem::export", {});
+ const result = await sdk.trigger({ function_id: "mem::export", payload: {} });
return {
status_code: 200,
body: {
@@ -263,13 +291,13 @@ export function registerMcpEndpoints(
}
const rawMaxHops = Number(args.maxHops);
const rawMinConf = Number(args.minConfidence);
- const result = await sdk.trigger("mem::get-related", {
+ const result = await sdk.trigger({ function_id: "mem::get-related", payload: {
memoryId: args.memoryId,
maxHops: Number.isFinite(rawMaxHops) ? rawMaxHops : 2,
minConfidence: Number.isFinite(rawMinConf)
? Math.max(0, Math.min(1, rawMinConf))
: 0,
- });
+ } });
return {
status_code: 200,
body: {
@@ -287,7 +315,10 @@ export function registerMcpEndpoints(
? "mem::claude-bridge-read"
: "mem::claude-bridge-sync";
try {
- const result = await sdk.trigger(funcId, {});
+ const result = await sdk.trigger({
+ function_id: funcId,
+ payload: {},
+ });
return {
status_code: 200,
body: {
@@ -313,11 +344,23 @@ export function registerMcpEndpoints(
case "memory_graph_query": {
try {
- const result = await sdk.trigger("mem::graph-query", {
- startNodeId: args.startNodeId as string,
- nodeType: args.nodeType as string,
- maxDepth: args.maxDepth as number,
- query: args.query as string,
+ const payload: {
+ startNodeId?: string;
+ nodeType?: string;
+ maxDepth?: number;
+ query?: string;
+ } = {};
+ const startNodeId = asNonEmptyString(args.startNodeId);
+ const nodeType = asNonEmptyString(args.nodeType);
+ const query = asNonEmptyString(args.query);
+ const maxDepth = asNumber(args.maxDepth);
+ if (startNodeId) payload.startNodeId = startNodeId;
+ if (nodeType) payload.nodeType = nodeType;
+ if (query) payload.query = query;
+ if (maxDepth !== undefined) payload.maxDepth = Math.max(1, Math.min(8, maxDepth));
+ const result = await sdk.trigger({
+ function_id: "mem::graph-query",
+ payload,
});
return {
status_code: 200,
@@ -344,9 +387,9 @@ export function registerMcpEndpoints(
case "memory_consolidate": {
try {
- const result = await sdk.trigger("mem::consolidate-pipeline", {
+ const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: {
tier: args.tier as string,
- });
+ } });
return {
status_code: 200,
body: {
@@ -381,10 +424,10 @@ export function registerMcpEndpoints(
};
}
try {
- const result = await sdk.trigger("mem::team-share", {
+ const result = await sdk.trigger({ function_id: "mem::team-share", payload: {
itemId: args.itemId,
itemType: args.itemType,
- });
+ } });
return {
status_code: 200,
body: {
@@ -410,9 +453,9 @@ export function registerMcpEndpoints(
case "memory_team_feed": {
try {
- const result = await sdk.trigger("mem::team-feed", {
- limit: (args.limit as number) || 20,
- });
+ const result = await sdk.trigger({ function_id: "mem::team-feed", payload: {
+ limit: typeof args.limit === "number" ? args.limit : 20,
+ } });
return {
status_code: 200,
body: {
@@ -438,10 +481,10 @@ export function registerMcpEndpoints(
case "memory_audit": {
try {
- const result = await sdk.trigger("mem::audit-query", {
+ const result = await sdk.trigger({ function_id: "mem::audit-query", payload: {
operation: args.operation as string,
- limit: (args.limit as number) || 50,
- });
+ limit: typeof args.limit === "number" ? args.limit : 50,
+ } });
return {
status_code: 200,
body: {
@@ -473,10 +516,10 @@ export function registerMcpEndpoints(
.map((id) => id.trim())
.filter(Boolean);
try {
- const result = await sdk.trigger("mem::governance-delete", {
+ const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: {
memoryIds: ids,
reason: args.reason as string,
- });
+ } });
return {
status_code: 200,
body: {
@@ -498,9 +541,9 @@ export function registerMcpEndpoints(
case "memory_snapshot_create": {
try {
- const result = await sdk.trigger("mem::snapshot-create", {
+ const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: {
message: args.message as string,
- });
+ } });
return {
status_code: 200,
body: {
@@ -540,7 +583,7 @@ export function registerMcpEndpoints(
const tags = typeof args.tags === "string" && args.tags.trim()
? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean)
: [];
- const actionResult = await sdk.trigger("mem::action-create", {
+ const actionResult = await sdk.trigger({ function_id: "mem::action-create", payload: {
title: args.title,
description: args.description,
priority: args.priority,
@@ -548,7 +591,7 @@ export function registerMcpEndpoints(
tags,
parentId: args.parentId,
edges: edges.length > 0 ? edges : undefined,
- });
+ } });
return {
status_code: 200,
body: {
@@ -566,12 +609,12 @@ export function registerMcpEndpoints(
body: { error: "actionId is required" },
};
}
- const updateResult = await sdk.trigger("mem::action-update", {
+ const updateResult = await sdk.trigger({ function_id: "mem::action-update", payload: {
actionId: args.actionId,
status: args.status,
result: args.result,
priority: args.priority,
- });
+ } });
return {
status_code: 200,
body: {
@@ -583,11 +626,11 @@ export function registerMcpEndpoints(
}
case "memory_frontier": {
- const frontierResult = await sdk.trigger("mem::frontier", {
+ const frontierResult = await sdk.trigger({ function_id: "mem::frontier", payload: {
project: args.project,
agentId: args.agentId,
limit: args.limit,
- });
+ } });
return {
status_code: 200,
body: {
@@ -599,10 +642,10 @@ export function registerMcpEndpoints(
}
case "memory_next": {
- const nextResult = await sdk.trigger("mem::next", {
+ const nextResult = await sdk.trigger({ function_id: "mem::next", payload: {
project: args.project,
agentId: args.agentId,
- });
+ } });
return {
status_code: 200,
body: {
@@ -627,23 +670,23 @@ export function registerMcpEndpoints(
const op = args.operation as string;
let leaseResult;
if (op === "acquire") {
- leaseResult = await sdk.trigger("mem::lease-acquire", {
+ leaseResult = await sdk.trigger({ function_id: "mem::lease-acquire", payload: {
actionId: args.actionId,
agentId: args.agentId,
ttlMs: args.ttlMs,
- });
+ } });
} else if (op === "release") {
- leaseResult = await sdk.trigger("mem::lease-release", {
+ leaseResult = await sdk.trigger({ function_id: "mem::lease-release", payload: {
actionId: args.actionId,
agentId: args.agentId,
result: args.result,
- });
+ } });
} else if (op === "renew") {
- leaseResult = await sdk.trigger("mem::lease-renew", {
+ leaseResult = await sdk.trigger({ function_id: "mem::lease-renew", payload: {
actionId: args.actionId,
agentId: args.agentId,
ttlMs: args.ttlMs,
- });
+ } });
} else {
return {
status_code: 400,
@@ -667,11 +710,11 @@ export function registerMcpEndpoints(
body: { error: "routineId is required" },
};
}
- const runResult = await sdk.trigger("mem::routine-run", {
+ const runResult = await sdk.trigger({ function_id: "mem::routine-run", payload: {
routineId: args.routineId,
project: args.project,
initiatedBy: args.initiatedBy,
- });
+ } });
return {
status_code: 200,
body: {
@@ -692,13 +735,13 @@ export function registerMcpEndpoints(
body: { error: "from and content are required" },
};
}
- const sigResult = await sdk.trigger("mem::signal-send", {
+ const sigResult = await sdk.trigger({ function_id: "mem::signal-send", payload: {
from: args.from,
to: args.to,
content: args.content,
type: args.type,
replyTo: args.replyTo,
- });
+ } });
return {
status_code: 200,
body: {
@@ -716,12 +759,12 @@ export function registerMcpEndpoints(
body: { error: "agentId is required" },
};
}
- const readResult = await sdk.trigger("mem::signal-read", {
+ const readResult = await sdk.trigger({ function_id: "mem::signal-read", payload: {
agentId: args.agentId,
unreadOnly: args.unreadOnly === true || args.unreadOnly === "true",
threadId: args.threadId,
limit: args.limit,
- });
+ } });
return {
status_code: 200,
body: {
@@ -745,12 +788,12 @@ export function registerMcpEndpoints(
const linkedIds = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim()
? args.linkedActionIds.split(",").map((s: string) => s.trim())
: [];
- cpResult = await sdk.trigger("mem::checkpoint-create", {
+ cpResult = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: {
name: args.name,
description: args.description,
type: args.type,
linkedActionIds: linkedIds,
- });
+ } });
} else if (cpOp === "resolve") {
if (typeof args.checkpointId !== "string" || !args.checkpointId.trim()) {
return {
@@ -758,15 +801,15 @@ export function registerMcpEndpoints(
body: { error: "checkpointId is required for resolve operation" },
};
}
- cpResult = await sdk.trigger("mem::checkpoint-resolve", {
+ cpResult = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: {
checkpointId: args.checkpointId,
status: args.status,
- });
+ } });
} else if (cpOp === "list") {
- cpResult = await sdk.trigger("mem::checkpoint-list", {
+ cpResult = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: {
status: args.status,
type: args.type,
- });
+ } });
} else {
return {
status_code: 400,
@@ -784,10 +827,10 @@ export function registerMcpEndpoints(
}
case "memory_mesh_sync": {
- const meshResult = await sdk.trigger("mem::mesh-sync", {
+ const meshResult = await sdk.trigger({ function_id: "mem::mesh-sync", payload: {
peerId: args.peerId,
direction: args.direction,
- });
+ } });
return {
status_code: 200,
body: {
@@ -805,15 +848,24 @@ export function registerMcpEndpoints(
} else if (typeof args.config === "string" && args.config.trim()) {
try { snlConfig = JSON.parse(args.config); } catch { return { status_code: 400, body: { error: "invalid config JSON" } }; }
}
- const snlLinked = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim()
- ? args.linkedActionIds.split(",").map((s: string) => s.trim()).filter(Boolean)
- : undefined;
- const snlResult = await sdk.trigger("mem::sentinel-create", {
- name: args.name,
- type: args.type,
- config: snlConfig,
- linkedActionIds: snlLinked,
- expiresInMs: args.expiresInMs,
+ const snlLinked = parseCsvList(args.linkedActionIds);
+ const expiresInMs = asNumber(args.expiresInMs);
+ const name = asNonEmptyString(args.name);
+ const type = asNonEmptyString(args.type);
+ const payload: {
+ name?: string;
+ type?: string;
+ config: Record<string, unknown>;
+ linkedActionIds?: string[];
+ expiresInMs?: number;
+ } = { config: snlConfig };
+ if (name) payload.name = name;
+ if (type) payload.type = type;
+ if (snlLinked.length) payload.linkedActionIds = snlLinked;
+ if (expiresInMs !== undefined) payload.expiresInMs = Math.max(0, expiresInMs);
+ const snlResult = await sdk.trigger({
+ function_id: "mem::sentinel-create",
+ payload,
});
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlResult, null, 2) }] } };
}
@@ -827,28 +879,53 @@ export function registerMcpEndpoints(
snlTrigPayload = args.result;
}
}
- const snlTrigResult = await sdk.trigger("mem::sentinel-trigger", {
- sentinelId: args.sentinelId,
+ const sentinelId = asNonEmptyString(args.sentinelId);
+ if (!sentinelId) {
+ return {
+ status_code: 400,
+ body: { error: "sentinelId is required for memory_sentinel_trigger" },
+ };
+ }
+ const snlTrigResult = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: {
+ sentinelId,
result: snlTrigPayload,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlTrigResult, null, 2) }] } };
}
case "memory_sketch_create": {
- const skResult = await sdk.trigger("mem::sketch-create", {
- title: args.title,
- description: args.description,
- expiresInMs: args.expiresInMs,
- project: args.project,
+ const title = asNonEmptyString(args.title);
+ if (!title) {
+ return {
+ status_code: 400,
+ body: { error: "title is required for memory_sketch_create" },
+ };
+ }
+ const sketchPayload = {
+ title,
+ description: asNonEmptyString(args.description),
+ expiresInMs: asNumber(args.expiresInMs),
+ project: asNonEmptyString(args.project),
+ };
+ const skResult = await sdk.trigger({
+ function_id: "mem::sketch-create",
+ payload: sketchPayload,
});
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skResult, null, 2) }] } };
}
case "memory_sketch_promote": {
- const skpResult = await sdk.trigger("mem::sketch-promote", {
- sketchId: args.sketchId,
+ const sketchId = asNonEmptyString(args.sketchId);
+ if (!sketchId) {
+ return {
+ status_code: 400,
+ body: { error: "sketchId is required for memory_sketch_promote" },
+ };
+ }
+ const skpResult = await sdk.trigger({ function_id: "mem::sketch-promote", payload: {
+ sketchId,
project: args.project,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skpResult, null, 2) }] } };
}
@@ -857,11 +934,11 @@ export function registerMcpEndpoints(
return { status_code: 400, body: { error: "actionIds is required" } };
}
const crysIds = args.actionIds.split(",").map((s: string) => s.trim()).filter(Boolean);
- const crysResult = await sdk.trigger("mem::crystallize", {
+ const crysResult = await sdk.trigger({ function_id: "mem::crystallize", payload: {
actionIds: crysIds,
project: args.project,
sessionId: args.sessionId,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(crysResult, null, 2) }] } };
}
@@ -869,7 +946,7 @@ export function registerMcpEndpoints(
const diagCats = typeof args.categories === "string" && args.categories.trim()
? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean)
: undefined;
- const diagResult = await sdk.trigger("mem::diagnose", { categories: diagCats });
+ const diagResult = await sdk.trigger({ function_id: "mem::diagnose", payload: { categories: diagCats } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(diagResult, null, 2) }] } };
}
@@ -877,20 +954,20 @@ export function registerMcpEndpoints(
const healCats = typeof args.categories === "string" && args.categories.trim()
? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean)
: undefined;
- const healResult = await sdk.trigger("mem::heal", {
+ const healResult = await sdk.trigger({ function_id: "mem::heal", payload: {
categories: healCats,
dryRun: args.dryRun === true || args.dryRun === "true",
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(healResult, null, 2) }] } };
}
case "memory_facet_tag": {
- const fctResult = await sdk.trigger("mem::facet-tag", {
+ const fctResult = await sdk.trigger({ function_id: "mem::facet-tag", payload: {
targetId: args.targetId,
targetType: args.targetType,
dimension: args.dimension,
value: args.value,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fctResult, null, 2) }] } };
}
@@ -907,11 +984,11 @@ export function registerMcpEndpoints(
const fqAny = typeof args.matchAny === "string" && args.matchAny.trim()
? args.matchAny.split(",").map((s: string) => s.trim()).filter(Boolean)
: undefined;
- const fqResult = await sdk.trigger("mem::facet-query", {
+ const fqResult = await sdk.trigger({ function_id: "mem::facet-query", payload: {
matchAll: fqAll,
matchAny: fqAny,
targetType: args.targetType,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult, null, 2) }] } };
}
@@ -919,7 +996,7 @@ export function registerMcpEndpoints(
if (!args.id || typeof args.id !== "string") {
return { status_code: 400, body: { error: "id is required" } };
}
- const verifyResult = await sdk.trigger("mem::verify", { id: args.id });
+ const verifyResult = await sdk.trigger({ function_id: "mem::verify", payload: { id: args.id } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult, null, 2) }] } };
}
@@ -930,14 +1007,14 @@ export function registerMcpEndpoints(
const lessonTags = typeof args.tags === "string" && args.tags.trim()
? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean)
: [];
- const lessonSaveResult = await sdk.trigger("mem::lesson-save", {
+ const lessonSaveResult = await sdk.trigger({ function_id: "mem::lesson-save", payload: {
content: args.content,
context: args.context || "",
confidence: args.confidence,
project: args.project,
tags: lessonTags,
source: "manual",
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonSaveResult, null, 2) }] } };
}
@@ -945,29 +1022,29 @@ export function registerMcpEndpoints(
if (typeof args.query !== "string" || !args.query.trim()) {
return { status_code: 400, body: { error: "query is required" } };
}
- const lessonRecallResult = await sdk.trigger("mem::lesson-recall", {
+ const lessonRecallResult = await sdk.trigger({ function_id: "mem::lesson-recall", payload: {
query: args.query,
project: args.project,
minConfidence: args.minConfidence,
limit: args.limit,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, null, 2) }] } };
}
case "memory_reflect": {
- const reflectResult = await sdk.trigger("mem::reflect", {
+ const reflectResult = await sdk.trigger({ function_id: "mem::reflect", payload: {
project: args.project,
maxClusters: args.maxClusters,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(reflectResult, null, 2) }] } };
}
case "memory_insight_list": {
- const insightListResult = await sdk.trigger("mem::insight-list", {
+ const insightListResult = await sdk.trigger({ function_id: "mem::insight-list", payload: {
project: args.project,
minConfidence: args.minConfidence,
limit: args.limit,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(insightListResult, null, 2) }] } };
}
@@ -975,10 +1052,10 @@ export function registerMcpEndpoints(
const exportTypes = typeof args.types === "string" && args.types.trim()
? args.types.split(",").map((t: string) => t.trim()).filter(Boolean)
: undefined;
- const obsidianResult = await sdk.trigger("mem::obsidian-export", {
+ const obsidianResult = await sdk.trigger({ function_id: "mem::obsidian-export", payload: {
vaultDir: args.vaultDir,
types: exportTypes,
- });
+ } });
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult, null, 2) }] } };
}
@@ -1044,8 +1121,7 @@ export function registerMcpEndpoints(
},
];
- sdk.registerFunction(
- { id: "mcp::resources::list" },
+ sdk.registerFunction("mcp::resources::list",
async (req: ApiRequest): Promise<McpResponse> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1058,8 +1134,7 @@ export function registerMcpEndpoints(
config: { api_path: "/agentmemory/mcp/resources", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "mcp::resources::read" },
+ sdk.registerFunction("mcp::resources::read",
async (req: ApiRequest<{ uri: string }>): Promise<McpResponse> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1106,9 +1181,9 @@ export function registerMcpEndpoints(
body: { error: "Invalid percent-encoding in URI" },
};
}
- const profile = await sdk.trigger("mem::profile", {
+ const profile = await sdk.trigger({ function_id: "mem::profile", payload: {
project: projectName,
- });
+ } });
return {
status_code: 200,
body: {
@@ -1332,8 +1407,7 @@ export function registerMcpEndpoints(
},
];
- sdk.registerFunction(
- { id: "mcp::prompts::list" },
+ sdk.registerFunction("mcp::prompts::list",
async (req: ApiRequest): Promise<McpResponse> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1346,8 +1420,7 @@ export function registerMcpEndpoints(
config: { api_path: "/agentmemory/mcp/prompts", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "mcp::prompts::get" },
+ sdk.registerFunction("mcp::prompts::get",
async (
req: ApiRequest<{ name: string; arguments?: Record<string, string> }>,
): Promise<McpResponse> => {
@@ -1375,7 +1448,10 @@ export function registerMcpEndpoints(
};
}
const searchResult = await sdk
- .trigger("mem::search", { query: taskDesc, limit: 10 })
+ .trigger({
+ function_id: "mem::search",
+ payload: { query: taskDesc, limit: 10 },
+ })
.catch(() => ({ results: [] }));
const memories = await kv.list<Memory>(KV.memories);
const relevant = memories.filter((m) => m.isLatest).slice(0, 5);
@@ -1434,9 +1510,9 @@ export function registerMcpEndpoints(
body: { error: "project argument must be a string" },
};
}
- const result = await sdk.trigger("mem::patterns", {
+ const result = await sdk.trigger({ function_id: "mem::patterns", payload: {
project: promptArgs.project || undefined,
- });
+ } });
return {
status_code: 200,
body: {
diff --git a/src/state/kv.ts b/src/state/kv.ts
index a158286c..0c0e6ccc 100644
--- a/src/state/kv.ts
+++ b/src/state/kv.ts
@@ -4,30 +4,44 @@ export class StateKV {
constructor(private sdk: ISdk) {}
async get<T = unknown>(scope: string, key: string): Promise<T | null> {
- return this.sdk.trigger<{ scope: string; key: string }, T | null>(
- 'state::get',
- { scope, key },
- )
+ return this.sdk.trigger<{ scope: string; key: string }, T | null>({
+ function_id: 'state::get',
+ payload: { scope, key },
+ })
}
- async set<T = unknown>(scope: string, key: string, data: T): Promise<T> {
- return this.sdk.trigger<{ scope: string; key: string; data: T }, T>(
- 'state::set',
- { scope, key, data },
- )
+ async set<T = unknown>(scope: string, key: string, value: T): Promise<T> {
+ return this.sdk.trigger<{ scope: string; key: string; value: T }, T>({
+ function_id: 'state::set',
+ payload: { scope, key, value },
+ })
+ }
+
+ async update<T = unknown>(
+ scope: string,
+ key: string,
+ ops: Array<{ type: string; path: string; value?: unknown }>,
+ ): Promise<T> {
+ return this.sdk.trigger<
+ { scope: string; key: string; ops: Array<{ type: string; path: string; value?: unknown }> },
+ T
+ >({
+ function_id: 'state::update',
+ payload: { scope, key, ops },
+ })
}
async delete(scope: string, key: string): Promise<void> {
- return this.sdk.trigger<{ scope: string; key: string }, void>(
- 'state::delete',
- { scope, key },
- )
+ return this.sdk.trigger<{ scope: string; key: string }, void>({
+ function_id: 'state::delete',
+ payload: { scope, key },
+ })
}
async list<T = unknown>(scope: string): Promise<T[]> {
- return this.sdk.trigger<{ scope: string }, T[]>(
- 'state::list',
- { scope },
- )
+ return this.sdk.trigger<{ scope: string }, T[]>({
+ function_id: 'state::list',
+ payload: { scope },
+ })
}
}
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 428fc0f5..ed21141b 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -15,6 +15,12 @@ type Response = {
body: unknown;
};
+function parseOptionalInt(raw: unknown): number | undefined {
+ if (raw === undefined || raw === null || raw === "") return undefined;
+ const n = typeof raw === "number" ? raw : parseInt(String(raw), 10);
+ return Number.isFinite(n) ? n : undefined;
+}
+
function checkAuth(
req: ApiRequest,
secret: string | undefined,
@@ -41,6 +47,31 @@ function requireConfiguredSecret(
};
}
+function asNonEmptyString(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed ? trimmed : null;
+}
+
+function parseOptionalFiniteNumber(value: unknown): number | undefined | null {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
+ if (typeof value === "string") {
+ const trimmed = value.trim();
+ if (!trimmed) return undefined;
+ const parsed = Number(trimmed);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+function parseOptionalPositiveInt(value: unknown): number | undefined | null {
+ const parsed = parseOptionalFiniteNumber(value);
+ if (parsed === undefined || parsed === null) return parsed;
+ if (!Number.isInteger(parsed) || parsed < 1) return null;
+ return parsed;
+}
+
export function registerApiTriggers(
sdk: ISdk,
kv: StateKV,
@@ -49,7 +80,27 @@ export function registerApiTriggers(
provider?: ResilientProvider | { circuitState?: unknown },
): void {
sdk.registerFunction(
- { id: "api::liveness" },
+ "middleware::api-auth",
+ async (input: {
+ request?: { headers?: Record<string, string | undefined> };
+ }) => {
+ if (!secret) return { action: "continue" };
+ const headers = input?.request?.headers || {};
+ const auth = headers["authorization"] || headers["Authorization"];
+ if (
+ typeof auth !== "string" ||
+ !timingSafeCompare(auth, `Bearer ${secret}`)
+ ) {
+ return {
+ action: "respond",
+ response: { status_code: 401, body: { error: "unauthorized" } },
+ };
+ }
+ return { action: "continue" };
+ },
+ );
+
+ sdk.registerFunction("api::liveness",
async (): Promise<Response> => ({
status_code: 200,
body: { status: "ok", service: "agentmemory" },
@@ -61,12 +112,8 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/livez", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::health" },
+ sdk.registerFunction("api::health",
async (req: ApiRequest): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
-
const health = await getLatestHealth(kv);
const functionMetrics = metricsStore ? await metricsStore.getAll() : [];
const circuitBreaker =
@@ -91,48 +138,95 @@ export function registerApiTriggers(
sdk.registerTrigger({
type: "http",
function_id: "api::health",
- config: { api_path: "/agentmemory/health", http_method: "GET" },
+ config: {
+ api_path: "/agentmemory/health",
+ http_method: "GET",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::observe" },
+ sdk.registerFunction("api::observe",
async (req: ApiRequest<HookPayload>): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
- const result = await sdk.trigger("mem::observe", req.body);
+ const body = (req.body ?? {}) as Record<string, unknown>;
+ const hookType = asNonEmptyString(body.hookType);
+ const sessionId = asNonEmptyString(body.sessionId);
+ const project = asNonEmptyString(body.project);
+ const cwd = asNonEmptyString(body.cwd);
+ const timestamp = asNonEmptyString(body.timestamp);
+ if (!hookType || !sessionId || !project || !cwd || !timestamp) {
+ return {
+ status_code: 400,
+ body: {
+ error:
+ "hookType, sessionId, project, cwd, and timestamp are required strings",
+ },
+ };
+ }
+ const payload: HookPayload = {
+ hookType: hookType as HookPayload["hookType"],
+ sessionId,
+ project,
+ cwd,
+ timestamp,
+ data: body.data,
+ };
+ const result = await sdk.trigger({ function_id: "mem::observe", payload });
return { status_code: 201, body: result };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::observe",
- config: { api_path: "/agentmemory/observe", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/observe",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::context" },
+ sdk.registerFunction("api::context",
async (
req: ApiRequest<{ sessionId: string; project: string; budget?: number }>,
): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
- const result = await sdk.trigger("mem::context", req.body);
+ const body = (req.body ?? {}) as Record<string, unknown>;
+ const sessionId = asNonEmptyString(body.sessionId);
+ const project = asNonEmptyString(body.project);
+ if (!sessionId || !project) {
+ return {
+ status_code: 400,
+ body: { error: "sessionId and project are required strings" },
+ };
+ }
+ const budget = parseOptionalPositiveInt(body.budget);
+ if (budget === null) {
+ return {
+ status_code: 400,
+ body: { error: "budget must be a positive integer" },
+ };
+ }
+ const payload: { sessionId: string; project: string; budget?: number } = {
+ sessionId,
+ project,
+ };
+ if (budget !== undefined) payload.budget = budget;
+ const result = await sdk.trigger({ function_id: "mem::context", payload });
return { status_code: 200, body: result };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::context",
- config: { api_path: "/agentmemory/context", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/context",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::search" },
+ sdk.registerFunction("api::search",
async (
req: ApiRequest<{ query: string; limit?: number; project?: string; cwd?: string }>,
): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
const body = (req.body ?? {}) as Record<string, unknown>;
if (typeof body.query !== "string" || !body.query.trim()) {
return { status_code: 400, body: { error: "query is required and must be a non-empty string" } };
@@ -155,24 +249,36 @@ export function registerApiTriggers(
project: body.project as string | undefined,
cwd: body.cwd as string | undefined,
};
- const result = await sdk.trigger("mem::search", payload);
+ const result = await sdk.trigger({ function_id: "mem::search", payload: payload });
return { status_code: 200, body: result };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::search",
- config: { api_path: "/agentmemory/search", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/search",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::session::start" },
+ sdk.registerFunction("api::session::start",
async (
req: ApiRequest<{ sessionId: string; project: string; cwd: string }>,
): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
- const { sessionId, project, cwd } = req.body;
+ const body = (req.body ?? {}) as Record<string, unknown>;
+ const sessionId = asNonEmptyString(body.sessionId);
+ const project = asNonEmptyString(body.project);
+ const cwd = asNonEmptyString(body.cwd);
+ if (!sessionId || !project || !cwd) {
+ return {
+ status_code: 400,
+ body: {
+ error: "sessionId, project, and cwd are required non-empty strings",
+ },
+ };
+ }
const session: Session = {
id: sessionId,
project,
@@ -185,7 +291,7 @@ export function registerApiTriggers(
const contextResult = await sdk.trigger<
{ sessionId: string; project: string },
{ context: string }
- >("mem::context", { sessionId, project });
+ >({ function_id: "mem::context", payload: { sessionId, project } });
return {
status_code: 200,
body: { session, context: contextResult.context },
@@ -195,48 +301,63 @@ export function registerApiTriggers(
sdk.registerTrigger({
type: "http",
function_id: "api::session::start",
- config: { api_path: "/agentmemory/session/start", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/session/start",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::session::end" },
+ sdk.registerFunction("api::session::end",
async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
- const session = await kv.get<Session>(KV.sessions, req.body.sessionId);
- if (session) {
- await kv.set(KV.sessions, req.body.sessionId, {
- ...session,
- endedAt: new Date().toISOString(),
- status: "completed",
- });
+ const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId);
+ if (!sessionId) {
+ return {
+ status_code: 400,
+ body: { error: "sessionId is required and must be a non-empty string" },
+ };
}
+ await kv.update(KV.sessions, sessionId, [
+ { type: "set", path: "endedAt", value: new Date().toISOString() },
+ { type: "set", path: "status", value: "completed" },
+ ]);
return { status_code: 200, body: { success: true } };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::session::end",
- config: { api_path: "/agentmemory/session/end", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/session/end",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::summarize" },
+ sdk.registerFunction("api::summarize",
async (req: ApiRequest<{ sessionId: string }>): Promise<Response> => {
- const authErr = checkAuth(req, secret);
- if (authErr) return authErr;
- const result = await sdk.trigger("mem::summarize", req.body);
+ const sessionId = asNonEmptyString((req.body as Record<string, unknown>)?.sessionId);
+ if (!sessionId) {
+ return { status_code: 400, body: { error: "sessionId is required" } };
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::summarize",
+ payload: { sessionId },
+ });
return { status_code: 200, body: result };
},
);
sdk.registerTrigger({
type: "http",
function_id: "api::summarize",
- config: { api_path: "/agentmemory/summarize", http_method: "POST" },
+ config: {
+ api_path: "/agentmemory/summarize",
+ http_method: "POST",
+ middleware_function_ids: ["middleware::api-auth"],
+ },
});
- sdk.registerFunction(
- { id: "api::sessions" },
+ sdk.registerFunction("api::sessions",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -250,12 +371,11 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/sessions", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::observations" },
+ sdk.registerFunction("api::observations",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const sessionId = req.query_params["sessionId"] as string;
+ const sessionId = asNonEmptyString(req.query_params?.["sessionId"]);
if (!sessionId)
return { status_code: 400, body: { error: "sessionId required" } };
const observations = await kv.list<CompressedObservation>(
@@ -270,14 +390,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/observations", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::file-context" },
+ sdk.registerFunction("api::file-context",
async (
req: ApiRequest<{ sessionId: string; files: string[] }>,
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::file-context", req.body);
+ const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -287,8 +406,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/file-context", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::enrich" },
+ sdk.registerFunction("api::enrich",
async (
req: ApiRequest<{
sessionId: string;
@@ -323,7 +441,7 @@ export function registerApiTriggers(
body: { error: "terms must be an array of strings" },
};
}
- const result = await sdk.trigger("mem::enrich", req.body);
+ const result = await sdk.trigger({ function_id: "mem::enrich", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -333,8 +451,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/enrich", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::remember" },
+ sdk.registerFunction("api::remember",
async (
req: ApiRequest<{
content: string;
@@ -352,7 +469,7 @@ export function registerApiTriggers(
) {
return { status_code: 400, body: { error: "content is required" } };
}
- const result = await sdk.trigger("mem::remember", req.body);
+ const result = await sdk.trigger({ function_id: "mem::remember", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -362,8 +479,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/remember", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::forget" },
+ sdk.registerFunction("api::forget",
async (
req: ApiRequest<{
sessionId?: string;
@@ -379,7 +495,7 @@ export function registerApiTriggers(
body: { error: "sessionId or memoryId is required" },
};
}
- const result = await sdk.trigger("mem::forget", req.body);
+ const result = await sdk.trigger({ function_id: "mem::forget", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -389,14 +505,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/forget", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::consolidate" },
+ sdk.registerFunction("api::consolidate",
async (
req: ApiRequest<{ project?: string; minObservations?: number }>,
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::consolidate", req.body);
+ const result = await sdk.trigger({ function_id: "mem::consolidate", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -406,12 +521,11 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/consolidate", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::patterns" },
+ sdk.registerFunction("api::patterns",
async (req: ApiRequest<{ project?: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::patterns", req.body);
+ const result = await sdk.trigger({ function_id: "mem::patterns", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -421,12 +535,11 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/patterns", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::generate-rules" },
+ sdk.registerFunction("api::generate-rules",
async (req: ApiRequest<{ project?: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::generate-rules", req.body);
+ const result = await sdk.trigger({ function_id: "mem::generate-rules", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -436,15 +549,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/generate-rules", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::migrate" },
+ sdk.registerFunction("api::migrate",
async (req: ApiRequest<{ dbPath: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
if (!req.body?.dbPath || typeof req.body.dbPath !== "string") {
return { status_code: 400, body: { error: "dbPath is required" } };
}
- const result = await sdk.trigger("mem::migrate", req.body);
+ const result = await sdk.trigger({ function_id: "mem::migrate", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -454,14 +566,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/migrate", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::evict" },
+ sdk.registerFunction("api::evict",
async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const dryRun =
req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true;
- const result = await sdk.trigger("mem::evict", { dryRun });
+ const result = await sdk.trigger({ function_id: "mem::evict", payload: { dryRun } });
return { status_code: 200, body: result };
},
);
@@ -471,8 +582,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/evict", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::smart-search" },
+ sdk.registerFunction("api::smart-search",
async (
req: ApiRequest<{ query?: string; expandIds?: string[]; limit?: number }>,
): Promise<Response> => {
@@ -487,7 +597,7 @@ export function registerApiTriggers(
body: { error: "query or expandIds is required" },
};
}
- const result = await sdk.trigger("mem::smart-search", req.body);
+ const result = await sdk.trigger({ function_id: "mem::smart-search", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -497,8 +607,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/smart-search", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::timeline" },
+ sdk.registerFunction("api::timeline",
async (
req: ApiRequest<{
anchor: string;
@@ -512,7 +621,7 @@ export function registerApiTriggers(
if (!req.body?.anchor) {
return { status_code: 400, body: { error: "anchor is required" } };
}
- const result = await sdk.trigger("mem::timeline", req.body);
+ const result = await sdk.trigger({ function_id: "mem::timeline", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -522,8 +631,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/timeline", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::profile" },
+ sdk.registerFunction("api::profile",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -534,7 +642,7 @@ export function registerApiTriggers(
body: { error: "project query param is required" },
};
}
- const result = await sdk.trigger("mem::profile", { project });
+ const result = await sdk.trigger({ function_id: "mem::profile", payload: { project } });
return { status_code: 200, body: result };
},
);
@@ -544,12 +652,11 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/profile", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::export" },
+ sdk.registerFunction("api::export",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::export", {});
+ const result = await sdk.trigger({ function_id: "mem::export", payload: {} });
return { status_code: 200, body: result };
},
);
@@ -559,8 +666,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/export", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::import" },
+ sdk.registerFunction("api::import",
async (
req: ApiRequest<{
exportData: unknown;
@@ -572,7 +678,7 @@ export function registerApiTriggers(
if (!req.body?.exportData) {
return { status_code: 400, body: { error: "exportData is required" } };
}
- const result = await sdk.trigger("mem::import", req.body);
+ const result = await sdk.trigger({ function_id: "mem::import", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -582,8 +688,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/import", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::relations" },
+ sdk.registerFunction("api::relations",
async (
req: ApiRequest<{ sourceId: string; targetId: string; type: string }>,
): Promise<Response> => {
@@ -595,7 +700,7 @@ export function registerApiTriggers(
body: { error: "sourceId, targetId, and type are required" },
};
}
- const result = await sdk.trigger("mem::relate", req.body);
+ const result = await sdk.trigger({ function_id: "mem::relate", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -605,8 +710,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/relations", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::evolve" },
+ sdk.registerFunction("api::evolve",
async (
req: ApiRequest<{
memoryId: string;
@@ -622,7 +726,7 @@ export function registerApiTriggers(
body: { error: "memoryId and newContent are required" },
};
}
- const result = await sdk.trigger("mem::evolve", req.body);
+ const result = await sdk.trigger({ function_id: "mem::evolve", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -632,14 +736,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/evolve", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::auto-forget" },
+ sdk.registerFunction("api::auto-forget",
async (req: ApiRequest<{ dryRun?: boolean }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const dryRun =
req.query_params?.["dryRun"] === "true" || req.body?.dryRun === true;
- const result = await sdk.trigger("mem::auto-forget", { dryRun });
+ const result = await sdk.trigger({ function_id: "mem::auto-forget", payload: { dryRun } });
return { status_code: 200, body: result };
},
);
@@ -649,13 +752,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/auto-forget", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::claude-bridge-read" },
+ sdk.registerFunction("api::claude-bridge-read",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::claude-bridge-read", {});
+ const result = await sdk.trigger({ function_id: "mem::claude-bridge-read", payload: {} });
return { status_code: 200, body: result };
} catch {
return {
@@ -671,13 +773,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/claude-bridge/read", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::claude-bridge-sync" },
+ sdk.registerFunction("api::claude-bridge-sync",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::claude-bridge-sync", {});
+ const result = await sdk.trigger({ function_id: "mem::claude-bridge-sync", payload: {} });
return { status_code: 200, body: result };
} catch {
return {
@@ -696,8 +797,7 @@ export function registerApiTriggers(
},
});
- sdk.registerFunction(
- { id: "api::graph-query" },
+ sdk.registerFunction("api::graph-query",
async (
req: ApiRequest<{
startNodeId?: string;
@@ -709,7 +809,7 @@ export function registerApiTriggers(
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::graph-query", req.body || {});
+ const result = await sdk.trigger({ function_id: "mem::graph-query", payload: req.body || {} });
return { status_code: 200, body: result };
} catch {
return {
@@ -725,13 +825,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/graph/query", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::graph-stats" },
+ sdk.registerFunction("api::graph-stats",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::graph-stats", {});
+ const result = await sdk.trigger({ function_id: "mem::graph-stats", payload: {} });
return { status_code: 200, body: result };
} catch {
return {
@@ -747,8 +846,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/graph/stats", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::graph-extract" },
+ sdk.registerFunction("api::graph-extract",
async (req: ApiRequest<{ observations: unknown[] }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -762,7 +860,7 @@ export function registerApiTriggers(
};
}
try {
- const result = await sdk.trigger("mem::graph-extract", req.body);
+ const result = await sdk.trigger({ function_id: "mem::graph-extract", payload: req.body });
return { status_code: 200, body: result };
} catch {
return {
@@ -778,16 +876,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/graph/extract", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::consolidate-pipeline" },
+ sdk.registerFunction("api::consolidate-pipeline",
async (req: ApiRequest<{ tier?: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger(
- "mem::consolidate-pipeline",
- req.body || {},
- );
+ const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: req.body || {},
+ });
return { status_code: 200, body: result };
} catch {
return {
@@ -806,8 +901,7 @@ export function registerApiTriggers(
},
});
- sdk.registerFunction(
- { id: "api::team-share" },
+ sdk.registerFunction("api::team-share",
async (
req: ApiRequest<{ itemId: string; itemType: string; project?: string }>,
): Promise<Response> => {
@@ -820,7 +914,7 @@ export function registerApiTriggers(
};
}
try {
- const result = await sdk.trigger("mem::team-share", req.body);
+ const result = await sdk.trigger({ function_id: "mem::team-share", payload: req.body });
return { status_code: 201, body: result };
} catch {
return { status_code: 404, body: { error: "Team memory not enabled" } };
@@ -833,14 +927,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/team/share", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::team-feed" },
+ sdk.registerFunction("api::team-feed",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const limit = parseInt(req.query_params?.["limit"] as string) || 20;
- const result = await sdk.trigger("mem::team-feed", { limit });
+ const parsedLimit = parseOptionalInt(req.query_params?.["limit"]);
+ const limit = parsedLimit ?? 20;
+ const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit } });
return { status_code: 200, body: result };
} catch {
return { status_code: 404, body: { error: "Team memory not enabled" } };
@@ -853,13 +947,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/team/feed", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::team-profile" },
+ sdk.registerFunction("api::team-profile",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::team-profile", {});
+ const result = await sdk.trigger({ function_id: "mem::team-profile", payload: {} });
return { status_code: 200, body: result };
} catch {
return { status_code: 404, body: { error: "Team memory not enabled" } };
@@ -872,15 +965,15 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/team/profile", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::audit" },
+ sdk.registerFunction("api::audit",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::audit-query", {
+ const parsedLimit = parseOptionalInt(req.query_params?.["limit"]);
+ const result = await sdk.trigger({ function_id: "mem::audit-query", payload: {
operation: req.query_params?.["operation"],
- limit: parseInt(req.query_params?.["limit"] as string) || 50,
- });
+ limit: parsedLimit ?? 50,
+ } });
return { status_code: 200, body: result };
},
);
@@ -890,8 +983,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/audit", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::governance-delete" },
+ sdk.registerFunction("api::governance-delete",
async (
req: ApiRequest<{ memoryIds: string[]; reason?: string }>,
): Promise<Response> => {
@@ -903,7 +995,7 @@ export function registerApiTriggers(
body: { error: "memoryIds array is required" },
};
}
- const result = await sdk.trigger("mem::governance-delete", req.body);
+ const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -916,8 +1008,7 @@ export function registerApiTriggers(
},
});
- sdk.registerFunction(
- { id: "api::governance-bulk" },
+ sdk.registerFunction("api::governance-bulk",
async (
req: ApiRequest<{
type?: string[];
@@ -929,7 +1020,7 @@ export function registerApiTriggers(
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::governance-bulk", req.body || {});
+ const result = await sdk.trigger({ function_id: "mem::governance-bulk", payload: req.body || {} });
return { status_code: 200, body: result };
},
);
@@ -942,13 +1033,12 @@ export function registerApiTriggers(
},
});
- sdk.registerFunction(
- { id: "api::snapshots" },
+ sdk.registerFunction("api::snapshots",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::snapshot-list", {});
+ const result = await sdk.trigger({ function_id: "mem::snapshot-list", payload: {} });
return { status_code: 200, body: result };
} catch {
return { status_code: 404, body: { error: "Snapshots not enabled" } };
@@ -961,16 +1051,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/snapshots", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::snapshot-create" },
+ sdk.registerFunction("api::snapshot-create",
async (req: ApiRequest<{ message?: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger(
- "mem::snapshot-create",
- req.body || {},
- );
+ const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: req.body || {},
+ });
return { status_code: 201, body: result };
} catch {
return { status_code: 404, body: { error: "Snapshots not enabled" } };
@@ -983,8 +1070,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/snapshot/create", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::snapshot-restore" },
+ sdk.registerFunction("api::snapshot-restore",
async (req: ApiRequest<{ commitHash: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -992,7 +1078,7 @@ export function registerApiTriggers(
return { status_code: 400, body: { error: "commitHash is required" } };
}
try {
- const result = await sdk.trigger("mem::snapshot-restore", req.body);
+ const result = await sdk.trigger({ function_id: "mem::snapshot-restore", payload: req.body });
return { status_code: 200, body: result };
} catch {
return { status_code: 404, body: { error: "Snapshots not enabled" } };
@@ -1005,8 +1091,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/snapshot/restore", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::memories" },
+ sdk.registerFunction("api::memories",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1022,8 +1107,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/memories", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::action-create" },
+ sdk.registerFunction("api::action-create",
async (
req: ApiRequest<{
title: string;
@@ -1041,7 +1125,7 @@ export function registerApiTriggers(
if (!req.body?.title) {
return { status_code: 400, body: { error: "title is required" } };
}
- const result = await sdk.trigger("mem::action-create", req.body);
+ const result = await sdk.trigger({ function_id: "mem::action-create", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1051,8 +1135,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/actions", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::action-update" },
+ sdk.registerFunction("api::action-update",
async (
req: ApiRequest<{
actionId: string;
@@ -1068,7 +1151,7 @@ export function registerApiTriggers(
if (!req.body?.actionId) {
return { status_code: 400, body: { error: "actionId is required" } };
}
- const result = await sdk.trigger("mem::action-update", req.body);
+ const result = await sdk.trigger({ function_id: "mem::action-update", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -1078,16 +1161,15 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/actions/update", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::action-list" },
+ sdk.registerFunction("api::action-list",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::action-list", {
+ const result = await sdk.trigger({ function_id: "mem::action-list", payload: {
status: req.query_params?.["status"],
project: req.query_params?.["project"],
parentId: req.query_params?.["parentId"],
- });
+ } });
return { status_code: 200, body: result };
},
);
@@ -1097,8 +1179,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/actions", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::action-get" },
+ sdk.registerFunction("api::action-get",
async (req: ApiRequest<{ actionId: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1106,7 +1187,7 @@ export function registerApiTriggers(
if (!actionId) {
return { status_code: 400, body: { error: "actionId required" } };
}
- const result = await sdk.trigger("mem::action-get", { actionId });
+ const result = await sdk.trigger({ function_id: "mem::action-get", payload: { actionId } });
return { status_code: 200, body: result };
},
);
@@ -1116,8 +1197,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/actions/get", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::action-edge" },
+ sdk.registerFunction("api::action-edge",
async (
req: ApiRequest<{
sourceActionId: string;
@@ -1130,7 +1210,7 @@ export function registerApiTriggers(
if (!req.body?.sourceActionId || !req.body?.targetActionId || !req.body?.type) {
return { status_code: 400, body: { error: "sourceActionId, targetActionId, and type are required" } };
}
- const result = await sdk.trigger("mem::action-edge-create", req.body);
+ const result = await sdk.trigger({ function_id: "mem::action-edge-create", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1140,16 +1220,16 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/actions/edges", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::frontier" },
+ sdk.registerFunction("api::frontier",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::frontier", {
+ const parsedLimit = parseOptionalInt(req.query_params?.["limit"]);
+ const result = await sdk.trigger({ function_id: "mem::frontier", payload: {
project: req.query_params?.["project"],
agentId: req.query_params?.["agentId"],
- limit: parseInt(req.query_params?.["limit"] as string) || undefined,
- });
+ limit: parsedLimit,
+ } });
return { status_code: 200, body: result };
},
);
@@ -1159,15 +1239,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/frontier", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::next" },
+ sdk.registerFunction("api::next",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::next", {
+ const result = await sdk.trigger({ function_id: "mem::next", payload: {
project: req.query_params?.["project"],
agentId: req.query_params?.["agentId"],
- });
+ } });
return { status_code: 200, body: result };
},
);
@@ -1177,8 +1256,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/next", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::lease-acquire" },
+ sdk.registerFunction("api::lease-acquire",
async (
req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>,
): Promise<Response> => {
@@ -1187,7 +1265,7 @@ export function registerApiTriggers(
if (!req.body?.actionId || !req.body?.agentId) {
return { status_code: 400, body: { error: "actionId and agentId are required" } };
}
- const result = await sdk.trigger("mem::lease-acquire", req.body);
+ const result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -1197,8 +1275,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/leases/acquire", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::lease-release" },
+ sdk.registerFunction("api::lease-release",
async (
req: ApiRequest<{ actionId: string; agentId: string; result?: string }>,
): Promise<Response> => {
@@ -1207,7 +1284,7 @@ export function registerApiTriggers(
if (!req.body?.actionId || !req.body?.agentId) {
return { status_code: 400, body: { error: "actionId and agentId are required" } };
}
- const result = await sdk.trigger("mem::lease-release", req.body);
+ const result = await sdk.trigger({ function_id: "mem::lease-release", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -1217,8 +1294,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/leases/release", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::lease-renew" },
+ sdk.registerFunction("api::lease-renew",
async (
req: ApiRequest<{ actionId: string; agentId: string; ttlMs?: number }>,
): Promise<Response> => {
@@ -1227,7 +1303,7 @@ export function registerApiTriggers(
if (!req.body?.actionId || !req.body?.agentId) {
return { status_code: 400, body: { error: "actionId and agentId are required" } };
}
- const result = await sdk.trigger("mem::lease-renew", req.body);
+ const result = await sdk.trigger({ function_id: "mem::lease-renew", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -1237,15 +1313,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/leases/renew", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::routine-create" },
+ sdk.registerFunction("api::routine-create",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
if (!req.body?.name) {
return { status_code: 400, body: { error: "name is required" } };
}
- const result = await sdk.trigger("mem::routine-create", req.body);
+ const result = await sdk.trigger({ function_id: "mem::routine-create", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1255,14 +1330,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/routines", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::routine-list" },
+ sdk.registerFunction("api::routine-list",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::routine-list", {
+ const result = await sdk.trigger({ function_id: "mem::routine-list", payload: {
frozen: req.query_params?.["frozen"] === "true" ? true : undefined,
- });
+ } });
return { status_code: 200, body: result };
},
);
@@ -1272,8 +1346,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/routines", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::routine-run" },
+ sdk.registerFunction("api::routine-run",
async (
req: ApiRequest<{ routineId: string; project?: string; initiatedBy?: string }>,
): Promise<Response> => {
@@ -1282,7 +1355,7 @@ export function registerApiTriggers(
if (!req.body?.routineId) {
return { status_code: 400, body: { error: "routineId is required" } };
}
- const result = await sdk.trigger("mem::routine-run", req.body);
+ const result = await sdk.trigger({ function_id: "mem::routine-run", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1292,8 +1365,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/routines/run", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::routine-status" },
+ sdk.registerFunction("api::routine-status",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1301,7 +1373,7 @@ export function registerApiTriggers(
if (!runId) {
return { status_code: 400, body: { error: "runId query param required" } };
}
- const result = await sdk.trigger("mem::routine-status", { runId });
+ const result = await sdk.trigger({ function_id: "mem::routine-status", payload: { runId } });
return { status_code: 200, body: result };
},
);
@@ -1311,8 +1383,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/routines/status", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::signal-send" },
+ sdk.registerFunction("api::signal-send",
async (
req: ApiRequest<{
from: string;
@@ -1327,7 +1398,7 @@ export function registerApiTriggers(
if (!req.body?.from || !req.body?.content) {
return { status_code: 400, body: { error: "from and content are required" } };
}
- const result = await sdk.trigger("mem::signal-send", req.body);
+ const result = await sdk.trigger({ function_id: "mem::signal-send", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1337,8 +1408,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/signals/send", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::signal-read" },
+ sdk.registerFunction("api::signal-read",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
@@ -1346,12 +1416,13 @@ export function registerApiTriggers(
if (!agentId) {
return { status_code: 400, body: { error: "agentId query param required" } };
}
- const result = await sdk.trigger("mem::signal-read", {
+ const parsedLimit = parseOptionalInt(req.query_params?.["limit"]);
+ const result = await sdk.trigger({ function_id: "mem::signal-read", payload: {
agentId,
unreadOnly: req.query_params?.["unreadOnly"] === "true",
threadId: req.query_params?.["threadId"],
- limit: parseInt(req.query_params?.["limit"] as string) || undefined,
- });
+ limit: parsedLimit,
+ } });
return { status_code: 200, body: result };
},
);
@@ -1361,8 +1432,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/signals", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::checkpoint-create" },
+ sdk.registerFunction("api::checkpoint-create",
async (
req: ApiRequest<{
name: string;
@@ -1377,7 +1447,7 @@ export function registerApiTriggers(
if (!req.body?.name) {
return { status_code: 400, body: { error: "name is required" } };
}
- const result = await sdk.trigger("mem::checkpoint-create", req.body);
+ const result = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1387,8 +1457,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/checkpoints", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::checkpoint-resolve" },
+ sdk.registerFunction("api::checkpoint-resolve",
async (
req: ApiRequest<{
checkpointId: string;
@@ -1402,7 +1471,7 @@ export function registerApiTriggers(
if (!req.body?.checkpointId || !req.body?.status) {
return { status_code: 400, body: { error: "checkpointId and status are required" } };
}
- const result = await sdk.trigger("mem::checkpoint-resolve", req.body);
+ const result = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: req.body });
return { status_code: 200, body: result };
},
);
@@ -1412,15 +1481,14 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/checkpoints/resolve", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::checkpoint-list" },
+ sdk.registerFunction("api::checkpoint-list",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::checkpoint-list", {
+ const result = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: {
status: req.query_params?.["status"],
type: req.query_params?.["type"],
- });
+ } });
return { status_code: 200, body: result };
},
);
@@ -1430,8 +1498,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/checkpoints", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::mesh-register" },
+ sdk.registerFunction("api::mesh-register",
async (
req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>,
): Promise<Response> => {
@@ -1442,7 +1509,7 @@ export function registerApiTriggers(
if (!req.body?.url || !req.body?.name) {
return { status_code: 400, body: { error: "url and name are required" } };
}
- const result = await sdk.trigger("mem::mesh-register", req.body);
+ const result = await sdk.trigger({ function_id: "mem::mesh-register", payload: req.body });
return { status_code: 201, body: result };
},
);
@@ -1452,14 +1519,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/mesh/peers", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::mesh-list" },
+ sdk.registerFunction("api::mesh-list",
async (req: ApiRequest): Promise<Response> => {
const secretErr = requireConfiguredSecret(secret, "mesh");
if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::mesh-list", {});
+ const result = await sdk.trigger({ function_id: "mem::mesh-list", payload: {} });
return { status_code: 200, body: result };
},
);
@@ -1469,8 +1535,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/mesh/peers", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::mesh-sync" },
+ sdk.registerFunction("api::mesh-sync",
async (
req: ApiRequest<{ peerId?: string; direction?: string }>,
): Promise<Response> => {
@@ -1478,7 +1543,7 @@ export function registerApiTriggers(
if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::mesh-sync", req.body || {});
+ const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: req.body || {} });
return { status_code: 200, body: result };
},
);
@@ -1488,14 +1553,13 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/mesh/sync", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::mesh-receive" },
+ sdk.registerFunction("api::mesh-receive",
async (req: ApiRequest): Promise<Response> => {
const secretErr = requireConfiguredSecret(secret, "mesh");
if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger("mem::mesh-receive", req.body || {});
+ const result = await sdk.trigger({ function_id: "mem::mesh-receive", payload: req.body || {} });
return { status_code: 200, body: result };
},
);
@@ -1505,8 +1569,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/mesh/receive", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::mesh-export" },
+ sdk.registerFunction("api::mesh-export",
async (req: ApiRequest): Promise<Response> => {
const secretErr = requireConfiguredSecret(secret, "mesh");
if (secretErr) return secretErr;
@@ -1555,8 +1618,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/mesh/export", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::flow-compress" },
+ sdk.registerFunction("api::flow-compress",
async (
req: ApiRequest<{
runId?: string;
@@ -1567,7 +1629,7 @@ export function registerApiTriggers(
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
try {
- const result = await sdk.trigger("mem::flow-compress", req.body || {});
+ const result = await sdk.trigger({ function_id: "mem::flow-compress", payload: req.body || {} });
return { status_code: 200, body: result };
} catch {
return {
@@ -1583,13 +1645,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/flow/compress", http_method: "POST" },
});
- sdk.registerFunction(
- { id: "api::branch-detect" },
+ sdk.registerFunction("api::branch-detect",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
- const result = await sdk.trigger("mem::detect-worktree", { cwd });
+ const result = await sdk.trigger({ function_id: "mem::detect-worktree", payload: { cwd } });
return { status_code: 200, body: result };
},
);
@@ -1599,13 +1660,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/branch/detect", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::branch-worktrees" },
+ sdk.registerFunction("api::branch-worktrees",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
- const result = await sdk.trigger("mem::list-worktrees", { cwd });
+ const result = await sdk.trigger({ function_id: "mem::list-worktrees", payload: { cwd } });
return { status_code: 200, body: result };
},
);
@@ -1615,13 +1675,12 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/branch/worktrees", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::branch-sessions" },
+ sdk.registerFunction("api::branch-sessions",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const cwd = (req.query_params?.["cwd"] as string) || process.cwd();
- const result = await sdk.trigger("mem::branch-sessions", { cwd });
+ const result = await sdk.trigger({ function_id: "mem::branch-sessions", payload: { cwd } });
return { status_code: 200, body: result };
},
);
@@ -1631,8 +1690,7 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" },
});
- sdk.registerFunction(
- { id: "api::viewer" },
+ sdk.registerFunction("api::viewer",
async (req: ApiRequest): Promise<Response> => {
const denied = checkAuth(req, secret);
if (denied) return denied;
@@ -1662,325 +1720,370 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/viewer", http_method: "GET" },
});
- sdk.registerFunction({ id: "api::sentinel-create" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sentinel-create", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.name) return { status_code: 400, body: { error: "name is required" } };
- const result = await sdk.trigger("mem::sentinel-create", body);
+ const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sentinel-create", config: { api_path: "/agentmemory/sentinels", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sentinel-trigger" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sentinel-trigger", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } };
- const result = await sdk.trigger("mem::sentinel-trigger", body);
+ const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sentinel-trigger", config: { api_path: "/agentmemory/sentinels/trigger", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sentinel-check" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sentinel-check", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
- const result = await sdk.trigger("mem::sentinel-check", {});
+ const result = await sdk.trigger({ function_id: "mem::sentinel-check", payload: {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sentinel-check", config: { api_path: "/agentmemory/sentinels/check", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sentinel-cancel" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sentinel-cancel", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.sentinelId) return { status_code: 400, body: { error: "sentinelId is required" } };
- const result = await sdk.trigger("mem::sentinel-cancel", body);
+ const result = await sdk.trigger({ function_id: "mem::sentinel-cancel", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sentinel-cancel", config: { api_path: "/agentmemory/sentinels/cancel", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sentinel-list" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sentinel-list", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::sentinel-list", { status: params.status, type: params.type });
+ const result = await sdk.trigger({ function_id: "mem::sentinel-list", payload: { status: params.status, type: params.type } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sentinel-list", config: { api_path: "/agentmemory/sentinels", http_method: "GET" } });
- sdk.registerFunction({ id: "api::sketch-create" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-create", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.title) return { status_code: 400, body: { error: "title is required" } };
- const result = await sdk.trigger("mem::sketch-create", body);
+ const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-create", config: { api_path: "/agentmemory/sketches", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sketch-add" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-add", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.sketchId || !body?.title) return { status_code: 400, body: { error: "sketchId and title are required" } };
- const result = await sdk.trigger("mem::sketch-add", body);
+ const result = await sdk.trigger({ function_id: "mem::sketch-add", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-add", config: { api_path: "/agentmemory/sketches/add", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sketch-promote" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-promote", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } };
- const result = await sdk.trigger("mem::sketch-promote", body);
+ const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-promote", config: { api_path: "/agentmemory/sketches/promote", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sketch-discard" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-discard", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.sketchId) return { status_code: 400, body: { error: "sketchId is required" } };
- const result = await sdk.trigger("mem::sketch-discard", body);
+ const result = await sdk.trigger({ function_id: "mem::sketch-discard", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-discard", config: { api_path: "/agentmemory/sketches/discard", http_method: "POST" } });
- sdk.registerFunction({ id: "api::sketch-list" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-list", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::sketch-list", { status: params.status, project: params.project });
+ const result = await sdk.trigger({ function_id: "mem::sketch-list", payload: { status: params.status, project: params.project } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-list", config: { api_path: "/agentmemory/sketches", http_method: "GET" } });
- sdk.registerFunction({ id: "api::sketch-gc" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::sketch-gc", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
- const result = await sdk.trigger("mem::sketch-gc", {});
+ const result = await sdk.trigger({ function_id: "mem::sketch-gc", payload: {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::sketch-gc", config: { api_path: "/agentmemory/sketches/gc", http_method: "POST" } });
- sdk.registerFunction({ id: "api::crystallize" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::crystallize", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.actionIds) return { status_code: 400, body: { error: "actionIds is required" } };
- const result = await sdk.trigger("mem::crystallize", body);
+ const result = await sdk.trigger({ function_id: "mem::crystallize", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::crystallize", config: { api_path: "/agentmemory/crystals/create", http_method: "POST" } });
- sdk.registerFunction({ id: "api::crystal-list" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::crystal-list", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::crystal-list", { project: params.project, sessionId: params.sessionId, limit: params.limit ? parseInt(params.limit as string) : undefined });
+ const limit = parseOptionalPositiveInt(params.limit);
+ if (limit === null) {
+ return {
+ status_code: 400,
+ body: { error: "invalid numeric parameter: limit" },
+ };
+ }
+ const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { project: params.project, sessionId: params.sessionId, limit } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::crystal-list", config: { api_path: "/agentmemory/crystals", http_method: "GET" } });
- sdk.registerFunction({ id: "api::auto-crystallize" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::auto-crystallize", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
- const result = await sdk.trigger("mem::auto-crystallize", body || {});
+ const result = await sdk.trigger({ function_id: "mem::auto-crystallize", payload: body || {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::auto-crystallize", config: { api_path: "/agentmemory/crystals/auto", http_method: "POST" } });
- sdk.registerFunction({ id: "api::diagnose" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::diagnose", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
- const result = await sdk.trigger("mem::diagnose", body || {});
+ const result = await sdk.trigger({ function_id: "mem::diagnose", payload: body || {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::diagnose", config: { api_path: "/agentmemory/diagnostics", http_method: "POST" } });
- sdk.registerFunction({ id: "api::heal" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::heal", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
- const result = await sdk.trigger("mem::heal", body || {});
+ const result = await sdk.trigger({ function_id: "mem::heal", payload: body || {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::heal", config: { api_path: "/agentmemory/diagnostics/heal", http_method: "POST" } });
- sdk.registerFunction({ id: "api::facet-tag" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::facet-tag", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.targetId || !body?.dimension || !body?.value) return { status_code: 400, body: { error: "targetId, dimension, and value are required" } };
- const result = await sdk.trigger("mem::facet-tag", body);
+ const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-tag", config: { api_path: "/agentmemory/facets", http_method: "POST" } });
- sdk.registerFunction({ id: "api::facet-untag" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::facet-untag", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.targetId || !body?.dimension) return { status_code: 400, body: { error: "targetId and dimension are required" } };
- const result = await sdk.trigger("mem::facet-untag", body);
+ const result = await sdk.trigger({ function_id: "mem::facet-untag", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-untag", config: { api_path: "/agentmemory/facets/remove", http_method: "POST" } });
- sdk.registerFunction({ id: "api::facet-query" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::facet-query", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
- const result = await sdk.trigger("mem::facet-query", body || {});
+ const result = await sdk.trigger({ function_id: "mem::facet-query", payload: body || {} });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-query", config: { api_path: "/agentmemory/facets/query", http_method: "POST" } });
- sdk.registerFunction({ id: "api::facet-get" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::facet-get", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
if (!params.targetId) return { status_code: 400, body: { error: "targetId query param is required" } };
- const result = await sdk.trigger("mem::facet-get", { targetId: params.targetId });
+ const result = await sdk.trigger({ function_id: "mem::facet-get", payload: { targetId: params.targetId } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-get", config: { api_path: "/agentmemory/facets", http_method: "GET" } });
- sdk.registerFunction({ id: "api::facet-stats" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::facet-stats", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::facet-stats", { targetType: params.targetType });
+ const result = await sdk.trigger({ function_id: "mem::facet-stats", payload: { targetType: params.targetType } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::facet-stats", config: { api_path: "/agentmemory/facets/stats", http_method: "GET" } });
- sdk.registerFunction({ id: "api::verify" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::verify", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.id || typeof body.id !== "string") return { status_code: 400, body: { error: "id is required" } };
- const result = await sdk.trigger("mem::verify", { id: body.id });
+ const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: body.id } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::verify", config: { api_path: "/agentmemory/verify", http_method: "POST" } });
- sdk.registerFunction({ id: "api::cascade-update" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::cascade-update", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.supersededMemoryId || typeof body.supersededMemoryId !== "string") {
return { status_code: 400, body: { error: "supersededMemoryId is required" } };
}
- const result = await sdk.trigger("mem::cascade-update", { supersededMemoryId: body.supersededMemoryId });
+ const result = await sdk.trigger({ function_id: "mem::cascade-update", payload: { supersededMemoryId: body.supersededMemoryId } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::cascade-update", config: { api_path: "/agentmemory/cascade-update", http_method: "POST" } });
- sdk.registerFunction({ id: "api::lesson-save" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::lesson-save", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.content || typeof body.content !== "string") return { status_code: 400, body: { error: "content is required" } };
const tags = typeof body.tags === "string" ? (body.tags as string).split(",").map((t: string) => t.trim()).filter(Boolean) : Array.isArray(body.tags) ? body.tags : [];
- const result = await sdk.trigger("mem::lesson-save", {
- content: body.content,
- context: body.context || "",
- confidence: typeof body.confidence === "number" ? body.confidence : undefined,
- project: typeof body.project === "string" ? body.project : undefined,
- tags,
- source: "manual",
- }) as { action?: string };
+ const result = (await sdk.trigger({
+ function_id: "mem::lesson-save",
+ payload: {
+ content: body.content,
+ context: body.context || "",
+ confidence: typeof body.confidence === "number" ? body.confidence : undefined,
+ project: typeof body.project === "string" ? body.project : undefined,
+ tags,
+ source: "manual",
+ },
+ })) as { action?: string };
const statusCode = result?.action === "created" ? 201 : 200;
return { status_code: statusCode, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::lesson-save", config: { api_path: "/agentmemory/lessons", http_method: "POST" } });
- sdk.registerFunction({ id: "api::lesson-list" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::lesson-list", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::lesson-list", {
+ const minConfidence = parseOptionalFiniteNumber(params.minConfidence);
+ if (minConfidence === null) {
+ return {
+ status_code: 400,
+ body: { error: "invalid numeric parameter: minConfidence" },
+ };
+ }
+ const limit = parseOptionalPositiveInt(params.limit);
+ if (limit === null) {
+ return {
+ status_code: 400,
+ body: { error: "invalid numeric parameter: limit" },
+ };
+ }
+ const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: {
project: params.project,
source: params.source,
- minConfidence: params.minConfidence ? parseFloat(params.minConfidence as string) : undefined,
- limit: params.limit ? parseInt(params.limit as string, 10) : undefined,
- });
+ minConfidence,
+ limit,
+ } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::lesson-list", config: { api_path: "/agentmemory/lessons", http_method: "GET" } });
- sdk.registerFunction({ id: "api::lesson-search" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::lesson-search", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } };
- const result = await sdk.trigger("mem::lesson-recall", body);
+ const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: body });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::lesson-search", config: { api_path: "/agentmemory/lessons/search", http_method: "POST" } });
- sdk.registerFunction({ id: "api::lesson-strengthen" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::lesson-strengthen", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.lessonId || typeof body.lessonId !== "string") return { status_code: 400, body: { error: "lessonId is required" } };
- const result = await sdk.trigger("mem::lesson-strengthen", { lessonId: body.lessonId });
+ const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: body.lessonId } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::lesson-strengthen", config: { api_path: "/agentmemory/lessons/strengthen", http_method: "POST" } });
- sdk.registerFunction({ id: "api::obsidian-export" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::obsidian-export", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = (req.body as Record<string, unknown>) || {};
+ const vaultDir = asNonEmptyString(body.vaultDir);
+ if (!vaultDir) {
+ return {
+ status_code: 400,
+ body: { error: "vaultDir must be a non-empty string" },
+ };
+ }
const types = typeof body.types === "string" ? body.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined;
- const result = await sdk.trigger("mem::obsidian-export", { vaultDir: body.vaultDir, types });
+ const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir, types } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::obsidian-export", config: { api_path: "/agentmemory/obsidian/export", http_method: "POST" } });
- sdk.registerFunction({ id: "api::reflect" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::reflect", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = (req.body as Record<string, unknown>) || {};
- const result = await sdk.trigger("mem::reflect", {
+ const result = await sdk.trigger({ function_id: "mem::reflect", payload: {
project: typeof body.project === "string" ? body.project : undefined,
maxClusters: typeof body.maxClusters === "number" ? body.maxClusters : undefined,
- });
+ } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::reflect", config: { api_path: "/agentmemory/reflect", http_method: "POST" } });
- sdk.registerFunction({ id: "api::insight-list" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::insight-list", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const params = req.query_params || {};
- const result = await sdk.trigger("mem::insight-list", {
+ const minConfidence = parseOptionalFiniteNumber(params.minConfidence);
+ if (minConfidence === null) {
+ return {
+ status_code: 400,
+ body: { error: "invalid numeric parameter: minConfidence" },
+ };
+ }
+ const limit = parseOptionalPositiveInt(params.limit);
+ if (limit === null) {
+ return {
+ status_code: 400,
+ body: { error: "invalid numeric parameter: limit" },
+ };
+ }
+ const result = await sdk.trigger({ function_id: "mem::insight-list", payload: {
project: params.project,
- minConfidence: params.minConfidence ? parseFloat(params.minConfidence as string) : undefined,
- limit: params.limit ? parseInt(params.limit as string, 10) : undefined,
- });
+ minConfidence,
+ limit,
+ } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::insight-list", config: { api_path: "/agentmemory/insights", http_method: "GET" } });
- sdk.registerFunction({ id: "api::insight-search" }, async (req: ApiRequest) => {
+ sdk.registerFunction("api::insight-search", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
if (!body?.query || typeof body.query !== "string") return { status_code: 400, body: { error: "query is required" } };
- const result = await sdk.trigger("mem::insight-search", {
+ const result = await sdk.trigger({ function_id: "mem::insight-search", payload: {
query: body.query,
project: typeof body.project === "string" ? body.project : undefined,
minConfidence: typeof body.minConfidence === "number" ? body.minConfidence : undefined,
limit: typeof body.limit === "number" ? body.limit : undefined,
- });
+ } });
return { status_code: 200, body: result };
});
sdk.registerTrigger({ type: "http", function_id: "api::insight-search", config: { api_path: "/agentmemory/insights/search", http_method: "POST" } });
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 88921005..6deb470e 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -1,11 +1,11 @@
-import type { ISdk } from "iii-sdk";
+import { TriggerAction, type ISdk } from "iii-sdk";
import type { HookPayload, Session } from "../types.js";
-import { KV } from "../state/schema.js";
+import { KV, STREAM } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
- { id: "event::session::started" },
+ "event::session::started",
async (data: { sessionId: string; project: string; cwd: string }) => {
const session: Session = {
id: data.sessionId,
@@ -19,53 +19,90 @@ export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {
const contextResult = await sdk.trigger<
{ sessionId: string; project: string },
{ context: string }
- >("mem::context", { sessionId: data.sessionId, project: data.project });
+ >({
+ function_id: "mem::context",
+ payload: { sessionId: data.sessionId, project: data.project },
+ });
return { session, context: contextResult.context };
},
);
sdk.registerTrigger({
- type: "queue",
+ type: "durable:subscriber",
function_id: "event::session::started",
config: { topic: "agentmemory.session.started" },
});
- sdk.registerFunction(
- { id: "event::observation" },
- async (data: HookPayload) => sdk.trigger("mem::observe", data),
+ sdk.registerFunction("event::observation", async (data: HookPayload) =>
+ sdk.trigger({ function_id: "mem::observe", payload: data }),
);
sdk.registerTrigger({
- type: "queue",
+ type: "durable:subscriber",
function_id: "event::observation",
config: { topic: "agentmemory.observation" },
});
- sdk.registerFunction(
- { id: "event::session::stopped" },
- async (data: { sessionId: string }) => sdk.trigger("mem::summarize", data),
+ sdk.registerFunction("event::session::stopped", async (data: { sessionId: string }) =>
+ sdk.trigger({ function_id: "mem::summarize", payload: data }),
);
sdk.registerTrigger({
- type: "queue",
+ type: "durable:subscriber",
function_id: "event::session::stopped",
config: { topic: "agentmemory.session.stopped" },
});
sdk.registerFunction(
- { id: "event::session::ended" },
+ "event::session::ended",
async (data: { sessionId: string }) => {
- const session = await kv.get<Session>(KV.sessions, data.sessionId);
- if (session) {
- await kv.set(KV.sessions, data.sessionId, {
- ...session,
- endedAt: new Date().toISOString(),
- status: "completed",
- });
- }
+ await kv.update(KV.sessions, data.sessionId, [
+ { type: "set", path: "endedAt", value: new Date().toISOString() },
+ { type: "set", path: "status", value: "completed" },
+ ]);
return { success: true };
},
);
sdk.registerTrigger({
- type: "queue",
+ type: "durable:subscriber",
function_id: "event::session::ended",
config: { topic: "agentmemory.session.ended" },
});
+
+ // React to observation count changes and emit a lightweight live event for dashboards/viewer.
+ sdk.registerFunction(
+ "event::session::observation-count-changed",
+ async (payload: {
+ key: string;
+ event_type: string;
+ old_value?: Session;
+ new_value?: Session;
+ }) => {
+ if (payload.event_type === "delete") return { skipped: true };
+ const oldCount = payload.old_value?.observationCount ?? 0;
+ const newCount = payload.new_value?.observationCount ?? 0;
+ if (newCount <= oldCount) return { skipped: true };
+
+ await sdk.trigger({
+ function_id: "stream::send",
+ payload: {
+ stream_name: STREAM.name,
+ group_id: STREAM.viewerGroup,
+ id: `session-activity-${payload.key}-${Date.now()}`,
+ type: "session.activity",
+ data: {
+ sessionId: payload.key,
+ observationCount: newCount,
+ delta: newCount - oldCount,
+ updatedAt: payload.new_value?.updatedAt ?? new Date().toISOString(),
+ },
+ },
+ action: TriggerAction.Void(),
+ });
+
+ return { emitted: true };
+ },
+ );
+ sdk.registerTrigger({
+ type: "state",
+ function_id: "event::session::observation-count-changed",
+ config: { scope: KV.sessions },
+ });
}
diff --git a/src/types.ts b/src/types.ts
index 92068bc9..841f9e70 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -468,6 +468,8 @@ export interface AuditEntry {
| "signal_send"
| "checkpoint_resolve"
| "mesh_sync"
+ | "relation_create"
+ | "relation_update"
| "sentinel_create"
| "sentinel_trigger"
| "sketch_create"
@@ -487,7 +489,8 @@ export interface AuditEntry {
| "skill_extract"
| "core_add"
| "core_remove"
- | "auto_page";
+ | "auto_page"
+ | "relation_create";
userId?: string;
functionId: string;
targetIds: string[];
@@ -796,7 +799,7 @@ export interface RetentionScore {
// Which KV scope this row came from. Needed by mem::retention-evict
// so the delete loop routes to KV.memories or KV.semantic correctly.
// Missing on pre-0.8.10 rows — callers must treat `undefined` as
- // "unknown, assume episodic" for backwards-compat. See #124.
+ // "unknown" and probe both scopes for backwards-compat. See #124.
source?: "episodic" | "semantic";
score: number;
salience: number;
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 9039d8d6..e7a2c396 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -809,6 +809,7 @@
var wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
var wsPort = params.get('wsPort') || String(parseInt(viewerPort) - 1);
var WS_URL = wsProto + '//' + window.location.hostname + ':' + wsPort;
+ var WS_DIRECT_URL = wsProto + '//' + window.location.hostname + ':' + wsPort + '/stream/mem-live/viewer';
var dateEl = document.getElementById('dateline');
if (dateEl) dateEl.textContent = new Date().toLocaleDateString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' });
@@ -2789,33 +2790,61 @@
var wsReconnectTimer = null;
var wsRetries = 0;
var WS_MAX_RETRIES = 10;
+ var directFailed = false;
+ var directFailures = 0;
+ var DIRECT_FAILURE_THRESHOLD = 2;
function connectWs() {
if (wsRetries >= WS_MAX_RETRIES) return;
+ var useDirect = !directFailed;
+ var ws;
try {
- state.ws = new WebSocket(WS_URL);
- state.ws.onopen = function() {
+ ws = new WebSocket(useDirect ? WS_DIRECT_URL : WS_URL);
+ ws.__direct = useDirect;
+ } catch (_) {
+ ws = new WebSocket(WS_URL);
+ ws.__direct = false;
+ }
+ try {
+ ws.onopen = function() {
+ if (state.ws !== ws) return;
wsRetries = 0;
- state.ws.send(JSON.stringify({
- type: 'join',
- data: {
- subscriptionId: 'viewer-' + Date.now(),
- streamName: 'mem-live',
- groupId: 'viewer'
- }
- }));
+ if (ws.__direct) {
+ directFailures = 0;
+ directFailed = false;
+ }
+ if (!ws.__direct) {
+ ws.send(JSON.stringify({
+ type: 'join',
+ data: {
+ subscriptionId: 'viewer-' + Date.now(),
+ streamName: 'mem-live',
+ groupId: 'viewer'
+ }
+ }));
+ }
document.getElementById('ws-status').textContent = 'live';
document.getElementById('ws-status').className = 'ws-status connected';
};
- state.ws.onmessage = function(e) {
+ ws.onmessage = function(e) {
+ if (state.ws !== ws) return;
try {
var msg = JSON.parse(e.data);
if (msg.type === 'stream' && msg.event) {
handleStreamEvent(msg);
+ } else if (msg.event_type && msg.data) {
+ handleStreamEvent({ event: { type: 'create', data: msg.data, event_type: msg.event_type } });
}
} catch {}
};
- state.ws.onclose = function() {
+ ws.onclose = function() {
+ if (state.ws !== ws) return;
+ if (ws.__direct) {
+ directFailures += 1;
+ if (directFailures >= DIRECT_FAILURE_THRESHOLD) {
+ directFailed = true;
+ }
+ }
document.getElementById('ws-status').textContent = 'reconnecting...';
document.getElementById('ws-status').className = 'ws-status disconnected';
wsRetries++;
@@ -2825,7 +2854,11 @@
document.getElementById('ws-status').textContent = 'disconnected';
}
};
- state.ws.onerror = function() { state.ws.close(); };
+ ws.onerror = function() {
+ if (state.ws !== ws) return;
+ try { ws.close(); } catch {}
+ };
+ state.ws = ws;
} catch {
wsRetries++;
if (wsRetries < WS_MAX_RETRIES) {
@@ -2834,20 +2867,36 @@
}
}
+ function looksLikeObservation(obj) {
+ return !!(obj && typeof obj === 'object' && obj.id && obj.timestamp);
+ }
+
function handleStreamEvent(msg) {
var evt = msg.event;
+ var observation;
+ if (!evt) return;
+ if (evt.event_type && evt.event_type !== 'observation' && evt.event_type !== 'create' && evt.event_type !== 'update') {
+ return;
+ }
+ if (evt.type === 'event' && evt.data) {
+ observation = evt.data.observation || evt.data;
+ if (looksLikeObservation(observation)) {
+ routeWsMessage({ observation: observation });
+ }
+ return;
+ }
if ((evt.type === 'create' || evt.type === 'update') && evt.data) {
var payload = evt.data;
- var observation = payload.observation || payload;
- if (observation) {
+ observation = payload.observation || payload;
+ if (looksLikeObservation(observation)) {
routeWsMessage({ observation: observation });
}
} else if (evt.type === 'sync') {
var items = Array.isArray(evt.data) ? evt.data : [];
items.forEach(function(item) {
var payload = item.data || item;
- var observation = payload.observation || payload;
- if (observation) {
+ observation = payload.observation || payload;
+ if (looksLikeObservation(observation)) {
routeWsMessage({ observation: observation });
}
});
diff --git a/test/actions.test.ts b/test/actions.test.ts
index d6b2b2f8..a4ee1a84 100644
--- a/test/actions.test.ts
+++ b/test/actions.test.ts
@@ -8,42 +8,7 @@ vi.mock("iii-sdk", () => ({
import { registerActionsFunction } from "../src/functions/actions.js";
import type { Action, ActionEdge } from "../src/types.js";
-
-function mockKV() {
- const store = new Map<string, Map<string, unknown>>();
- return {
- get: async <T>(scope: string, key: string): Promise<T | null> => {
- return (store.get(scope)?.get(key) as T) ?? null;
- },
- set: async <T>(scope: string, key: string, data: T): Promise<T> => {
- if (!store.has(scope)) store.set(scope, new Map());
- store.get(scope)!.set(key, data);
- return data;
- },
- delete: async (scope: string, key: string): Promise<void> => {
- store.get(scope)?.delete(key);
- },
- list: async <T>(scope: string): Promise<T[]> => {
- const entries = store.get(scope);
- return entries ? (Array.from(entries.values()) as T[]) : [];
- },
- };
-}
-
-function mockSdk() {
- const functions = new Map<string, Function>();
- return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
- },
- registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
- const fn = functions.get(id);
- if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
- },
- };
-}
+import { mockKV, mockSdk } from "./helpers/mocks.js";
describe("Actions Functions", () => {
let sdk: ReturnType<typeof mockSdk>;
diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.ts
index 52b02790..f75f8c0e 100644
--- a/test/auto-compress.test.ts
+++ b/test/auto-compress.test.ts
@@ -1,11 +1,15 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { RawObservation } from "../src/types.js";
-vi.mock("iii-sdk", () => ({
- getContext: () => ({
- logger: { info: () => {}, warn: () => {}, error: () => {} },
- }),
-}));
+vi.mock("iii-sdk", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("iii-sdk")>();
+ return {
+ ...actual,
+ getContext: () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ }),
+ };
+});
function mockKV() {
const store = new Map<string, Map<string, unknown>>();
@@ -34,17 +38,29 @@ function mockSdk() {
return {
fns,
triggered,
- registerFunction: (opts: { id: string }, fn: Function) => {
- fns.set(opts.id, fn);
+ registerFunction: (
+ idOrOpts: string | { id: string },
+ fn: Function,
+ _options?: Record<string, unknown>,
+ ) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ fns.set(id, fn);
},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput:
+ | string
+ | { function_id: string; payload: unknown; action?: unknown },
+ data?: unknown,
+ ) => {
+ const id =
+ typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload =
+ typeof idOrInput === "string" ? data : idOrInput.payload;
+ triggered.push({ id, data: payload });
const fn = fns.get(id);
- if (fn) return fn(data);
+ if (fn) return fn(payload);
return null;
},
- triggerVoid: (id: string, data: unknown) => {
- triggered.push({ id, data });
- },
};
}
diff --git a/test/auto-forget.test.ts b/test/auto-forget.test.ts
index d284cc5a..cda28354 100644
--- a/test/auto-forget.test.ts
+++ b/test/auto-forget.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/checkpoints.test.ts b/test/checkpoints.test.ts
index bdb62972..8aab6ae4 100644
--- a/test/checkpoints.test.ts
+++ b/test/checkpoints.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/claude-bridge.test.ts b/test/claude-bridge.test.ts
index 3edc2a0c..4ce31cae 100644
--- a/test/claude-bridge.test.ts
+++ b/test/claude-bridge.test.ts
@@ -46,14 +46,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/confidence.test.ts b/test/confidence.test.ts
index a3c62635..1b4fa34e 100644
--- a/test/confidence.test.ts
+++ b/test/confidence.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
getFunction: (id: string) => functions.get(id),
};
diff --git a/test/consolidation-pipeline.test.ts b/test/consolidation-pipeline.test.ts
index ff031f92..c05d5508 100644
--- a/test/consolidation-pipeline.test.ts
+++ b/test/consolidation-pipeline.test.ts
@@ -39,14 +39,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/crystallize.test.ts b/test/crystallize.test.ts
index d76450eb..bb13272b 100644
--- a/test/crystallize.test.ts
+++ b/test/crystallize.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/diagnostics.test.ts b/test/diagnostics.test.ts
index 0872f6ca..bd1cbb9e 100644
--- a/test/diagnostics.test.ts
+++ b/test/diagnostics.test.ts
@@ -45,14 +45,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/enrich.test.ts b/test/enrich.test.ts
index 2e8498d8..0ddb9afe 100644
--- a/test/enrich.test.ts
+++ b/test/enrich.test.ts
@@ -52,17 +52,23 @@ function mockSdk() {
const functions = new Map<string, Function>();
const triggerOverrides = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
if (triggerOverrides.has(id)) {
- return triggerOverrides.get(id)!(data);
+ return triggerOverrides.get(id)!(payload);
}
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
overrideTrigger: (id: string, handler: Function) => {
triggerOverrides.set(id, handler);
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index b1a149f4..c478babd 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -39,14 +39,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/facets.test.ts b/test/facets.test.ts
index 85b36fde..9a29935c 100644
--- a/test/facets.test.ts
+++ b/test/facets.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/frontier.test.ts b/test/frontier.test.ts
index f46685b5..131c1e3a 100644
--- a/test/frontier.test.ts
+++ b/test/frontier.test.ts
@@ -35,14 +35,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
@@ -422,17 +425,23 @@ describe("Frontier Functions", () => {
const originalFunctions = new Map<string, Function>();
const failSdk = {
- registerFunction: (opts: { id: string }, handler: Function) => {
- originalFunctions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ originalFunctions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
if (id === "mem::frontier") {
return { success: false, error: "internal failure" };
}
const fn = originalFunctions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
diff --git a/test/governance.test.ts b/test/governance.test.ts
index f725fd19..5621fff5 100644
--- a/test/governance.test.ts
+++ b/test/governance.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/graph.test.ts b/test/graph.test.ts
index 661cbc14..9904f6ae 100644
--- a/test/graph.test.ts
+++ b/test/graph.test.ts
@@ -38,14 +38,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/helpers/mocks.ts b/test/helpers/mocks.ts
index 8b5f48cf..a382e2ee 100644
--- a/test/helpers/mocks.ts
+++ b/test/helpers/mocks.ts
@@ -26,15 +26,28 @@ export function mockKV() {
export function mockSdk() {
const functions = new Map<string, Handler>();
return {
- registerFunction: (opts: { id: string }, handler: Handler) => {
- functions.set(opts.id, handler);
+ registerFunction: (
+ idOrOpts: string | { id: string },
+ handler: Handler,
+ _options?: Record<string, unknown>,
+ ) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: vi.fn(),
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput:
+ | string
+ | { function_id: string; payload: unknown; action?: unknown },
+ data?: unknown,
+ ) => {
+ const id =
+ typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload =
+ typeof idOrInput === "string" ? data : (idOrInput.payload as unknown);
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
- triggerVoid: vi.fn(),
};
}
diff --git a/test/leases.test.ts b/test/leases.test.ts
index 46861f5b..8bceccb0 100644
--- a/test/leases.test.ts
+++ b/test/leases.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/lessons.test.ts b/test/lessons.test.ts
index ce85dfaa..134bcce0 100644
--- a/test/lessons.test.ts
+++ b/test/lessons.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/mcp-prompts.test.ts b/test/mcp-prompts.test.ts
index 903e90d1..53a5d468 100644
--- a/test/mcp-prompts.test.ts
+++ b/test/mcp-prompts.test.ts
@@ -34,17 +34,23 @@ function mockSdk() {
const functions = new Map<string, Function>();
const triggerOverrides = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
if (triggerOverrides.has(id)) {
- return triggerOverrides.get(id)!(data);
+ return triggerOverrides.get(id)!(payload);
}
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
overrideTrigger: (id: string, handler: Function) => {
triggerOverrides.set(id, handler);
diff --git a/test/mcp-resources.test.ts b/test/mcp-resources.test.ts
index fc4a35b0..fdda5c6a 100644
--- a/test/mcp-resources.test.ts
+++ b/test/mcp-resources.test.ts
@@ -34,17 +34,23 @@ function mockSdk() {
const functions = new Map<string, Function>();
const triggerOverrides = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
if (triggerOverrides.has(id)) {
- return triggerOverrides.get(id)!(data);
+ return triggerOverrides.get(id)!(payload);
}
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
overrideTrigger: (id: string, handler: Function) => {
triggerOverrides.set(id, handler);
diff --git a/test/mesh.test.ts b/test/mesh.test.ts
index 91fc29da..a7d7b537 100644
--- a/test/mesh.test.ts
+++ b/test/mesh.test.ts
@@ -42,14 +42,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/obsidian-export.test.ts b/test/obsidian-export.test.ts
index fe11caff..f0199ab1 100644
--- a/test/obsidian-export.test.ts
+++ b/test/obsidian-export.test.ts
@@ -45,14 +45,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/profile.test.ts b/test/profile.test.ts
index b104e344..a1f7b4d9 100644
--- a/test/profile.test.ts
+++ b/test/profile.test.ts
@@ -37,14 +37,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/query-expansion.test.ts b/test/query-expansion.test.ts
index 0dc3f3f0..855012d8 100644
--- a/test/query-expansion.test.ts
+++ b/test/query-expansion.test.ts
@@ -14,12 +14,15 @@ vi.mock("iii-sdk", () => ({
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, fn: Function) => {
- functions.set(opts.id, fn);
+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, fn);
},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
- if (fn) return fn(data);
+ if (fn) return fn(payload);
return null;
},
};
diff --git a/test/reflect.test.ts b/test/reflect.test.ts
index d4e54c0a..143324ce 100644
--- a/test/reflect.test.ts
+++ b/test/reflect.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/relations.test.ts b/test/relations.test.ts
index b818bc0a..22fa71d5 100644
--- a/test/relations.test.ts
+++ b/test/relations.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
getFunction: (id: string) => functions.get(id),
};
diff --git a/test/retention-access.test.ts b/test/retention-access.test.ts
index d27728e9..fddda4b2 100644
--- a/test/retention-access.test.ts
+++ b/test/retention-access.test.ts
@@ -42,12 +42,19 @@ function mockKV(
function mockSdk() {
const fns = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, fn: Function) => {
- fns.set(opts.id, fn);
+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ fns.set(id, fn);
},
- trigger: async (id: string, data: unknown) => {
- const fn = fns.get(id);
- if (fn) return fn(data);
+ trigger: async (
+ input: string | { function_id: string; payload: unknown },
+ data?: unknown,
+ ) => {
+ const functionId =
+ typeof input === "string" ? input : input.function_id;
+ const payload = typeof input === "string" ? data : input.payload;
+ const fn = fns.get(functionId);
+ if (fn) return fn(payload);
return null;
},
};
@@ -118,7 +125,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
await recordAccess(kv as never, "mem_hot", now - i * 60_000);
}
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const hot = result.scores.find((s: any) => s.memoryId === "mem_hot");
const cold = result.scores.find((s: any) => s.memoryId === "mem_cold");
@@ -152,7 +159,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
// mem_old_read: 1 access 60 days ago
await recordAccess(kv as never, "mem_old_read", now - 60 * 86_400_000);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const recent = result.scores.find(
(s: any) => s.memoryId === "mem_recent_read",
);
@@ -182,7 +189,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
const kv = mockKV([], [semWith, semWithout]);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const withEntry = result.scores.find(
(s: any) => s.memoryId === "sem_with_legacy",
);
@@ -210,7 +217,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
const kv = mockKV([], [sem]);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const entry = result.scores.find((s: any) => s.memoryId === "sem_corrupt");
expect(Number.isFinite(entry.score)).toBe(true);
@@ -244,7 +251,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const corrupt = result.scores.find(
(s: any) => s.memoryId === "mem_corrupt",
);
@@ -273,7 +280,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
expect(result.success).toBe(true);
const entry = result.scores.find(
(s: any) => s.memoryId === "mem_resilient",
@@ -299,7 +306,7 @@ describe("RetentionScoring with access log (issue #119)", () => {
await recordAccess(kv as never, "sem_active", now - i * 30_000);
}
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({ function_id: "mem::retention-score", payload: {} })) as any;
const entry = result.scores.find(
(s: any) => s.memoryId === "sem_active",
);
diff --git a/test/retention.test.ts b/test/retention.test.ts
index 2d647288..6a44ae63 100644
--- a/test/retention.test.ts
+++ b/test/retention.test.ts
@@ -49,12 +49,18 @@ function mockKV(
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, fn: Function) => {
- functions.set(opts.id, fn);
+ registerFunction: (idOrOpts: string, fn: Function) => {
+ if (typeof idOrOpts !== "string") {
+ throw new Error("registerFunction expects string function id");
+ }
+ functions.set(idOrOpts, fn);
},
- trigger: async (id: string, data: unknown) => {
- const fn = functions.get(id);
- if (fn) return fn(data);
+ trigger: async (input: { function_id: string; payload: unknown }) => {
+ if (typeof input === "string") {
+ throw new Error("legacy trigger signature is not supported in tests");
+ }
+ const fn = functions.get(input.function_id);
+ if (fn) return fn(input.payload);
return null;
},
};
@@ -126,7 +132,10 @@ describe("RetentionScoring", () => {
const kv = mockKV(memories);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as {
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-score",
+ payload: {},
+ })) as {
success: boolean;
total: number;
tiers: any;
@@ -161,7 +170,10 @@ describe("RetentionScoring", () => {
const kv = mockKV(memories);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-score",
+ payload: {},
+ })) as any;
const archScore = result.scores.find(
(s: any) => s.memoryId === "mem_arch",
@@ -189,7 +201,10 @@ describe("RetentionScoring", () => {
const kv = mockKV(memories);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-score",
+ payload: {},
+ })) as any;
expect(result.tiers.hot + result.tiers.warm + result.tiers.cold + result.tiers.evictable).toBe(4);
});
@@ -207,11 +222,14 @@ describe("RetentionScoring", () => {
const kv = mockKV(memories);
registerRetentionFunctions(sdk as never, kv as never);
- await sdk.trigger("mem::retention-score", {});
+ await sdk.trigger({ function_id: "mem::retention-score", payload: {} });
- const dryResult = (await sdk.trigger("mem::retention-evict", {
- threshold: 0.5,
- dryRun: true,
+ const dryResult = (await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: {
+ threshold: 0.5,
+ dryRun: true,
+ },
})) as any;
expect(dryResult.dryRun).toBe(true);
@@ -235,7 +253,10 @@ describe("RetentionScoring", () => {
const kv = mockKV([], semanticMems);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-score",
+ payload: {},
+ })) as any;
expect(result.total).toBe(2);
const sem1 = result.scores.find((s: any) => s.memoryId === "sem_1");
@@ -255,7 +276,10 @@ describe("RetentionScoring", () => {
);
registerRetentionFunctions(sdk as never, kv as never);
- const result = (await sdk.trigger("mem::retention-score", {})) as any;
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-score",
+ payload: {},
+ })) as any;
const ep = result.scores.find((s: any) => s.memoryId === "mem_ep");
const sem = result.scores.find((s: any) => s.memoryId === "sem_sem");
expect(ep.source).toBe("episodic");
@@ -289,9 +313,10 @@ describe("RetentionScoring", () => {
);
registerRetentionFunctions(sdk as never, kv as never);
- await sdk.trigger("mem::retention-score", {});
- const result = (await sdk.trigger("mem::retention-evict", {
- threshold: 0.9,
+ await sdk.trigger({ function_id: "mem::retention-score", payload: {} });
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: { threshold: 0.9 },
})) as any;
expect(result.evicted).toBe(2);
@@ -320,8 +345,11 @@ describe("RetentionScoring", () => {
);
registerRetentionFunctions(sdk as never, kv as never);
- await sdk.trigger("mem::retention-score", {});
- await sdk.trigger("mem::retention-evict", { threshold: 0.9 });
+ await sdk.trigger({ function_id: "mem::retention-score", payload: {} });
+ await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: { threshold: 0.9 },
+ });
// Retention-score ALSO emits an audit row (one per rescore, also
// required by the repo audit-coverage policy), so filter the audit
@@ -358,8 +386,11 @@ describe("RetentionScoring", () => {
const kv = mockKV([makeMemory("mem_keep", "architecture", 1)]);
registerRetentionFunctions(sdk as never, kv as never);
- await sdk.trigger("mem::retention-score", {});
- await sdk.trigger("mem::retention-evict", { threshold: 0.0001 });
+ await sdk.trigger({ function_id: "mem::retention-score", payload: {} });
+ await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: { threshold: 0.0001 },
+ });
const allEntries = await kv.list<{ functionId: string }>("mem:audit");
const evictEntries = allEntries.filter(
@@ -380,7 +411,7 @@ describe("RetentionScoring", () => {
);
registerRetentionFunctions(sdk as never, kv as never);
- await sdk.trigger("mem::retention-score", {});
+ await sdk.trigger({ function_id: "mem::retention-score", payload: {} });
const allEntries = await kv.list<{
operation: string;
@@ -429,8 +460,9 @@ describe("RetentionScoring", () => {
accessCount: 0,
});
- const result = (await sdk.trigger("mem::retention-evict", {
- threshold: 0.5,
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: { threshold: 0.5 },
})) as any;
expect(result.evicted).toBe(1);
expect(result.evictedSemantic).toBe(1);
@@ -467,8 +499,9 @@ describe("RetentionScoring", () => {
accessCount: 0,
});
- const result = (await sdk.trigger("mem::retention-evict", {
- threshold: 0.5,
+ const result = (await sdk.trigger({
+ function_id: "mem::retention-evict",
+ payload: { threshold: 0.5 },
})) as any;
expect(result.evicted).toBe(1);
expect(result.evictedEpisodic).toBe(1);
diff --git a/test/routines.test.ts b/test/routines.test.ts
index f62b8664..5f6b119f 100644
--- a/test/routines.test.ts
+++ b/test/routines.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/sentinels.test.ts b/test/sentinels.test.ts
index 726d7764..1be91c94 100644
--- a/test/sentinels.test.ts
+++ b/test/sentinels.test.ts
@@ -34,14 +34,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/signals.test.ts b/test/signals.test.ts
index 3e43e46e..145e9339 100644
--- a/test/signals.test.ts
+++ b/test/signals.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/sketches.test.ts b/test/sketches.test.ts
index 2404f3ad..ba00ed2c 100644
--- a/test/sketches.test.ts
+++ b/test/sketches.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/skill-extract.test.ts b/test/skill-extract.test.ts
index cce85231..cc18f87b 100644
--- a/test/skill-extract.test.ts
+++ b/test/skill-extract.test.ts
@@ -39,8 +39,9 @@ describe("skill-extract", () => {
mockKv.list.mockResolvedValue([]);
handlers = {};
- mockSdk.registerFunction.mockImplementation((meta: any, handler: any) => {
- handlers[meta.id] = handler;
+ mockSdk.registerFunction.mockImplementation((idOrMeta: any, handler: any) => {
+ const id = typeof idOrMeta === "string" ? idOrMeta : idOrMeta.id;
+ handlers[id] = handler;
});
registerSkillExtractFunctions(mockSdk as any, mockKv as any, mockProvider);
diff --git a/test/sliding-window.test.ts b/test/sliding-window.test.ts
index b11f16e5..52849931 100644
--- a/test/sliding-window.test.ts
+++ b/test/sliding-window.test.ts
@@ -53,12 +53,15 @@ function mockKV(observations: CompressedObservation[] = []) {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, fn: Function) => {
- functions.set(opts.id, fn);
+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, fn);
},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
- if (fn) return fn(data);
+ if (fn) return fn(payload);
return null;
},
triggerVoid: () => {},
diff --git a/test/smart-search.test.ts b/test/smart-search.test.ts
index ba5bc6e4..6d65eae7 100644
--- a/test/smart-search.test.ts
+++ b/test/smart-search.test.ts
@@ -38,14 +38,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts
index 69d33aca..33b4aab1 100644
--- a/test/snapshot.test.ts
+++ b/test/snapshot.test.ts
@@ -61,14 +61,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/team.test.ts b/test/team.test.ts
index 4ab9493d..684a2d04 100644
--- a/test/team.test.ts
+++ b/test/team.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/temporal-graph.test.ts b/test/temporal-graph.test.ts
index bdf994eb..aed0491d 100644
--- a/test/temporal-graph.test.ts
+++ b/test/temporal-graph.test.ts
@@ -48,12 +48,15 @@ function mockKV(
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, fn: Function) => {
- functions.set(opts.id, fn);
+ registerFunction: (idOrOpts: string | { id: string }, fn: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, fn);
},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
- if (fn) return fn(data);
+ if (fn) return fn(payload);
return null;
},
};
diff --git a/test/timeline.test.ts b/test/timeline.test.ts
index 3e48bf0c..f726c12e 100644
--- a/test/timeline.test.ts
+++ b/test/timeline.test.ts
@@ -33,14 +33,17 @@ function mockKV() {
function mockSdk() {
const functions = new Map<string, Function>();
return {
- registerFunction: (opts: { id: string }, handler: Function) => {
- functions.set(opts.id, handler);
+ registerFunction: (idOrOpts: string | { id: string }, handler: Function) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ functions.set(id, handler);
},
registerTrigger: () => {},
- trigger: async (id: string, data: unknown) => {
+ trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
const fn = functions.get(id);
if (!fn) throw new Error(`No function: ${id}`);
- return fn(data);
+ return fn(payload);
},
};
}
diff --git a/test/working-memory.test.ts b/test/working-memory.test.ts
index 06d0afed..2a90973a 100644
--- a/test/working-memory.test.ts
+++ b/test/working-memory.test.ts
@@ -34,8 +34,9 @@ describe("working-memory", () => {
mockKv.delete.mockResolvedValue(undefined);
handlers = {};
- mockSdk.registerFunction.mockImplementation((meta: any, handler: any) => {
- handlers[meta.id] = handler;
+ mockSdk.registerFunction.mockImplementation((idOrMeta: any, handler: any) => {
+ const id = typeof idOrMeta === "string" ? idOrMeta : idOrMeta.id;
+ handlers[id] = handler;
});
registerWorkingMemoryFunctions(mockSdk as any, mockKv as any, 4000);