Skip to content

Commit 9e041cd

Browse files
fix(hooks): preserve multi-account agent delivery (#116095)
* fix(hooks): preserve account routing for agent delivery Refs #43866 Co-authored-by: Paul Desmond Parker <[email protected]> * test(gateway): prove hook account delivery handoff --------- Co-authored-by: Paul Desmond Parker <[email protected]>
1 parent 23e151a commit 9e041cd

8 files changed

Lines changed: 211 additions & 8 deletions

File tree

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ Query-string tokens are rejected.
532532
-d '{"message":"Summarize inbox","name":"Email","model":"openai/gpt-5.6-sol"}'
533533
```
534534

535-
Fields: `message` (required), `name`, `agentId`, `sessionKey` (requires `hooks.allowRequestSessionKey=true`), `sessionMode` (`isolated` or `persistent`), `idempotencyKey`, `wakeMode`, `deliver`, `channel`, `to`, `model`, `thinking`, `timeoutSeconds`.
535+
Fields: `message` (required), `name`, `agentId`, `sessionKey` (requires `hooks.allowRequestSessionKey=true`), `sessionMode` (`isolated` or `persistent`), `idempotencyKey`, `wakeMode`, `deliver`, `channel`, `to`, `accountId`, `model`, `thinking`, `timeoutSeconds`.
536536

537537
Set `sessionMode: "persistent"` only when repeated deliveries should reuse prior context. Direct persistent hooks require an explicit `sessionKey`, `hooks.allowRequestSessionKey: true`, and a non-empty `hooks.allowedSessionKeyPrefixes` allowlist. Omit `sessionMode` or use `"isolated"` for a fresh run session.
538538

@@ -543,6 +543,7 @@ Query-string tokens are rejected.
543543
- Announce delivery requires a concrete channel; webhook hooks never inherit the main session's `last` channel or recipient.
544544
- Setting `deliver: false` keeps the run completion-only and ignores any delivery destination.
545545
- Supplying both a concrete `channel` and `to` enables direct announce delivery.
546+
- Set `accountId` with `channel` and `to` to select a configured account on multi-account channels.
546547

547548
The HTTP response waits only for runner admission, not for the agent turn to finish. A `200` may take up to 15 seconds and means the run entered its agent runner. Pre-run failures return `{ ok: false, error, runId }` with:
548549

‎docs/gateway/configuration-reference.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -930,10 +930,11 @@ Validation and safety notes:
930930
**Endpoints:**
931931

932932
- `POST /hooks/wake` → `{ text, mode?: "now"|"next-heartbeat" }`
933-
- `POST /hooks/agent` → `{ message, name?, agentId?, sessionKey?, sessionMode?, wakeMode?, deliver?, channel?, to?, model?, thinking?, timeoutSeconds? }`
933+
- `POST /hooks/agent` → `{ message, name?, agentId?, sessionKey?, sessionMode?, wakeMode?, deliver?, channel?, to?, accountId?, model?, thinking?, timeoutSeconds? }`
934934
- `sessionKey` from request payload is accepted only when `hooks.allowRequestSessionKey=true` (default: `false`).
935935
- `sessionMode` is `"isolated"` by default. `"persistent"` reuses the resolved session and requires an explicit request `sessionKey`, `hooks.allowRequestSessionKey=true`, and non-empty `hooks.allowedSessionKeyPrefixes`.
936936
- Direct announce delivery requires both a concrete `channel` and `to`; supplying only one fails before the run is scheduled.
937+
- `accountId` selects a configured account for direct announce delivery and requires both `channel` and `to`.
937938
- Omit both delivery fields for completion-only hooks, or set `deliver: false` to ignore supplied destination data.
938939
- The request waits up to 15 seconds for runner admission, not run completion. `200` means the agent runner was entered.
939940
- Pre-run failures return `{ ok: false, error, runId }`: `409` for session admission conflicts, `502` for other preparation failures, and `503` when the 15-second admission deadline expires. Timed-out queued work is canceled and will not start later.
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// QA Lab product proof exercises hook delivery through a real Gateway child and qa-channel bus.
2+
import { setTimeout as sleep } from "node:timers/promises";
3+
import { fileURLToPath } from "node:url";
4+
import { describe, expect, it, vi } from "vitest";
5+
import { startQaGatewayChild } from "./gateway-child.js";
6+
import { startQaLabServer } from "./lab-server.js";
7+
import { startQaProviderServer } from "./providers/server-runtime.js";
8+
import { createQaChannelTransport } from "./qa-channel-transport.js";
9+
10+
const HOOK_TOKEN = "qa-hook-account-routing-token";
11+
const MARKER = "QA_HOOK_ACCOUNT_ROUTING_OK";
12+
const MODEL = "mock-openai/gpt-5.6-luna";
13+
14+
async function postJson(url: string, body: unknown, headers: Record<string, string>) {
15+
const response = await fetch(url, {
16+
method: "POST",
17+
headers: {
18+
"Content-Type": "application/json",
19+
...headers,
20+
},
21+
body: JSON.stringify(body),
22+
signal: AbortSignal.timeout(30_000),
23+
});
24+
return {
25+
status: response.status,
26+
json: (await response.json()) as unknown,
27+
};
28+
}
29+
30+
describe("hook agent account routing product proof", () => {
31+
it(
32+
"delivers exactly once through the selected qa-channel account",
33+
{ timeout: 180_000 },
34+
async () => {
35+
const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
36+
const lab = await startQaLabServer({
37+
repoRoot,
38+
embeddedGateway: "disabled",
39+
});
40+
const mock = await startQaProviderServer("mock-openai", {
41+
modelRefs: [MODEL],
42+
});
43+
let gateway: Awaited<ReturnType<typeof startQaGatewayChild>> | undefined;
44+
45+
try {
46+
if (!mock) {
47+
throw new Error("mock-openai provider server did not start");
48+
}
49+
const transport = createQaChannelTransport(lab.state);
50+
gateway = await startQaGatewayChild({
51+
repoRoot,
52+
useRepoCli: true,
53+
providerBaseUrl: `${mock.baseUrl}/v1`,
54+
providerMode: "mock-openai",
55+
primaryModel: MODEL,
56+
alternateModel: MODEL,
57+
transportBaseUrl: lab.listenUrl,
58+
transport,
59+
controlUiEnabled: false,
60+
mutateConfig: (config) => {
61+
const qaChannel = config.channels?.["qa-channel"];
62+
if (!qaChannel) {
63+
throw new Error("qa-channel transport config missing");
64+
}
65+
return {
66+
...config,
67+
hooks: {
68+
enabled: true,
69+
token: HOOK_TOKEN,
70+
path: "/hooks",
71+
},
72+
channels: {
73+
...config.channels,
74+
"qa-channel": {
75+
...qaChannel,
76+
defaultAccount: "default",
77+
accounts: {
78+
default: { name: "Default" },
79+
work: { name: "Work" },
80+
},
81+
},
82+
},
83+
};
84+
},
85+
});
86+
87+
const response = await postJson(
88+
`${gateway.baseUrl}/hooks/agent`,
89+
{
90+
message: `Reply exactly: ${MARKER}`,
91+
deliver: true,
92+
channel: "qa-channel",
93+
to: "dm:hook-recipient",
94+
accountId: "work",
95+
},
96+
{ Authorization: `Bearer ${HOOK_TOKEN}` },
97+
);
98+
expect(response.status, JSON.stringify(response.json)).toBe(200);
99+
100+
const body = response.json as { ok?: boolean; runId?: string };
101+
expect(body.ok).toBe(true);
102+
expect(body.runId).toEqual(expect.any(String));
103+
104+
await vi.waitFor(
105+
() => {
106+
const outbound = lab.state
107+
.getSnapshot()
108+
.messages.filter((message) => message.direction === "outbound");
109+
expect(outbound).toHaveLength(1);
110+
expect(outbound[0]).toMatchObject({
111+
accountId: "work",
112+
conversation: { id: "hook-recipient", kind: "direct" },
113+
text: MARKER,
114+
});
115+
},
116+
{ interval: 50, timeout: 60_000 },
117+
);
118+
await sleep(500);
119+
120+
const outbound = lab.state
121+
.getSnapshot()
122+
.messages.filter((message) => message.direction === "outbound");
123+
expect(outbound).toHaveLength(1);
124+
expect(outbound.filter((message) => message.accountId === "default")).toHaveLength(0);
125+
} finally {
126+
await gateway?.stop().catch(() => undefined);
127+
await mock?.stop().catch(() => undefined);
128+
await lab.stop().catch(() => undefined);
129+
}
130+
},
131+
);
132+
});

‎src/gateway/hooks.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,18 +283,47 @@ describe("gateway hooks helpers", () => {
283283
ok: false,
284284
error: "channel must name a concrete channel for hook delivery",
285285
});
286+
expect(
287+
normalizeAgentPayload({
288+
message: "hello",
289+
accountId: "work",
290+
}),
291+
).toEqual({
292+
ok: false,
293+
error: "accountId requires channel and to for hook delivery",
294+
});
295+
for (const accountId of [123, " "]) {
296+
expect(
297+
normalizeAgentPayload({
298+
message: "hello",
299+
channel: "demo-alias-channel",
300+
to: "123456",
301+
accountId,
302+
}),
303+
).toEqual({
304+
ok: false,
305+
error: "accountId must be a non-empty string for hook delivery",
306+
});
307+
}
286308

287309
const explicit = normalizeAgentPayload({
288310
message: "hello",
289311
channel: "demo-alias-channel",
290312
to: "123456",
313+
accountId: " work ",
291314
});
292315
expect(explicit).toMatchObject({
293316
ok: true,
294317
value: {
295318
channel: "demo-alias-channel",
296319
to: "123456",
297-
delivery: { mode: "announce", channel: "demo-alias-channel", to: "123456" },
320+
accountId: "work",
321+
delivery: {
322+
mode: "announce",
323+
channel: "demo-alias-channel",
324+
to: "123456",
325+
accountId: "work",
326+
},
298327
},
299328
});
300329
});

‎src/gateway/hooks.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,12 +231,14 @@ type HookAgentPayload = {
231231
deliver: boolean;
232232
channel: HookMessageChannel;
233233
to?: string;
234+
accountId?: string;
234235
delivery:
235236
| { mode: "none" }
236237
| {
237238
mode: "announce";
238239
channel: HookMessageChannel;
239240
to?: string;
241+
accountId?: string;
240242
};
241243
model?: string;
242244
thinking?: string;
@@ -280,10 +282,15 @@ export function resolveHookDeliver(raw: unknown): boolean {
280282
}
281283

282284
/** Normalize webhook delivery intent before any isolated cron work is scheduled. */
283-
function normalizeHookAgentDelivery(params: { deliver: unknown; channel: unknown; to: unknown }):
285+
function normalizeHookAgentDelivery(params: {
286+
deliver: unknown;
287+
channel: unknown;
288+
to: unknown;
289+
accountId: unknown;
290+
}):
284291
| {
285292
ok: true;
286-
value: Pick<HookAgentPayload, "deliver" | "channel" | "to" | "delivery">;
293+
value: Pick<HookAgentPayload, "deliver" | "channel" | "to" | "accountId" | "delivery">;
287294
}
288295
| { ok: false; error: string } {
289296
const deliver = resolveHookDeliver(params.deliver);
@@ -294,24 +301,28 @@ function normalizeHookAgentDelivery(params: { deliver: unknown; channel: unknown
294301
deliver,
295302
channel: "last",
296303
to: undefined,
304+
accountId: undefined,
297305
delivery: { mode: "none" },
298306
},
299307
};
300308
}
301309
const to = normalizeOptionalString(params.to);
310+
const accountId = normalizeOptionalString(params.accountId);
302311
const channel = resolveHookChannel(params.channel);
303312
if (!channel) {
304313
return { ok: false, error: getHookChannelError() };
305314
}
306315
const hasChannel = params.channel !== undefined;
307316
const hasTo = params.to !== undefined;
308-
if (!hasChannel && !hasTo) {
317+
const hasAccountId = params.accountId !== undefined;
318+
if (!hasChannel && !hasTo && !hasAccountId) {
309319
return {
310320
ok: true,
311321
value: {
312322
deliver,
313323
channel,
314324
to,
325+
accountId,
315326
delivery: { mode: "none" },
316327
},
317328
};
@@ -322,6 +333,18 @@ function normalizeHookAgentDelivery(params: { deliver: unknown; channel: unknown
322333
error: "to must be a non-empty string for hook delivery",
323334
};
324335
}
336+
if (hasAccountId && !accountId) {
337+
return {
338+
ok: false,
339+
error: "accountId must be a non-empty string for hook delivery",
340+
};
341+
}
342+
if (hasAccountId && (!hasChannel || !to)) {
343+
return {
344+
ok: false,
345+
error: "accountId requires channel and to for hook delivery",
346+
};
347+
}
325348
if (!hasChannel || !to) {
326349
return {
327350
ok: false,
@@ -340,10 +363,12 @@ function normalizeHookAgentDelivery(params: { deliver: unknown; channel: unknown
340363
deliver,
341364
channel,
342365
to,
366+
accountId,
343367
delivery: {
344368
mode: "announce",
345369
channel,
346370
to,
371+
...(accountId ? { accountId } : {}),
347372
},
348373
},
349374
};
@@ -532,6 +557,7 @@ export function normalizeAgentPayload(payload: Record<string, unknown>):
532557
deliver: payload.deliver,
533558
channel: payload.channel,
534559
to: payload.to,
560+
accountId: payload.accountId,
535561
});
536562
if (!delivery.ok) {
537563
return delivery;

‎src/gateway/server-http.hooks-delivery.test.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,22 @@ describe("hook request delivery normalization", () => {
141141
const explicit = await dispatchPayload({
142142
handler,
143143
path: "/hooks/agent",
144-
payload: { message: "Explicit", channel: "delivery-test", to: "123456" },
144+
payload: {
145+
message: "Explicit",
146+
channel: "delivery-test",
147+
to: "123456",
148+
accountId: "work",
149+
},
145150
});
146151
expect(explicit.res.statusCode).toBe(200);
147152
expect(dispatchAgentHook.mock.calls[2]?.[0]).toMatchObject({
148-
delivery: { mode: "announce", channel: "delivery-test", to: "123456" },
153+
accountId: "work",
154+
delivery: {
155+
mode: "announce",
156+
channel: "delivery-test",
157+
to: "123456",
158+
accountId: "work",
159+
},
149160
});
150161
});
151162

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ export function createHooksRequestHandler(
392392
deliver: normalized.value.deliver,
393393
channel: normalized.value.channel,
394394
to: normalized.value.to ?? null,
395+
accountId: normalized.value.accountId ?? null,
395396
model: normalized.value.model ?? null,
396397
thinking: normalized.value.thinking ?? null,
397398
timeoutSeconds: normalized.value.timeoutSeconds ?? null,

‎src/gateway/server/hooks.agent-trust.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ describe("dispatchAgentHook trust handling", () => {
172172
mode: "announce" as const,
173173
channel: "telegram" as const,
174174
to: "123456",
175+
accountId: "work",
175176
};
176177
runCronIsolatedAgentTurnMock.mockResolvedValueOnce({
177178
status: "ok",
@@ -184,6 +185,7 @@ describe("dispatchAgentHook trust handling", () => {
184185
deliver: true,
185186
channel: delivery.channel,
186187
to: delivery.to,
188+
accountId: delivery.accountId,
187189
delivery,
188190
});
189191

0 commit comments

Comments
 (0)