Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(agent-hook-plugin): keep Cursor, TRAE and ZCode hooks inside their timeouts and fix the doctor's timeout checks (#5467)

t0saki00a668e3eacb
diff --git a/examples/agent-hook-plugin/hosts/cursor.mjs b/examples/agent-hook-plugin/hosts/cursor.mjs
index d21470c67..bcb108910 100644
--- a/examples/agent-hook-plugin/hosts/cursor.mjs
+++ b/examples/agent-hook-plugin/hosts/cursor.mjs
@@ -48,6 +48,13 @@ async function captureTranscript(ctx, state) {
export const cursor = {
prefix: "cu-",
+ requestBudgets: {
+ sessionStart: 25_000,
+ beforeSubmitPrompt: 17_000,
+ stop: 25_000,
+ preCompact: 25_000,
+ sessionEnd: 25_000,
+ },
stages: {
sessionStart: "start",
beforeSubmitPrompt: "prompt",
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index c99090cb2..f552a00a9 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.9",
+ "version": "0.5.10",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
index fe00ca091..4e6313b2b 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.9",
+ "version": "0.5.10",
"description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
index b284b9991..133bb45bd 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.9",
+ "version": "0.5.10",
"clients": [
"kimicode"
],
diff --git a/examples/agent-hook-plugin/hosts/trae.mjs b/examples/agent-hook-plugin/hosts/trae.mjs
index 521e4de7b..98f65dd4c 100644
--- a/examples/agent-hook-plugin/hosts/trae.mjs
+++ b/examples/agent-hook-plugin/hosts/trae.mjs
@@ -11,6 +11,7 @@ export const trae = {
prefix: "tr-",
tracksPendingPrompt: true,
capturesOnlyWhenEnabled: true,
+ requestBudgets: { "session-start": 25_000, "user-prompt-submit": 17_000, stop: 25_000 },
stages: { "session-start": "start", "user-prompt-submit": "prompt", stop: "capture" },
envelope(event, block) {
const value = { decision: "approve" };
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index b9c1ec3eb..0da0dbf7b 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.9",
+ "version": "0.5.10",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode.mjs b/examples/agent-hook-plugin/hosts/zcode.mjs
index 86554d420..9121711fe 100644
--- a/examples/agent-hook-plugin/hosts/zcode.mjs
+++ b/examples/agent-hook-plugin/hosts/zcode.mjs
@@ -17,6 +17,7 @@ export const zcode = {
tracksPendingPrompt: true,
capturesOnlyWhenEnabled: true,
detachesCapture: true,
+ requestBudgets: { "session-start": 25_000, "user-prompt-submit": 17_000, stop: 25_000 },
stages: { "session-start": "start", "user-prompt-submit": "prompt", stop: "capture" },
envelope(event, block) {
if (!block) return null;
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index 1f58e5cc0..cfc6fe342 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.9",
+ "version": "0.5.10",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index eacab0dc7..636e80e04 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agent-hook-plugin",
- "version": "0.5.9",
+ "version": "0.5.10",
"description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode and Kimi Code — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/scripts/hook.mjs b/examples/agent-hook-plugin/scripts/hook.mjs
index baf0a3796..d26a675c2 100644
--- a/examples/agent-hook-plugin/scripts/hook.mjs
+++ b/examples/agent-hook-plugin/scripts/hook.mjs
@@ -28,6 +28,7 @@ import {
import { maybeDetach, readHookStdin } from "../../memory-plugin-shared/lib/async-writer.mjs";
import { isCaptureEnabled } from "../../memory-plugin-shared/lib/capture-utils.mjs";
import { HOSTS } from "../hosts/index.mjs";
+import { withRequestBudget } from "./request-budget.mjs";
// ZCode's detached writer re-enters this file with no arguments at all, so what
// the first run put in the environment is what tells the worker what it is.
@@ -122,26 +123,6 @@ async function promptSubmit(ctx) {
});
}
-function withRequestBudget(fetchJSON, budgetMs) {
- if (!budgetMs) return fetchJSON;
- const deadline = Date.now() + budgetMs;
- return (path, init = {}, options = {}) => {
- const remaining = deadline - Date.now();
- // ov-http deliberately clamps individual requests to one second. Do not
- // start one inside that final second or the host-level total can overrun.
- if (remaining < 1000) {
- return Promise.resolve({
- ok: false,
- status: 0,
- result: null,
- error: { name: "AbortError", aborted: true, message: "hook request budget exhausted" },
- });
- }
- const requested = Number(options.timeoutMs) || remaining;
- return fetchJSON(path, init, { ...options, timeoutMs: Math.min(requested, remaining) });
- };
-}
-
async function capture(ctx) {
if (host.capturesOnlyWhenEnabled && !isCaptureEnabled(ctx.cfg)) return "";
await withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
@@ -180,7 +161,7 @@ async function main() {
input: payload,
nativeSessionId: resolveNativeSessionId(payload),
sessionId: deriveAgentSessionId(host.prefix, payload),
- fetchJSON: withRequestBudget(baseFetchJSON, host.requestBudgets?.[event]),
+ fetchJSON: withRequestBudget(baseFetchJSON, host.requestBudgets?.[event], cfg.timeoutMs),
// The peer the actor-peer header already carries, stamped into captured
// messages because session writes read it from the body only.
get peerId() { return agent.effectivePeer.peerId; },
diff --git a/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs b/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs
index dfa6d2767..150b39ba4 100644
--- a/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs
+++ b/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs
@@ -48,7 +48,10 @@ const REQUIRED_PLUGIN_FILES = ["plugin.json", "scripts/hook.mjs", "scripts/uri-g
* Where each client keeps the two things the installer writes.
*
* ZCode reads both out of one config file; the rest keep hooks and MCP apart,
- * and TRAE's MCP path is the editor's platform-specific user directory.
+ * and TRAE's MCP path is the editor's platform-specific user directory. No
+ * client names timeout budgets: each hook's requests share one deadline its
+ * host adapter sets inside the hook's timeout, so no knob can make one outlive
+ * it.
*/
const CLIENTS = {
cursor: {
@@ -61,7 +64,6 @@ const CLIENTS = {
join(homedir(), ".cursor", "skills", "openviking-memory", "SKILL.md"),
join(homedir(), ".cursor", "skills", "openviking-skills", "SKILL.md"),
],
- timeoutBudgets: { beforeSubmitPrompt: "recallTimeoutMs", stop: "captureTimeoutMs" },
},
trae: {
cliName: "trae",
@@ -70,7 +72,6 @@ const CLIENTS = {
mcp: () => (process.platform === "darwin"
? join(homedir(), "Library", "Application Support", "Trae", "User", "mcp.json")
: join(homedir(), ".trae", "mcp.json")),
- timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
},
"trae-cn": {
cliName: "trae",
@@ -79,14 +80,12 @@ const CLIENTS = {
mcp: () => (process.platform === "darwin"
? join(homedir(), "Library", "Application Support", "Trae CN", "User", "mcp.json")
: join(homedir(), ".trae-cn", "mcp.json")),
- timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
},
zcode: {
cliName: "zcode",
launcherHint: "ZCode",
hooks: () => join(homedir(), ".zcode", "cli", "config.json"),
mcp: () => join(homedir(), ".zcode", "cli", "config.json"),
- timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
},
};
@@ -229,10 +228,8 @@ function checkActivity(report, cfg, connection) {
const HOST = {
harness: CLIENT,
pluginRoot: PLUGIN_ROOT,
- hooksTemplate: join(PLUGIN_ROOT, "hosts", HOST_DIR, "hooks.json"),
cliName: SPEC.cliName,
launcherHint: SPEC.launcherHint,
- timeoutBudgets: SPEC.timeoutBudgets,
loadConfig: () => loadAgentHookConfig(CLIENT),
checkInstall,
checkConfig,
diff --git a/examples/agent-hook-plugin/scripts/request-budget.mjs b/examples/agent-hook-plugin/scripts/request-budget.mjs
new file mode 100644
index 000000000..9455fed92
--- /dev/null
+++ b/examples/agent-hook-plugin/scripts/request-budget.mjs
@@ -0,0 +1,28 @@
+/**
+ * One deadline for every request a hook sends.
+ *
+ * A hook's requests run one after another — recall falls back through three
+ * endpoints, capture sends then commits — so per-request timeouts alone add up
+ * past the timeout the host gives the hook, and the host kills it mid-write.
+ * Each request still gets its own timeout, or `defaultTimeoutMs`, but never
+ * more than what is left of `budgetMs`.
+ */
+export function withRequestBudget(fetchJSON, budgetMs, defaultTimeoutMs = 0) {
+ if (!budgetMs) return fetchJSON;
+ const deadline = Date.now() + budgetMs;
+ return (path, init = {}, options = {}) => {
+ const remaining = deadline - Date.now();
+ // ov-http deliberately clamps individual requests to one second. Do not
+ // start one inside that final second or the host-level total can overrun.
+ if (remaining < 1000) {
+ return Promise.resolve({
+ ok: false,
+ status: 0,
+ result: null,
+ error: { name: "AbortError", aborted: true, message: "hook request budget exhausted" },
+ });
+ }
+ const requested = Number(options.timeoutMs) || Number(defaultTimeoutMs) || remaining;
+ return fetchJSON(path, init, { ...options, timeoutMs: Math.min(requested, remaining) });
+ };
+}
diff --git a/examples/agent-hook-plugin/tests/request-budget.test.mjs b/examples/agent-hook-plugin/tests/request-budget.test.mjs
new file mode 100644
index 000000000..424bde0fa
--- /dev/null
+++ b/examples/agent-hook-plugin/tests/request-budget.test.mjs
@@ -0,0 +1,112 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import {
+ loadAgentHookConfig,
+ makeAgentFetchJSON,
+ recallForPrompt,
+} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { HOSTS } from "../hosts/index.mjs";
+import { withRequestBudget } from "../scripts/request-budget.mjs";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
+const dir = mkdtempSync(join(tmpdir(), "ov-request-budget-"));
+process.on("exit", () => rmSync(dir, { recursive: true, force: true }));
+process.env.OPENVIKING_STATE_DIR = join(dir, "state");
+process.env.OPENVIKING_PENDING_DIR = join(dir, "pending");
+process.env.OPENVIKING_HOME = join(dir, "home");
+
+/** A server that takes every connection and never answers. */
+async function silentServer(t) {
+ const requests = [];
+ const sockets = new Set();
+ const server = createServer((socket) => {
+ sockets.add(socket);
+ socket.once("data", (chunk) => requests.push(String(chunk).split(" ").slice(0, 2).join(" ")));
+ socket.on("error", () => {});
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => {
+ for (const socket of sockets) socket.destroy();
+ server.close();
+ });
+ return { port: server.address().port, requests };
+}
+
+function config(port, env = {}) {
+ return loadAgentHookConfig("cursor", dir, {
+ env: {
+ OPENVIKING_URL: `http://127.0.0.1:${port}`,
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "missing-ovcli.conf"),
+ OPENVIKING_CONFIG_FILE: join(dir, "missing-ov.conf"),
+ OPENVIKING_TIMEOUT_MS: "1000",
+ ...env,
+ },
+ });
+}
+
+test("every hook.mjs event has a request budget inside the timeout its hooks.json gives it", () => {
+ for (const [client, hostDir] of [["cursor", "cursor"], ["trae", "trae"], ["trae-cn", "trae"], ["zcode", "zcode"]]) {
+ const { hooks } = JSON.parse(readFileSync(join(ROOT, "hosts", hostDir, "hooks.json"), "utf8"));
+ const events = [];
+ for (const entry of Object.values(hooks).flat()) {
+ for (const leaf of entry.hooks || [entry]) {
+ const event = /scripts\/hook\.mjs (\S+) /u.exec(leaf.command)?.[1];
+ if (!event) continue;
+ events.push(event);
+ const budget = HOSTS[client].requestBudgets?.[event];
+ // The seconds left over cover node start-up, the session lock and the state write.
+ assert.ok(budget > 0 && budget <= leaf.timeout * 1000 - 3000,
+ `${client} ${event}: request budget ${budget}ms, hook timeout ${leaf.timeout}s`);
+ }
+ }
+ assert.ok(events.length >= 3, `${client}: found only ${events.join(", ")}`);
+ }
+});
+
+test("recall stops falling back once the prompt budget is spent", async (t) => {
+ const server = await silentServer(t);
+ const cfg = config(server.port, { OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS: "1000" });
+ const { fetchJSON } = makeAgentFetchJSON(cfg, dir);
+ const started = Date.now();
+ // Unbounded, this chain is six rounds of one timeout each.
+ const block = await recallForPrompt(withRequestBudget(fetchJSON, 2500, cfg.timeoutMs), cfg,
+ "how do we deploy the service", dir, () => {}, { sessionId: "cu-budget" });
+ const elapsed = Date.now() - started;
+ assert.equal(block, null);
+ assert.ok(elapsed < 2500, `recall took ${elapsed}ms`);
+ assert.deepEqual(server.requests, ["POST /api/v1/search/search", "POST /api/v1/search/recall"]);
+});
+
+test("a capture keeps each request to the request timeout and queues what the stop budget cannot fit", async (t) => {
+ const server = await silentServer(t);
+ const cfg = config(server.port);
+ const transcript = join(dir, "transcript.jsonl");
+ writeFileSync(transcript, [
+ JSON.stringify({ role: "user", message: { content: [{ type: "text", text: "question" }] } }),
+ JSON.stringify({ role: "assistant", message: { content: [{ type: "text", text: "answer" }] } }),
+ ].join("\n"));
+ const { fetchJSON } = makeAgentFetchJSON(cfg, dir);
+ const ctx = {
+ cfg,
+ input: { transcript_path: transcript },
+ sessionId: "cu-budget",
+ fetchJSON: withRequestBudget(fetchJSON, 1500, cfg.timeoutMs),
+ peerId: "",
+ log: () => {},
+ };
+ const started = Date.now();
+ await HOSTS.cursor.capture(ctx, {}, "preCompact");
+ const elapsed = Date.now() - started;
+ assert.ok(elapsed < 1500, `capture took ${elapsed}ms`);
+ assert.deepEqual(server.requests, ["POST /api/v1/sessions/cu-budget/messages/batch"]);
+ const queued = readdirSync(process.env.OPENVIKING_PENDING_DIR)
+ .map((name) => JSON.parse(readFileSync(join(process.env.OPENVIKING_PENDING_DIR, name), "utf8")).type)
+ .sort();
+ assert.deepEqual(queued, ["addMessage", "addMessage", "commitSession"]);
+});
diff --git a/examples/memory-plugin-shared/doctor-core.test.mjs b/examples/memory-plugin-shared/doctor-core.test.mjs
index ce68ddf59..4dabd600d 100644
--- a/examples/memory-plugin-shared/doctor-core.test.mjs
+++ b/examples/memory-plugin-shared/doctor-core.test.mjs
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
-import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
@@ -310,6 +311,35 @@ test("no doctor wrapper redefines a name doctor-core already exports", () => {
}
});
+// The hooks bound their own requests (agent-hook-plugin/tests/request-budget),
+// so no timeout setting is a hook overrun the doctor should report.
+test("the hook hosts' doctor reports no hook-budget overrun at any request timeout", () => {
+ const home = mkdtempSync(join(tmpdir(), "ov-doctor-hosts-"));
+ const doctor = fileURLToPath(new URL("../agent-hook-plugin/scripts/ov-memory-doctor.mjs", import.meta.url));
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("OPENVIKING_")));
+ const budgetWarnings = (client, extra = {}) => {
+ const run = spawnSync(process.execPath, [doctor, client, "--offline", "--json"], {
+ cwd: home,
+ // Only node on PATH, so the doctor's `<client> --version` probe never
+ // starts a host editor installed on the machine running the suite.
+ env: { ...env, ...extra, HOME: home, PATH: dirname(process.execPath) },
+ encoding: "utf8",
+ });
+ const config = JSON.parse(run.stdout).sections.find((section) => section.title === "Configuration");
+ return config.findings
+ .filter((finding) => finding.level === "warn" && finding.title.includes("hook budget"))
+ .map((finding) => `${finding.title} → ${finding.fix}`);
+ };
+ try {
+ for (const client of ["cursor", "trae", "trae-cn", "zcode"]) {
+ assert.deepEqual(budgetWarnings(client), [], client);
+ assert.deepEqual(budgetWarnings(client, { OPENVIKING_TIMEOUT_MS: "35000" }), [], client);
+ }
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+});
+
const CLI_PATH = "/nowhere/.openviking/ovcli.conf";
const OV_PATH = "/nowhere/.openviking/ov.conf";
const cliConf = (data) => ({ ok: true, path: CLI_PATH, data });