Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

test(omp): run the extension behind a redirecting gateway

João Matheus85091bd65c59
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 0f61069e..4b9a9f25 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -15042,6 +15042,105 @@ process.exit(0);
);
}
}
+
+ /// Every request reaches a gateway in front of the server that
+ /// answers with a redirect to its login page on another origin: 302
+ /// for reads, 307 for the event posts, which a followed redirect
+ /// would replay there. One event from an earlier offline session is
+ /// already spooled.
+ const REDIRECT_HARNESS: &str = r#"import { createServer } from "node:http";
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+const project = process.argv[2]!;
+const loginHits: string[] = [];
+const login = createServer((req, res) => {
+ req.resume();
+ loginHits.push(`${req.method} ${req.url}`);
+ res.writeHead(200, { "content-type": "text/html" });
+ res.end("<html>GATEWAY-LOGIN</html>");
+});
+await new Promise<void>((resolve) => login.listen(0, "127.0.0.1", () => resolve()));
+const loginPort = (login.address() as any).port;
+const gatewayBodies: string[] = [];
+const gateway = createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk) => (body += chunk));
+ req.on("end", () => {
+ gatewayBodies.push(body);
+ res.writeHead(req.method === "POST" ? 307 : 302, {
+ location: `http://127.0.0.1:${loginPort}/login`,
+ });
+ res.end();
+ });
+});
+await new Promise<void>((resolve) => gateway.listen(0, "127.0.0.1", () => resolve()));
+const port = (gateway.address() as any).port;
+
+const spool = join(process.env.AI_MEMORY_DATA_DIR!, "hook-spool");
+mkdirSync(spool, { recursive: true });
+writeFileSync(join(spool, "0000000000001-1-0000000000000001.json"), JSON.stringify({
+ url: `http://127.0.0.1:${port}/hook?event=user-prompt&agent=omp`,
+ body: JSON.stringify({ sessionID: "s-offline", prompt: "SPOOLED-WHILE-OFFLINE" }),
+ created_ms: 1,
+ auth_mode: "none",
+}));
+writeFileSync(
+ "./ext.ts",
+ readFileSync("./ext.template.ts", "utf8").replace("http://127.0.0.1:65535", `http://127.0.0.1:${port}`),
+);
+const { default: AiMemoryExtension } = await import("./ext.ts");
+const handlers: Record<string, any> = {};
+AiMemoryExtension({ on: (name: string, fn: any) => { handlers[name] = fn; } });
+const ctx = { sessionManager: { getSessionId: () => "s-gateway" }, cwd: project };
+handlers["session_start"]({}, ctx);
+const reply = await handlers["before_agent_start"]({ prompt: "continue" }, ctx);
+await handlers["session_shutdown"]({}, ctx);
+// A queue flush starts the spool drain in the background: wait until it has
+// posted the spooled event, then give its answer time to land.
+const drained = () => gatewayBodies.some((body) => body.includes("SPOOLED-WHILE-OFFLINE"));
+for (let i = 0; i < 100 && !drained(); i++) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+}
+await new Promise((resolve) => setTimeout(resolve, 300));
+console.log(JSON.stringify({
+ handoff: reply?.message?.content ?? null,
+ loginHits,
+ drained: drained(),
+ spooled: readdirSync(spool).filter((name) => name.endsWith(".json")).sort(),
+}));
+process.exit(0);
+"#;
+
+ /// Followed, the gateway's redirect would put its login page in the
+ /// agent's context, count it as the delivery of every event (the
+ /// spooled one deleted, this session's never spooled) and replay the
+ /// posts to the login origin. Refused, that origin is never
+ /// contacted, no handoff is injected, and the events wait on disk
+ /// for the real server.
+ #[test]
+ fn omp_extension_refuses_a_gateway_redirect() {
+ if !node_strips_types() {
+ eprintln!("skipping: node lacks --experimental-strip-types");
+ return;
+ }
+ let tmp = TempDir::new().unwrap();
+ let project = tmp.path().join("project");
+ fs::create_dir(&project).unwrap();
+ let run = run_harness(&tmp, extension_under_test(), REDIRECT_HARNESS, &project);
+ assert_eq!(run["loginHits"], serde_json::json!([]), "{run}");
+ assert!(run["handoff"].is_null(), "{run}");
+ assert_eq!(run["drained"], serde_json::json!(true), "{run}");
+ let spooled = run["spooled"].as_array().expect("spool listing");
+ assert!(
+ spooled.contains(&serde_json::json!("0000000000001-1-0000000000000001.json")),
+ "the refused drain must keep the earlier event: {run}"
+ );
+ assert!(
+ spooled.len() > 1,
+ "this session's refused posts must be spooled: {run}"
+ );
+ }
}
#[test]