Skip to content

Commit 8dda07a

Browse files
committed
feat(queue): add queue modes and discord gating
1 parent e9f1851 commit 8dda07a

16 files changed

Lines changed: 378 additions & 12 deletions

‎docs/configuration.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,26 @@ Group messages default to **require mention** (either metadata mention or regex
8585
}
8686
```
8787

88+
### `routing.queue`
89+
90+
Controls how inbound messages behave when an agent run is already active.
91+
92+
```json5
93+
{
94+
routing: {
95+
queue: {
96+
mode: "interrupt", // global default: queue | interrupt | drop
97+
bySurface: {
98+
whatsapp: "interrupt",
99+
telegram: "interrupt",
100+
discord: "queue",
101+
webchat: "queue"
102+
}
103+
}
104+
}
105+
}
106+
```
107+
88108
### `discord` (bot transport)
89109

90110
Configure the Discord bot by setting the bot token and optional gating:
@@ -94,6 +114,10 @@ Configure the Discord bot by setting the bot token and optional gating:
94114
discord: {
95115
token: "your-bot-token",
96116
allowFrom: ["discord:1234567890", "*"], // optional DM allowlist (user ids)
117+
guildAllowFrom: {
118+
guilds: ["123456789012345678"], // optional guild allowlist (ids)
119+
users: ["987654321098765432"] // optional user allowlist (ids)
120+
},
97121
requireMention: true, // require @bot mentions in guilds
98122
mediaMaxMb: 8 // clamp inbound media size
99123
}

‎docs/discord.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Status: ready for DM and guild text channels via the official Discord bot gatewa
2222
5. Direct chats: use `user:<id>` (or a `<@id>` mention) when delivering; all turns land in the shared `main` session.
2323
6. Guild channels: use `channel:<channelId>` for delivery. Mentions are required by default; disable with `discord.requireMention = false`.
2424
7. Optional DM allowlist: reuse `discord.allowFrom` with user ids (`1234567890` or `discord:1234567890`). Use `"*"` to allow all DMs.
25+
8. Optional guild allowlist: set `discord.guildAllowFrom` with `guilds` and/or `users` to gate who can invoke the bot in servers.
2526

2627
Note: Discord does not provide a simple username → id lookup without extra guild context, so prefer ids or `<@id>` mentions for DM delivery targets.
2728

@@ -38,13 +39,18 @@ Note: Discord does not provide a simple username → id lookup without extra gui
3839
discord: {
3940
token: "abc.123",
4041
allowFrom: ["123456789012345678"],
42+
guildAllowFrom: {
43+
guilds: ["123456789012345678"],
44+
users: ["987654321098765432"]
45+
},
4146
requireMention: true,
4247
mediaMaxMb: 8
4348
}
4449
}
4550
```
4651

4752
- `allowFrom`: DM allowlist (user ids). Omit or set to `["*"]` to allow any DM sender.
53+
- `guildAllowFrom`: Optional allowlist for guild messages. Set `guilds` and/or `users` (ids). When both are set, both must match.
4854
- `requireMention`: when `true`, messages in guild channels must mention the bot.
4955
- `mediaMaxMb`: clamp inbound media saved to disk.
5056

‎docs/queue.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,33 @@ We now serialize command-based auto-replies (WhatsApp Web listener) through a ti
1818
- When verbose logging is enabled, queued commands emit a short notice if they waited more than ~2s before starting.
1919
- Typing indicators (`onReplyStart`) still fire immediately on enqueue so user experience is unchanged while we wait our turn.
2020

