Skip to content

Commit 03befda

Browse files
authored
fix(slack): reject user-token mention identity
1 parent 5321b35 commit 03befda

58 files changed

Lines changed: 3684 additions & 380 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7778,21 +7778,25 @@ public struct ChatAbortParams: Codable, Sendable {
77787778
public let sessionkey: String
77797779
public let agentid: String?
77807780
public let runid: String?
7781+
public let preservesideruns: Bool?
77817782

77827783
public init(
77837784
sessionkey: String,
77847785
agentid: String? = nil,
7785-
runid: String?)
7786+
runid: String?,
7787+
preservesideruns: Bool? = nil)
77867788
{
77877789
self.sessionkey = sessionkey
77887790
self.agentid = agentid
77897791
self.runid = runid
7792+
self.preservesideruns = preservesideruns
77907793
}
77917794

77927795
private enum CodingKeys: String, CodingKey {
77937796
case sessionkey = "sessionKey"
77947797
case agentid = "agentId"
77957798
case runid = "runId"
7799+
case preservesideruns = "preserveSideRuns"
77967800
}
77977801
}
77987802

‎docs/concepts/queue.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,28 @@ keys.
118118
- Applies to auto-reply agent runs across all inbound channels that use the gateway reply pipeline (WhatsApp web, Telegram, Slack, Discord, Signal, iMessage, webchat, etc.).
119119
- Default lane (`main`) is process-wide for inbound + main heartbeats; set `agents.defaults.maxConcurrent` to allow multiple sessions in parallel.
120120
- Additional lanes may exist (e.g. `cron`, `cron-nested`, `nested`, `subagent`) so background jobs can run in parallel without blocking inbound replies. Isolated cron agent turns hold a `cron` slot while their inner agent execution uses `cron-nested`; both use `cron.maxConcurrentRuns`. Shared non-cron `nested` flows keep their own lane behavior. These detached runs are tracked as [background tasks](/automation/tasks).
121+
122+
## Queued-turn cancellation
123+
124+
When Gateway admits a prompt into the followup/collect queue (for example a TUI
125+
or webchat `chat.send` while another turn is active), it keeps a **Gateway-owned
126+
cancel identity** for that client `runId` until the queued content runs or is
127+
dropped. The identity follows content folded into an overflow summary.
128+
129+
- `chat.abort` with a specific `runId` cancels that turn while it is still queued,
130+
if the requester is authorized (same ownership rules as active runs).
131+
- `chat.abort` for a session without `runId` cancels **authorized queued turns
132+
first**, then aborts authorized active runs. That order prevents queue drain
133+
from promoting work into a half-stopped session.
134+
- Clearing the entire session queue without per-requester checks is not the stop
135+
path for multi-owner sessions.
136+
- Queued waits are not projected as active agent runs for `sessions.list` and do
137+
not own active-run timeout semantics; only the active phase does.
138+
139+
Clients (including the TUI) forward mid-run prompts and let Gateway apply the
140+
queue mode. Esc/`/stop` uses a session-scoped abort so lost local handles cannot
141+
leave a still-queued prompt running.
142+
121143
- Per-session lanes guarantee that only one agent run touches a given session at a time.
122144
- No external dependencies or background worker threads; pure TypeScript + promises.
123145

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2757,6 +2757,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
27572757
- H2: Precedence
27582758
- H2: Per-session overrides
27592759
- H2: Scope and guarantees
2760+
- H2: Queued-turn cancellation
27602761
- H2: Troubleshooting
27612762
- H2: Related
27622763

‎packages/gateway-protocol/src/index.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ describe("lazy protocol validators", () => {
118118
sessionKey: "global",
119119
agentId: "work",
120120
runId: "run-global-work",
121+
preserveSideRuns: true,
121122
}),
122123
).toBe(true);
123124
expect(

‎packages/gateway-protocol/src/schema/logs-chat.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ export const ChatAbortParamsSchema = Type.Object(
107107
sessionKey: NonEmptyString,
108108
agentId: Type.Optional(NonEmptyString),
109109
runId: Type.Optional(NonEmptyString),
110+
preserveSideRuns: Type.Optional(Type.Boolean()),
110111
},
111112
{ additionalProperties: false },
112113
);

