Skip to content

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

fix(dsh-plugin): listen on agent/created for session startup (#5444)

Zayn Jarvisf31678ead87a
diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.md
index 9743d41e6..f5edb860a 100644
--- a/examples/dsh-memory-plugin/README.md
+++ b/examples/dsh-memory-plugin/README.md
@@ -216,7 +216,7 @@ The older size settings apply to fallback recall, not the primary context reques
## Behavior
-- `agent/session-start` injects the OpenViking profile, the available-memory index, and the `<available-skills>` catalog through `agent.inject()`.
+- Agent startup injects the OpenViking profile, the available-memory index, and the `<available-skills>` catalog through `agent.inject()`, and registers the per-session disposal commit. On DSH `0.1.7` and later this runs from the serial `agent/created` event (`{ agent, source, signal? }`), which holds queued input until it settles; DSH `0.1.0-rc.6` and `0.1.5` emit `agent/created` without `source` and start the session through `agent/session-start` instead. Startup runs once per agent, and `agent/pre-step` delivers the profile only if startup did not.
- `agent/pre-step` retrieves with the current step input and appends a durable plugin message to that same step.
- `session/event` captures user, assistant, and optionally tool-result messages without scraping a transcript.
- `turn/end` checks the OpenViking pending-token threshold and commits when required.
diff --git a/examples/dsh-memory-plugin/index.mjs b/examples/dsh-memory-plugin/index.mjs
index de8c0edbc..577facd01 100644
--- a/examples/dsh-memory-plugin/index.mjs
+++ b/examples/dsh-memory-plugin/index.mjs
@@ -34,14 +34,42 @@ export function apply(ctx, input = {}) {
"openvikingMemory.stopDrainer()",
);
- ctx.on("agent/session-start", ({ agent }) => {
- if (skipMemory(agent.session)) return false;
+ // Per-agent startup: register the session's disposal commit, initialize the
+ // OpenViking session, and inject the profile while the agent is still idle.
+ // Runs at most once per agent, whichever DSH event reaches it.
+ const started = new WeakSet();
+ const startAgent = async (agent, signal) => {
+ if (skipMemory(agent.session) || started.has(agent)) return false;
+ started.add(agent);
agent.ctx.effect(
() => () => runtime.dispose(agent.session),
"openvikingMemory.disposeSession()",
);
- return injectStartupProfile(agent, runtime);
+ try {
+ return await injectStartupProfile(agent, runtime, signal);
+ } catch (error) {
+ // A throw from a serial `agent/created` listener fails agent creation;
+ // memory startup must never do that. pre-step retries profile delivery.
+ runtime.log("startup_error", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ };
+
+ // DSH 0.1.7+ has no `agent/session-start`; startup is the serial
+ // `agent/created` event with `{ agent, source, signal? }`, and AgentLoop holds
+ // queued input until its listeners settle. DSH 0.1.0-rc.6 and 0.1.5 still
+ // emit a composition-only `agent/created` with `{ agent }` only, followed by
+ // `agent/session-start`, so a missing `source` leaves startup to that event.
+ // The listener must resolve to undefined: any other value bails the serial
+ // dispatch and skips the listeners registered after this one.
+ ctx.on("agent/created", async ({ agent, source, signal }) => {
+ if (source === undefined) return undefined;
+ await untilAborted(startAgent(agent, signal), signal);
+ return undefined;
});
+ ctx.on("agent/session-start", ({ agent }) => startAgent(agent));
// prepend: downstream waterfall listeners run first, so this plugin sees
// the final claimed batch and appends after every other contributor.
@@ -83,3 +111,18 @@ export function apply(ctx, input = {}) {
mountOpenVikingMcp(ctx, config);
mountOpenVikingSkills(ctx);
}
+
+// Resolve when `promise` settles or `signal` aborts, whichever comes first. An
+// abandoned initialization keeps running and is reused by the pre-step path.
+function untilAborted(promise, signal) {
+ if (!signal) return promise;
+ if (signal.aborted) return Promise.resolve();
+ return new Promise(resolve => {
+ const onAbort = () => resolve();
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.finally(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve();
+ });
+ });
+}
diff --git a/examples/dsh-memory-plugin/index.test.mjs b/examples/dsh-memory-plugin/index.test.mjs
index 43f9e2770..183fbd7ff 100644
--- a/examples/dsh-memory-plugin/index.test.mjs
+++ b/examples/dsh-memory-plugin/index.test.mjs
@@ -35,8 +35,8 @@ test("session filtering skips subagents without changing main-session recall", a
},
},
};
- const sessionStart = handlers.get("agent/session-start");
- assert.equal(typeof sessionStart, "function");
+ const created = handlers.get("agent/created");
+ assert.equal(typeof created, "function");
const preStep = handlers.get("agent/pre-step");
const initial = [message("initial input")];
@@ -77,7 +77,8 @@ test("session filtering skips subagents without changing main-session recall", a
},
},
};
- assert.equal(await sessionStart({ agent: child }), false);
+ assert.equal(await created({ agent: child, source: "startup" }), undefined);
+ assert.equal(await handlers.get("agent/session-start")({ agent: child }), false);
const childMessages = [message("derived worker input")];
const childDecision = await preStep({
agent: child,
@@ -100,6 +101,149 @@ test("session filtering skips subagents without changing main-session recall", a
assert.deepEqual(seen, ["downstream replacement"]);
});
+function mountPlugin() {
+ const handlers = new Map();
+ let runtime;
+ const ctx = {
+ logger: { debug() {} },
+ provide(name, value) {
+ if (name === "openvikingMemory") runtime = value;
+ },
+ effect(execute) {
+ execute();
+ return async () => {};
+ },
+ tools: { register() {} },
+ plugin() {},
+ on(name, handler) {
+ handlers.set(name, handler);
+ },
+ };
+ apply(ctx, { endpoint: "http://127.0.0.1:1933", workspacePeer: false });
+ runtime.stopDrainer();
+ // Replace only the network-bound part; initialize/profileMessage stay real so
+ // the single-flight and delivered-once guarantees are the plugin's own.
+ const calls = { initialize: 0 };
+ runtime.initializeState = async state => {
+ calls.initialize += 1;
+ state.profileBlock = "<openviking-context source=\"profile\">p</openviking-context>";
+ state.ready = true;
+ return state;
+ };
+ return { handlers, runtime, calls };
+}
+
+function startupAgent(id = "dsh-startup") {
+ const agent = {
+ status: "idle",
+ session: { id, header: { cwd: "/workspace" } },
+ injected: [],
+ effects: [],
+ inject(message) {
+ this.injected.push(message);
+ },
+ ctx: {
+ effect(execute, label) {
+ agent.effects.push(label);
+ return async () => {};
+ },
+ },
+ };
+ return agent;
+}
+
+async function withQuietFetch(run) {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async () => response({ rendered: "" });
+ try {
+ return await run();
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+}
+
+test("agent/created (dsh 0.1.7+) runs startup once and pre-step does not re-inject the profile", async () => {
+ const { handlers, calls } = mountPlugin();
+ const agent = startupAgent();
+ await withQuietFetch(async () => {
+ const result = await handlers.get("agent/created")({
+ agent,
+ source: "startup",
+ signal: new AbortController().signal,
+ });
+ // Anything but undefined would bail DSH's serial agent/created dispatch.
+ assert.equal(result, undefined);
+ assert.equal(calls.initialize, 1);
+ assert.equal(agent.injected.length, 1);
+ assert.match(agent.injected[0].content[0].text, /source="profile"/);
+ assert.deepEqual(agent.effects, ["openvikingMemory.disposeSession()"]);
+
+ // A stray session-start on the same agent must not repeat startup.
+ await handlers.get("agent/session-start")({ agent, source: "startup" });
+ const input = [message("first prompt")];
+ const decision = await handlers.get("agent/pre-step")({
+ agent,
+ messages: input,
+ signal: new AbortController().signal,
+ }, async () => ({ kind: "enter", messages: input }));
+
+ assert.equal(calls.initialize, 1);
+ assert.equal(agent.injected.length, 1);
+ assert.deepEqual(agent.effects, ["openvikingMemory.disposeSession()"]);
+ assert.equal(
+ decision.messages.some(m => /source="profile"/.test(m.content?.[0]?.text || "")),
+ false,
+ );
+ });
+});
+
+test("dsh 0.1.x: source-less agent/created defers startup to agent/session-start", async () => {
+ const { handlers, calls } = mountPlugin();
+ const agent = startupAgent("dsh-legacy");
+ await withQuietFetch(async () => {
+ assert.equal(await handlers.get("agent/created")({ agent }), undefined);
+ assert.equal(calls.initialize, 0);
+ assert.deepEqual(agent.effects, []);
+
+ assert.equal(
+ await handlers.get("agent/session-start")({ agent, source: "startup" }),
+ true,
+ );
+ assert.equal(calls.initialize, 1);
+ assert.equal(agent.injected.length, 1);
+ assert.deepEqual(agent.effects, ["openvikingMemory.disposeSession()"]);
+ });
+});
+
+test("agent/created returns on abort and never rejects on startup failure", async () => {
+ const { handlers, runtime } = mountPlugin();
+ let release;
+ runtime.initializeState = () => new Promise(resolve => {
+ release = resolve;
+ });
+ const controller = new AbortController();
+ const agent = startupAgent("dsh-aborted");
+ const pending = handlers.get("agent/created")({
+ agent,
+ source: "startup",
+ signal: controller.signal,
+ });
+ controller.abort();
+ assert.equal(await pending, undefined);
+ release({ ready: false });
+ assert.deepEqual(agent.injected, []);
+
+ runtime.initializeState = async () => {
+ throw new Error("boom");
+ };
+ const failing = startupAgent("dsh-failing");
+ assert.equal(
+ await handlers.get("agent/created")({ agent: failing, source: "startup" }),
+ undefined,
+ );
+ assert.deepEqual(failing.injected, []);
+});
+
function message(text) {
return {
role: "user",
diff --git a/examples/dsh-memory-plugin/lifecycle.mjs b/examples/dsh-memory-plugin/lifecycle.mjs
index c8a69d604..14a9e7082 100644
--- a/examples/dsh-memory-plugin/lifecycle.mjs
+++ b/examples/dsh-memory-plugin/lifecycle.mjs
@@ -1,6 +1,6 @@
-export async function injectStartupProfile(agent, runtime) {
+export async function injectStartupProfile(agent, runtime, signal) {
await runtime.initialize(agent);
- if (agent.status !== "idle") return false;
+ if (signal?.aborted || agent.status !== "idle") return false;
const profile = await runtime.profileMessage(agent);
if (!profile) return false;
agent.inject(profile);