21+
## Queue modes (per surface)
22+
Inbound messages can either queue or interrupt when a run is already active:
23+
- `queue`: serialize per session; if the agent is streaming, the new message is appended to the current run.
24+
- `interrupt`: abort the active run for that session, then run the newest message.
25+
- `drop`: ignore the message if the session lane is busy.
26+
27+
Defaults (when unset in config):
28+
- WhatsApp + Telegram → `interrupt`
29+
- Discord + WebChat → `queue`
30+
31+
Configure globally or per surface via `routing.queue`:
32+
33+
```json5
34+
{
35+
routing: {
36+
queue: {
37+
mode: "interrupt",
38+
bySurface: { discord: "queue", telegram: "interrupt" }
39+
}
40+
}
41+
}
42+
```
43+
44+
## Per-session overrides
45+
- `/queue <mode>` as a standalone command stores the mode for the current session.
46+
- `/queue <mode>` embedded in a message applies **once** (no persistence).
47+
2148
## Scope and guarantees
2249
- Applies only to config-driven command replies; plain text replies are unaffected.
2350
- Default lane (`main`) is process-wide for inbound + main heartbeats; set `agent.maxConcurrent` to allow multiple sessions in parallel.

‎src/agents/pi-embedded-runner.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ export type EmbeddedPiRunResult = {
8686
type EmbeddedPiQueueHandle = {
8787
queueMessage: (text: string) => Promise<void>;
8888
isStreaming: () => boolean;
89+
abort: () => void;
8990
};
9091

9192
const ACTIVE_EMBEDDED_RUNS = new Map<string, EmbeddedPiQueueHandle>();
@@ -203,6 +204,27 @@ export function queueEmbeddedPiMessage(
203204
return true;
204205
}
205206

207+
export function abortEmbeddedPiRun(sessionId: string): boolean {
208+
const handle = ACTIVE_EMBEDDED_RUNS.get(sessionId);
209+
if (!handle) return false;
210+
handle.abort();
211+
return true;
212+
}
213+
214+
export function isEmbeddedPiRunActive(sessionId: string): boolean {
215+
return ACTIVE_EMBEDDED_RUNS.has(sessionId);
216+
}
217+
218+
export function isEmbeddedPiRunStreaming(sessionId: string): boolean {
219+
const handle = ACTIVE_EMBEDDED_RUNS.get(sessionId);
220+
if (!handle) return false;
221+
return handle.isStreaming();
222+
}
223+
224+
export function resolveEmbeddedSessionLane(key: string) {
225+
return resolveSessionLane(key);
226+
}
227+
206228
function mapThinkingLevel(level?: ThinkLevel): ThinkingLevel {
207229
// pi-agent-core supports "xhigh" too; Clawdis doesn't surface it for now.
208230
if (!level) return "off";
@@ -445,14 +467,19 @@ export async function runEmbeddedPiAgent(params: {
445467
if (prior.length > 0) {
446468
session.agent.replaceMessages(prior);
447469
}
470+
let aborted = Boolean(params.abortSignal?.aborted);
471+
const abortRun = () => {
472+
aborted = true;
473+
void session.abort();
474+
};
448475
const queueHandle: EmbeddedPiQueueHandle = {
449476
queueMessage: async (text: string) => {
450477
await session.queueMessage(text);
451478
},
452479
isStreaming: () => session.isStreaming,
480+
abort: abortRun,
453481
};
454482
ACTIVE_EMBEDDED_RUNS.set(params.sessionId, queueHandle);
455-
let aborted = Boolean(params.abortSignal?.aborted);
456483

457484
const {
458485
assistantTexts,
@@ -473,17 +500,15 @@ export async function runEmbeddedPiAgent(params: {
473500

474501
const abortTimer = setTimeout(
475502
() => {
476-
aborted = true;
477-
void session.abort();
503+
abortRun();
478504
},
479505
Math.max(1, params.timeoutMs),
480506
);
481507

482508
let messagesSnapshot: AppMessage[] = [];
483509
let sessionIdUsed = session.sessionId;
484510
const onAbort = () => {
485-
aborted = true;
486-
void session.abort();
511+
abortRun();
487512
};
488513
if (params.abortSignal) {
489514
if (params.abortSignal.aborted) {

‎src/agents/pi-embedded.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ export type {
44
EmbeddedPiRunResult,
55
} from "./pi-embedded-runner.js";
66
export {
7+
abortEmbeddedPiRun,
8+
isEmbeddedPiRunActive,
9+
isEmbeddedPiRunStreaming,
710
queueEmbeddedPiMessage,
11+
resolveEmbeddedSessionLane,
812
runEmbeddedPiAgent,
913
} from "./pi-embedded-runner.js";

‎src/auto-reply/reply.directive.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66

77
vi.mock("../agents/pi-embedded.js", () => ({
8+
abortEmbeddedPiRun: vi.fn().mockReturnValue(false),
89
runEmbeddedPiAgent: vi.fn(),
910
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
11+
resolveEmbeddedSessionLane: (key: string) =>
12+
`session:${key.trim() || "main"}`,
1013
}));
1114
vi.mock("../agents/model-catalog.js", () => ({
1215
loadModelCatalog: vi.fn(),
@@ -20,6 +23,7 @@ import {
2023
saveSessionStore,
2124
} from "../config/sessions.js";
2225
import {
26+
extractQueueDirective,
2327
extractThinkDirective,
2428
extractVerboseDirective,
2529
getReplyFromConfig,
@@ -83,6 +87,13 @@ describe("directive parsing", () => {
8387
expect(res.thinkLevel).toBe("high");
8488
});
8589

90+
it("matches queue directive", () => {
91+
const res = extractQueueDirective("please /queue interrupt now");
92+
expect(res.hasDirective).toBe(true);
93+
expect(res.queueMode).toBe("interrupt");
94+
expect(res.cleaned).toBe("please now");
95+
});
96+
8697
it("applies inline think and still runs agent content", async () => {
8798
await withTempHome(async (home) => {
8899
vi.mocked(runEmbeddedPiAgent).mockResolvedValue({
@@ -142,6 +153,33 @@ describe("directive parsing", () => {
142153
});
143154
});
144155

156+
it("acks queue directive and persists override", async () => {
157+
await withTempHome(async (home) => {
158+
vi.mocked(runEmbeddedPiAgent).mockReset();
159+
const storePath = path.join(home, "sessions.json");
160+
161+
const res = await getReplyFromConfig(
162+
{ Body: "/queue interrupt", From: "+1222", To: "+1222" },
163+
{},
164+
{
165+
agent: {
166+
model: "anthropic/claude-opus-4-5",
167+
workspace: path.join(home, "clawd"),
168+
},
169+
routing: { allowFrom: ["*"] },
170+
session: { store: storePath },
171+
},
172+
);
173+
174+
const text = Array.isArray(res) ? res[0]?.text : res?.text;
175+
expect(text).toMatch(/^⚙️ Queue mode set to interrupt\./);
176+
const store = loadSessionStore(storePath);
177+
const entry = Object.values(store)[0];
178+
expect(entry?.queueMode).toBe("interrupt");
179+
expect(runEmbeddedPiAgent).not.toHaveBeenCalled();
180+
});
181+
});
182+
145183
it("updates tool verbose during an in-flight run (toggle on)", async () => {
146184
await withTempHome(async (home) => {
147185
const storePath = path.join(home, "sessions.json");

‎src/auto-reply/reply.triggers.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@ import { join } from "node:path";
44
import { afterEach, describe, expect, it, vi } from "vitest";
55

66
vi.mock("../agents/pi-embedded.js", () => ({
7+
abortEmbeddedPiRun: vi.fn().mockReturnValue(false),
78
runEmbeddedPiAgent: vi.fn(),
89
queueEmbeddedPiMessage: vi.fn().mockReturnValue(false),
10+
resolveEmbeddedSessionLane: (key: string) =>
11+
`session:${key.trim() || "main"}`,
912
}));
1013

1114
import { runEmbeddedPiAgent } from "../agents/pi-embedded.js";

0 commit comments

Comments
 (0)