‎scripts/protocol-gen-swift.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ const DEFAULTED_OPTIONAL_INIT_PARAM_ENTRIES: readonly [string, readonly string[]
6464
["SessionsUsageParams", ["agentId", "agentScope"]],
6565
["ChatHistoryParams", ["agentId", "offset"]],
6666
["ChatSendParams", ["agentId"]],
67-
["ChatAbortParams", ["agentId"]],
67+
["ChatAbortParams", ["agentId", "preserveSideRuns"]],
6868
["ChatInjectParams", ["agentId"]],
6969
["ChatDeltaEvent", ["agentId"]],
7070
["ChatFinalEvent", ["agentId"]],
@@ -73,7 +73,7 @@ const DEFAULTED_OPTIONAL_INIT_PARAM_ENTRIES: readonly [string, readonly string[]
7373
["ArtifactsListParams", ["agentId"]],
7474
["ArtifactsGetParams", ["agentId"]],
7575
["ArtifactsDownloadParams", ["agentId"]],
76-
["ChatAbortParams", ["agentId"]],
76+
["ChatAbortParams", ["agentId", "preserveSideRuns"]],
7777
["ChatAbortedEvent", ["agentId"]],
7878
["ChatDeltaEvent", ["agentId"]],
7979
["ChatErrorEvent", ["agentId"]],

‎src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,4 +455,133 @@ describe("preemptive-compaction", () => {
455455
expect(result.route).toBe("truncate_tool_results_only");
456456
expect(result.shouldCompact).toBe(false);
457457
});
458+
459+
it("estimates CJK tool results at roughly one token per character", () => {
460+
const cjkText = "中".repeat(85_000);
461+
const toolResultTokens = estimateLlmBoundaryTokenPressure({
462+
messages: [makeToolResultMessage(cjkText)],
463+
systemPrompt: "sys",
464+
prompt: "continue",
465+
});
466+
const assistantTokens = estimateLlmBoundaryTokenPressure({
467+
messages: [makeAssistantHistory(cjkText)],
468+
systemPrompt: "sys",
469+
prompt: "continue",
470+
});
471+
const result = shouldPreemptivelyCompactBeforePrompt({
472+
messages: [makeToolResultMessage(cjkText)],
473+
systemPrompt: "sys",
474+
prompt: "continue",
475+
contextTokenBudget: 128_000,
476+
reserveTokens: 20_000,
477+
});
478+
479+
expect(toolResultTokens).toBeGreaterThanOrEqual(assistantTokens);
480+
expect(toolResultTokens - assistantTokens).toBeLessThanOrEqual(5);
481+
expect(result.estimatedPromptTokens).toBe(toolResultTokens);
482+
expect(result.promptBudgetBeforeReserve).toBeGreaterThan(result.estimatedPromptTokens);
483+
expect(result.route).toBe("fits");
484+
expect(result.shouldCompact).toBe(false);
485+
expect(result.overflowTokens).toBe(0);
486+
});
487+
488+
it("avoids false overflow when CJK is less than half of a tool result", () => {
489+
const mixedContent = "中".repeat(40_000) + "a".repeat(60_000);
490+
const result = shouldPreemptivelyCompactBeforePrompt({
491+
messages: [makeToolResultMessage(mixedContent)],
492+
systemPrompt: "sys",
493+
prompt: "continue",
494+
contextTokenBudget: 100_000,
495+
reserveTokens: 20_000,
496+
});
497+
498+
expect(result.estimatedPromptTokens).toBeLessThan(result.promptBudgetBeforeReserve);
499+
expect(result.route).toBe("fits");
500+
expect(result.shouldCompact).toBe(false);
501+
});
502+
503+
it("keeps mixed-script estimates monotonic across the former CJK cutoff", () => {
504+
const estimate = (cjkChars: number) =>
505+
estimateLlmBoundaryTokenPressure({
506+
messages: [makeToolResultMessage("中".repeat(cjkChars) + "a".repeat(10_000 - cjkChars))],
507+
systemPrompt: "sys",
508+
prompt: "continue",
509+
});
510+
511+
const belowCutoff = estimate(4_999);
512+
const atCutoff = estimate(5_000);
513+
const aboveCutoff = estimate(5_001);
514+
515+
expect(atCutoff).toBeGreaterThanOrEqual(belowCutoff);
516+
expect(aboveCutoff).toBeGreaterThanOrEqual(atCutoff);
517+
expect(aboveCutoff - belowCutoff).toBeLessThanOrEqual(2);
518+
});
519+
520+
it("keeps the conservative ratio for non-CJK tool results", () => {
521+
const latinText = "alpha beta gamma delta epsilon ".repeat(1000);
522+
const toolResultTokens = estimateLlmBoundaryTokenPressure({
523+
messages: [makeToolResultMessage(latinText)],
524+
systemPrompt: "sys",
525+
prompt: "continue",
526+
});
527+
const assistantTokens = estimateLlmBoundaryTokenPressure({
528+
messages: [makeAssistantHistory(latinText)],
529+
systemPrompt: "sys",
530+
prompt: "continue",
531+
});
532+
533+
expect(toolResultTokens).toBeGreaterThan(assistantTokens * 1.5);
534+
expect(toolResultTokens).toBeLessThan(assistantTokens * 2.5);
535+
});
536+
537+
it("applies the CJK-aware ratio to JSON tool-result payloads", () => {
538+
const cjkPayload = {
539+
summary: "中文内容".repeat(5_000),
540+
note: "更多中文文本".repeat(2_000),
541+
};
542+
const messages = [makeJsonToolResultMessage(cjkPayload)];
543+
544+
const estimatedPromptTokens = estimateLlmBoundaryTokenPressure({
545+
messages,
546+
systemPrompt: "sys",
547+
prompt: "continue",
548+
});
549+
550+
expect(estimatedPromptTokens).toBeLessThan(90_000);
551+
552+
const result = shouldPreemptivelyCompactBeforePrompt({
553+
messages,
554+
systemPrompt: "sys",
555+
prompt: "continue",
556+
contextTokenBudget: 128_000,
557+
reserveTokens: 20_000,
558+
});
559+
560+
expect(result.route).toBe("fits");
561+
expect(result.shouldCompact).toBe(false);
562+
expect(result.overflowTokens).toBe(0);
563+
});
564+
565+
it("does not throw when tool-result content cannot be serialized", () => {
566+
const circular: Record<string, unknown> = { self: undefined };
567+
circular.self = circular;
568+
const message = {
569+
role: "toolResult",
570+
toolCallId: "call_circular",
571+
toolName: "bad_tool",
572+
content: circular,
573+
isError: false,
574+
timestamp: timestamp++,
575+
} as unknown as AgentMessage;
576+
577+
const result = shouldPreemptivelyCompactBeforePrompt({
578+
messages: [message],
579+
systemPrompt: "sys",
580+
prompt: "continue",
581+
contextTokenBudget: 128_000,
582+
reserveTokens: 20_000,
583+
});
584+
585+
expect(Number.isFinite(result.estimatedPromptTokens)).toBe(true);
586+
});
458587
});

