Skip to content

Commit 43d88a0

Browse files
committed
fix(hooks): route mapped wake events to configured sessions
Fixes #64556
1 parent 3226f07 commit 43d88a0

7 files changed

Lines changed: 221 additions & 35 deletions

File tree

‎src/gateway/hooks-mapping.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,86 @@ describe("hooks mapping", () => {
323323
}
324324
});
325325

326+
it("carries wake agent and session routing from mappings", async () => {
327+
const mappings = resolveHookMappings({
328+
mappings: [
329+
{
330+
id: "targeted-wake",
331+
match: { path: "gmail" },
332+
action: "wake",
333+
textTemplate: "Subject: {{messages[0].subject}}",
334+
agentId: "hooks",
335+
sessionKey: "hook:gmail:{{messages[0].subject}}",
336+
},
337+
],
338+
});
339+
const result = await applyHookMappings(mappings, {
340+
payload: gmailPayload,
341+
headers: {},
342+
url: baseUrl,
343+
path: "gmail",
344+
});
345+
346+
expect(result?.ok).toBe(true);
347+
if (result?.ok && result.action?.kind === "wake") {
348+
expect(result.action).toMatchObject({
349+
agentId: "hooks",
350+
sessionKey: "hook:gmail:Hello",
351+
sessionKeySource: "templated",
352+
});
353+
}
354+
});
355+
356+
it.each(["wake", "agent"] as const)(
357+
"rejects %s session key templates that render empty",
358+
async (action) => {
359+
const mappings = resolveHookMappings({
360+
mappings: [
361+
{
362+
id: `empty-${action}-session-key`,
363+
match: { path: "gmail" },
364+
action,
365+
...(action === "wake"
366+
? { textTemplate: "Subject: {{messages[0].subject}}" }
367+
: { messageTemplate: "Subject: {{messages[0].subject}}" }),
368+
sessionKey: "{{messages[0].missing}}",
369+
},
370+
],
371+
});
372+
const result = await applyHookMappings(mappings, {
373+
payload: gmailPayload,
374+
headers: {},
375+
url: baseUrl,
376+
path: "gmail",
377+
});
378+
379+
expect(result).toEqual({
380+
ok: false,
381+
error: "hook mapping sessionKey template rendered empty",
382+
});
383+
},
384+
);
385+
386+
it("rejects custom wake sessions that cannot be drained on the next heartbeat", async () => {
387+
const result = await applyGmailMappings({
388+
mappings: [
389+
{
390+
id: "deferred-targeted-wake",
391+
match: { path: "gmail" },
392+
action: "wake",
393+
textTemplate: "Subject: {{messages[0].subject}}",
394+
wakeMode: "next-heartbeat",
395+
sessionKey: "hook:gmail:fixed",
396+
},
397+
],
398+
});
399+
400+
expect(result).toEqual({
401+
ok: false,
402+
error: "hook mapping sessionKey requires wakeMode=now",
403+
});
404+
});
405+
326406
it("runs transform module", async () => {
327407
const configDir = makeTempDir(hooksTempDirs, "openclaw-config-");
328408
const transformsRoot = path.join(configDir, "hooks", "transforms");

‎src/gateway/hooks-mapping.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ type HookAction =
5050
kind: "wake";
5151
text: string;
5252
mode: "now" | "next-heartbeat";
53+
agentId?: string;
54+
sessionKey?: string;
55+
sessionKeySource?: "static" | "templated";
5356
}
5457
| {
5558
kind: "agent";
@@ -270,6 +273,9 @@ function buildActionFromMapping(
270273
kind: "wake",
271274
text,
272275
mode: mapping.wakeMode ?? "now",
276+
agentId: mapping.agentId,
277+
sessionKey: renderOptional(mapping.sessionKey, ctx),
278+
sessionKeySource: getSessionKeyTemplateSource(mapping.sessionKey),
273279
},
274280
};
275281
}
@@ -309,7 +315,14 @@ function mergeAction(
309315
const baseWake = base.kind === "wake" ? base : undefined;
310316
const text = typeof override.text === "string" ? override.text : (baseWake?.text ?? "");
311317
const mode = override.mode === "next-heartbeat" ? "next-heartbeat" : (baseWake?.mode ?? "now");
312-
return validateAction({ kind: "wake", text, mode });
318+
return validateAction({
319+
kind: "wake",
320+
text,
321+
mode,
322+
agentId: override.agentId ?? baseWake?.agentId,
323+
sessionKey: override.sessionKey ?? baseWake?.sessionKey,
324+
sessionKeySource: resolveMergedSessionKeySource(baseWake, override),
325+
});
313326
}
314327
const baseAgent = base.kind === "agent" ? base : undefined;
315328
const message =
@@ -339,10 +352,19 @@ function mergeAction(
339352
}
340353