‎src/agents/embedded-agent-runner/run/preemptive-compaction.ts‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,18 +112,50 @@ function estimateContentBlockTokenPressure(
112112
return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateJsonPayloadTokenPressure(block, charsPerToken);
113113
}
114114

115+
function estimateToolResultStringTokenPressure(text: string): number {
116+
const conservativeToolResultEstimate = Math.ceil(text.length / TOOL_RESULT_CHARS_PER_TOKEN);
117+
const cjkAwareEstimate = estimateStringTokenPressure(text);
118+
return Math.max(conservativeToolResultEstimate, cjkAwareEstimate);
119+
}
120+
121+
function estimateToolResultJsonTokenPressure(value: unknown): number {
122+
try {
123+
const serialized = JSON.stringify(value);
124+
return typeof serialized === "string" ? estimateToolResultStringTokenPressure(serialized) : 1;
125+
} catch {
126+
return 256;
127+
}
128+
}
129+
130+
function estimateToolResultBlockTokenPressure(block: unknown): number {
131+
if (typeof block === "string") {
132+
return estimateToolResultStringTokenPressure(block);
133+
}
134+
if (!isRecord(block)) {
135+
return estimateToolResultJsonTokenPressure(block);
136+
}
137+
138+
if (block.type === "text" && typeof block.text === "string") {
139+
return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateToolResultStringTokenPressure(block.text);
140+
}
141+
if (block.type === "thinking" && typeof block.thinking === "string") {
142+
return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateToolResultStringTokenPressure(block.thinking);
143+
}
144+
if (block.type === "image") {
145+
return IMAGE_BLOCK_TOKENS;
146+
}
147+
return CONTENT_BLOCK_OVERHEAD_TOKENS + estimateToolResultJsonTokenPressure(block);
148+
}
149+
115150
function estimateToolResultContentTokenPressure(content: unknown): number {
116151
if (typeof content === "string") {
117-
return estimateStringTokenPressure(content, TOOL_RESULT_CHARS_PER_TOKEN);
152+
return estimateToolResultStringTokenPressure(content);
118153
}
119154
if (Array.isArray(content)) {
120-
return content.reduce(
121-
(sum, block) => sum + estimateContentBlockTokenPressure(block, TOOL_RESULT_CHARS_PER_TOKEN),
122-
0,
123-
);
155+
return content.reduce((sum, block) => sum + estimateToolResultBlockTokenPressure(block), 0);
124156
}
125157
if (content !== undefined) {
126-
return estimateJsonPayloadTokenPressure(content, TOOL_RESULT_CHARS_PER_TOKEN);
158+
return estimateToolResultJsonTokenPressure(content);
127159
}
128160
return 0;
129161
}

‎src/auto-reply/get-reply-options.types.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,14 @@ export type QueuedReplyDeliveryCorrelation = {
4343

4444
/** Lifecycle hooks for queued follow-up replies. */
4545
export type QueuedReplyLifecycle = {
46-
onEnqueued?: () => void;
46+
/** Stable cancellation owner used to keep collect-mode batches authorization-safe. */
47+
ownerKey?: string;
48+
/** Return false when the external owner rejects this queue identity. */
49+
onEnqueued?: () => boolean | void;
50+
/** Retires this source's cancellation ownership while retaining its live identity. */
51+
onCancellationRetired?: () => void;
52+
/** Called after the queued turn owns the reply lane, before model/tool execution. */
53+
onAdmitted?: () => void;
4754
onComplete?: () => void;
4855
};
4956

‎src/auto-reply/reply/dispatch-from-config.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,48 @@ describe("dispatchReplyFromConfig", () => {
21982198
}
21992199
});
22002200

2201+
it("lets Gateway-owned turns reach queue resolution while a reply operation is active", async () => {
2202+
setNoAbort();
2203+
const sessionKey = "agent:main:main";
2204+
const activeOperation = createReplyOperation({
2205+
sessionKey,
2206+
sessionId: "active-session",
2207+
resetTriggered: false,
2208+
});
2209+
activeOperation.setPhase("running");
2210+
const dispatcher = createDispatcher();
2211+
const replyResolver = vi.fn(async () => undefined);
2212+
2213+
try {
2214+
const result = await dispatchReplyFromConfig({
2215+
ctx: buildTestCtx({
2216+
Provider: "webchat",
2217+
Surface: "webchat",
2218+
SessionKey: sessionKey,
2219+
BodyForAgent: "queue this turn",
2220+
}),
2221+
cfg: emptyConfig,
2222+
dispatcher,
2223+
replyOptions: {
2224+
queuedFollowupLifecycle: {
2225+
onEnqueued: vi.fn(),
2226+
onComplete: vi.fn(),
2227+
},
2228+
},
2229+
replyResolver,
2230+
});
2231+
2232+
expect(result).toMatchObject({
2233+
queuedFinal: false,
2234+
counts: { tool: 0, block: 0, final: 0 },
2235+
});
2236+
expect(replyResolver).toHaveBeenCalledTimes(1);
2237+
expect(replyRunRegistry.get(sessionKey)).toBe(activeOperation);
2238+
} finally {
2239+
activeOperation.complete();
2240+
}
2241+
});
2242+
22012243
it("clears stale active reply operations for terminal sessions and retries admission", async () => {
22022244
setNoAbort();
22032245
const sessionKey = "agent:main:telegram:group:-1003774691294";

0 commit comments

Comments
 (0)