341354
function validateAction(action: HookAction): HookMappingResult {
355+
if (action.sessionKeySource === "templated" && !action.sessionKey?.trim()) {
356+
return { ok: false, error: "hook mapping sessionKey template rendered empty" };
357+
}
342358
if (action.kind === "wake") {
343359
if (!action.text?.trim()) {
344360
return { ok: false, error: "hook mapping requires text" };
345361
}
362+
if (action.mode === "next-heartbeat" && action.sessionKey) {
363+
return {
364+
ok: false,
365+
error: "hook mapping sessionKey requires wakeMode=now",
366+
};
367+
}
346368
return { ok: true, action };
347369
}
348370
if (!action.message?.trim()) {
@@ -365,7 +387,7 @@ function getSessionKeyTemplateSource(
365387
}
366388

367389
function resolveMergedSessionKeySource(
368-
baseAgent: Extract<HookAction, { kind: "agent" }> | undefined,
390+
baseAction: HookAction | undefined,
369391
override: Exclude<HookTransformResult, null>,
370392
): HookSessionKeyTemplateSource | undefined {
371393
if (typeof override.sessionKey === "string") {
@@ -377,7 +399,7 @@ function resolveMergedSessionKeySource(
377399
}
378400
return override.sessionKeySource === "static" ? "static" : "templated";
379401
}
380-
return baseAgent?.sessionKeySource;
402+
return baseAction?.sessionKeySource;
381403
}
382404

383405
export function hasHookTemplateExpressions(template: string): boolean {

‎src/gateway/hooks.test.ts‎

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -568,27 +568,23 @@ describe("gateway hooks helpers", () => {
568568
expect(resolved.sessionPolicy.allowedSessionKeyPrefixes).toBeUndefined();
569569
});
570570

571-
test("resolveHooksConfig ignores templated session keys on wake mappings", () => {
572-
const resolved = resolveHooksConfigOrThrow({
573-
hooks: {
574-
enabled: true,
575-
token: "secret",
576-
mappings: [
577-
{
578-
match: { path: "wake" },
579-
action: "wake",
580-
textTemplate: "ping",
581-
sessionKey: "hook:wake:{{payload.id}}",
582-
},
583-
],
584-
},
585-
} as OpenClawConfig);
586-
587-
expect(resolved.mappings).toHaveLength(1);
588-
expect(resolved.mappings[0]?.action).toBe("wake");
589-
expect(resolved.mappings[0]?.matchPath).toBe("wake");
590-
expect(resolved.mappings[0]?.sessionKey).toBe("hook:wake:{{payload.id}}");
591-
expect(resolved.sessionPolicy.allowedSessionKeyPrefixes).toBeUndefined();
571+
test("resolveHooksConfig applies templated session-key policy to wake mappings", () => {
572+
expect(() =>
573+
resolveHooksConfigOrThrow({
574+
hooks: {
575+
enabled: true,
576+
token: "secret",
577+
mappings: [
578+
{
579+
match: { path: "wake" },
580+
action: "wake",
581+
textTemplate: "ping",
582+
sessionKey: "hook:wake:{{payload.id}}",
583+
},
584+
],
585+
},
586+
} as OpenClawConfig),
587+
).toThrow("hooks.allowedSessionKeyPrefixes is required");
592588
});
593589

594590
test("resolveHooksConfig treats '/' match.path as a catch-all for shadowing", () => {

‎src/gateway/hooks.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ function hasEffectiveTemplatedHookSessionKeyMapping(mappings: HookMappingResolve
464464
continue;
465465
}
466466
effectiveMappings.push(mapping);
467-
if (mapping.action === "agent" && hasTemplatedHookSessionKey(mapping.sessionKey)) {
467+
if (hasTemplatedHookSessionKey(mapping.sessionKey)) {
468468
return true;
469469
}
470470
}

‎src/gateway/server.hooks.test.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -504,14 +504,19 @@ describe("gateway server hooks", () => {
504504
testState.hooksConfig = {
505505
enabled: true,
506506
token: HOOK_TOKEN,
507+
allowedAgentIds: ["hooks"],
508+
allowedSessionKeyPrefixes: ["hook:"],
507509
mappings: [
508510
{
509511
match: { path: "mapped-wake" },
510512
action: "wake",
511513
textTemplate: "Mapped wake: {{payload.subject}}",
514+
agentId: "hooks",
515+
sessionKey: "hook:wake:fixed",
512516
},
513517
],
514518
};
519+
setMainAndHooksAgents();
515520

516521
await withGatewayServer(async ({ port }) => {
517522
const direct = await postHook(port, "/hooks/wake", { text: "Direct wake" });
@@ -524,11 +529,18 @@ describe("gateway server hooks", () => {
524529

525530
const mapped = await postHook(port, "/hooks/mapped-wake", { subject: "Email" });
526531
expect(mapped.status).toBe(200);
527-
await waitForSystemEvent(5_000);
528-
const mappedEvents = peekSystemEventEntries(resolveMainKey());
532+
await waitForSystemEventTexts("agent:hooks:hook:wake:fixed");
533+
const mappedEvents = peekSystemEventEntries("agent:hooks:hook:wake:fixed");
529534
expect(mappedEvents).toHaveLength(1);
530535
expect(mappedEvents[0]?.text).toBe("Mapped wake: Email");
531-
drainSystemEvents(resolveMainKey());
536+
drainSystemEvents("agent:hooks:hook:wake:fixed");
537+
});
538+
539+
testState.sessionConfig = { scope: "global" };
540+
await withGatewayServer(async ({ port }) => {
541+
expect((await postHook(port, "/hooks/mapped-wake", { subject: "Global" })).status).toBe(200);
542+
await waitForSystemEventTexts("global");
543+
expect(peekSystemEvents("global")).toContain("Mapped wake: Global");
532544
});
533545
});
534546

‎src/gateway/server/hooks-request-handler.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,12 @@ export type HookClientIpConfig = Readonly<{
4848
export type HooksRequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
4949

5050
type HookDispatchers = {
51-
dispatchWakeHook: (value: { text: string; mode: "now" | "next-heartbeat" }) => void;
51+
dispatchWakeHook: (value: {
52+
text: string;
53+
mode: "now" | "next-heartbeat";
54+
agentId?: string;
55+
sessionKey?: string;
56+
}) => void;
5257
dispatchAgentHook: (
5358
value: HookAgentDispatchPayload,
5459
) => HookAgentDispatchResult | Promise<HookAgentDispatchResult>;
@@ -437,11 +442,40 @@ export function createHooksRequestHandler(
437442
return true;
438443
}
439444
if (mapped.action.kind === "wake") {
445+
const action = mapped.action;
446+
let targetAgentId: string | undefined;
447+
let dispatchSessionKey: string | undefined;
448+
if (action.agentId || action.sessionKey) {
449+
if (!isHookAgentAllowed(hooksConfig, action.agentId)) {
450+
sendJson(res, 400, { ok: false, error: getHookAgentPolicyError() });
451+
return true;
452+
}
453+
targetAgentId = resolveEffectiveHookTargetAgentId(hooksConfig, action.agentId);
454+
if (action.sessionKey) {
455+
const sessionKey = resolveHookSessionKey({
456+
hooksConfig,
457+
source:
458+
action.sessionKeySource === "static" ? "mapping-static" : "mapping-templated",
459+
sessionKey: action.sessionKey,
460+
});
461+
if (!sessionKey.ok) {
462+
sendJson(res, 400, { ok: false, error: sessionKey.error });
463+
return true;
464+
}
465+
dispatchSessionKey =
466+
resolveDispatchSessionKeyOrRespond(sessionKey.value, targetAgentId) ?? undefined;
467+
if (!dispatchSessionKey) {
468+
return true;
469+
}
470+
}
471+
}
440472
dispatchWakeHook({
441-
text: mapped.action.text,
442-
mode: mapped.action.mode,
473+
text: action.text,
474+
mode: action.mode,
475+
...(targetAgentId ? { agentId: targetAgentId } : {}),
476+
...(dispatchSessionKey ? { sessionKey: dispatchSessionKey } : {}),
443477
});
444-
sendJson(res, 200, { ok: true, mode: mapped.action.mode });
478+
sendJson(res, 200, { ok: true, mode: action.mode });
445479
return true;
446480
}
447481
const action = mapped.action;

‎src/gateway/server/hooks.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { resolveDefaultAgentId } from "../../agents/agent-scope.js";
1010
import type { CliDeps } from "../../cli/deps.types.js";
1111
import { getRuntimeConfig } from "../../config/io.js";
1212
import {
13+
canonicalizeMainSessionAlias,
1314
resolveAgentMainSessionKey,
1415
resolveMainSessionKey,
1516
resolveMainSessionKeyFromConfig,
@@ -25,6 +26,7 @@ import { requestHeartbeat } from "../../infra/heartbeat-wake.js";
2526
import { enqueueSystemEvent } from "../../infra/system-events.js";
2627
import type { createSubsystemLogger } from "../../logging/subsystem.js";
2728
import { runWithGatewayIndependentRootWorkContinuation } from "../../process/gateway-work-admission.js";
29+
import { toAgentStoreSessionKey } from "../../routing/session-key.js";
2830
import type { HookAgentDispatchPayload, HooksConfigResolved } from "../hooks.js";
2931
import {
3032
createHooksRequestHandler,
@@ -174,13 +176,53 @@ export function createGatewayHooksRequestHandler(params: {
174176
const loadIsolatedAgentModule = () =>
175177
(isolatedAgentModulePromise ??= import("../../cron/isolated-agent.js"));
176178

177-
const dispatchWakeHook = (value: { text: string; mode: "now" | "next-heartbeat" }) => {
178-
const sessionKey = resolveMainSessionKeyFromConfig();
179+
const dispatchWakeHook = (value: {
180+
text: string;
181+
mode: "now" | "next-heartbeat";
182+
agentId?: string;
183+
sessionKey?: string;
184+
}) => {
185+
const targeted = Boolean(value.agentId || value.sessionKey);
186+
// A targeted wake must enqueue and wake the same canonical store key;
187+
// otherwise the heartbeat runs for one agent while its event waits elsewhere.
188+
const target = targeted
189+
? (() => {
190+
const cfg = getRuntimeConfig();
191+
const agentId = value.agentId ?? resolveDefaultAgentId(cfg);
192+
if (cfg.session?.scope === "global") {
193+
return {
194+
eventSessionKey: "global",
195+
heartbeatTarget: { agentId },
196+
};
197+
}
198+
const eventSessionKey = canonicalizeMainSessionAlias({
199+
cfg,
200+
agentId,
201+
sessionKey: value.sessionKey
202+
? toAgentStoreSessionKey({
203+
agentId,
204+
requestKey: value.sessionKey,
205+
mainKey: cfg.session?.mainKey,
206+
})
207+
: resolveAgentMainSessionKey({ cfg, agentId }),
208+
});
209+
return {
210+
eventSessionKey,
211+
heartbeatTarget: { agentId, sessionKey: eventSessionKey },
212+
};
213+
})()
214+
: undefined;
215+
const sessionKey = target?.eventSessionKey ?? resolveMainSessionKeyFromConfig();
179216
enqueueSystemEvent(value.text, {
180217
sessionKey,
181218
});
182219
if (value.mode === "now") {
183-
requestHeartbeat({ source: "hook", intent: "immediate", reason: "hook:wake" });
220+
requestHeartbeat({
221+
source: "hook",
222+
intent: "immediate",
223+
reason: "hook:wake",
224+
...target?.heartbeatTarget,
225+
});
184226
}
185227
};
186228

0 commit comments

Comments
 (0)