Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Notify shared Slack users when history is rate limited (#1227)

Regan Bellb6f4bf493927
diff --git a/src/api/routes/context.ts b/src/api/routes/context.ts
index 326faae87..6bcb30f0d 100644
--- a/src/api/routes/context.ts
+++ b/src/api/routes/context.ts
@@ -62,6 +62,13 @@ async function resolveSurfaceTarget(
return { source: dest.type, target: { conversationTarget: dest.target } };
}
+async function rateLimitRecipient(ctx: ApiCtx): Promise<Pick<SurfaceContextQuery, "rateLimitRecipient">> {
+ const cap = ctx.capability;
+ if (!cap?.liveActor || cap.destination?.type !== "slack" || !cap.destination.target) return {};
+ const member = await ctx.app.directoryMember(cap.actorId);
+ return { rateLimitRecipient: { target: cap.destination.target, user: member?.slackId ?? cap.actorId } };
+}
+
async function createSurfaceContextRequest(ctx: ApiCtx): Promise<void> {
const { res, app, body, capability } = ctx;
if (!capability) {
@@ -84,6 +91,7 @@ async function createSurfaceContextRequest(ctx: ApiCtx): Promise<void> {
...resolved.target,
viewer: capability.actorId,
count,
+ ...(await rateLimitRecipient(ctx)),
...(before ? { before } : {}),
...(match ? { match } : {}),
};
@@ -112,6 +120,7 @@ async function createSurfaceFileRequest(ctx: ApiCtx): Promise<void> {
const query: SurfaceContextQuery = {
...resolved.target,
count: 1,
+ ...(await rateLimitRecipient(ctx)),
file: { ts, ...(threadTs ? { threadTs } : {}), ...(name ? { name } : {}) },
};
const request = await app.createContextRequest(resolved.source, query);
diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.ts
index 6d2dc92a2..84b63c3b9 100644
--- a/src/core/orchestrator/surface-tools.ts
+++ b/src/core/orchestrator/surface-tools.ts
@@ -94,6 +94,10 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
if (strictReadOnly || !(input.surfaceTools && defaultDestination && deps.deliveries)) return undefined;
const deliveries = deps.deliveries;
const currentDestination = defaultDestination;
+ const rateLimitRecipient =
+ input.origin?.kind === "human" && currentDestination.type === "slack" && currentDestination.target
+ ? { rateLimitRecipient: { target: currentDestination.target, user: actor.id } }
+ : {};
let editRefConsumed = false;
const resolveDestination = async (
target?: {
@@ -295,6 +299,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const result = await deps.surfaceContext.pull(input.surface ?? "unknown", {
conversationTarget: currentDestination.target,
viewer: actor.id,
+ ...rateLimitRecipient,
count,
});
if (!result) return { ok: false, message: "the surface didn't answer in time" };
@@ -308,6 +313,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const result = await deps.surfaceContext.pull(input.surface ?? "unknown", {
conversationTarget: dest.target,
viewer: actor.id,
+ ...rateLimitRecipient,
count: SURFACE_READ_MAX,
});
if (!result) return { ok: false, message: "the surface didn't answer in time" };
@@ -365,6 +371,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const result = await deps.surfaceContext.searchLive(input.surface ?? "unknown", {
conversationTarget: dest.target,
viewer: actor.id,
+ ...rateLimitRecipient,
count: SURFACE_READ_MAX,
searchAll: q,
});
@@ -430,6 +437,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps
const result = await deps.surfaceContext.pull(input.surface ?? "unknown", {
conversationTarget: dest.target,
viewer: actor.id,
+ ...rateLimitRecipient,
count: SURFACE_READ_MAX,
match: q,
});
diff --git a/src/slack/config.ts b/src/slack/config.ts
index 44f439d79..90b97bb44 100644
--- a/src/slack/config.ts
+++ b/src/slack/config.ts
@@ -18,6 +18,7 @@ export function parseSlackContextSource(value: string | undefined): SlackContext
export interface SlackPluginConfig {
contextSource?: SlackContextSource;
installationId?: string;
+ sharedServiceUrl?: string;
receiverFactory?: (staging?: EnvelopeStaging) => Receiver;
botToken: string;
accountId?: string;
@@ -85,6 +86,7 @@ export function slackPluginConfigFromEnv(
...opt("userToken", env.SLACK_USER_TOKEN),
...opt("copilotBotToken", env.SLACK_COPILOT_BOT_TOKEN),
...opt("webUiPublicUrl", env.WEB_UI_PUBLIC_URL),
+ ...opt("sharedServiceUrl", env.QM_SLACK_SERVICE_URL),
...opt("identityEmail", env.SLACK_IDENTITY_EMAIL),
...(() => {
const allowFrom = parseAllowFrom(env.SLACK_ALLOW_FROM);
@@ -143,6 +145,7 @@ export function slackAccountConfigsFromEnv(env: Record<string, string | undefine
SLACK_LOG_LEVEL: env.SLACK_LOG_LEVEL,
SLACK_CONTEXT_SOURCE: env.SLACK_CONTEXT_SOURCE,
WEB_UI_PUBLIC_URL: env.WEB_UI_PUBLIC_URL,
+ QM_SLACK_SERVICE_URL: env.QM_SLACK_SERVICE_URL,
};
const config = slackPluginConfigFromEnv(accountEnv);
if (!config) throw new Error(`SLACK_ACCOUNTS[${i}] ("${id}") is missing required tokens for its events mode`);
diff --git a/src/slack/history-rate-limit.ts b/src/slack/history-rate-limit.ts
index bd4cd9873..4f518dd91 100644
--- a/src/slack/history-rate-limit.ts
+++ b/src/slack/history-rate-limit.ts
@@ -1,15 +1,14 @@
export function slackHistoryRateLimitMessage(
error: unknown,
- opts: { setupUrl?: string; managed?: boolean } = {},
+ opts: { setupUrl?: string; managed?: boolean; format?: "slack" } = {},
): string | undefined {
if (!error || typeof error !== "object") return undefined;
const value = error as { code?: unknown; retryAfter?: unknown; data?: { error?: unknown } };
if (value.code !== "slack_webapi_rate_limited_error" && value.data?.error !== "ratelimited") return undefined;
const seconds = Number(value.retryAfter);
- const retry =
- Number.isFinite(seconds) && seconds > 0 ? ` Retry after ${Math.ceil(seconds)} seconds.` : " Try again shortly.";
- const message = `Slack is temporarily limiting history reads for this workspace. Earlier context may be incomplete.${retry}`;
- if (!opts.managed) return message;
+ const retry = Number.isFinite(seconds) && seconds > 0 ? `in ${Math.ceil(seconds)} seconds` : "shortly";
+ const message = `Slack is temporarily limiting history reads, so I may be missing earlier context. Try again ${retry}`;
+ if (!opts.managed) return opts.format === "slack" ? undefined : `${message}.`;
let setupUrl: string | undefined;
try {
const url = new URL(opts.setupUrl ?? "");
@@ -17,8 +16,10 @@ export function slackHistoryRateLimitMessage(
} catch {
setupUrl = undefined;
}
- const setup = setupUrl
- ? `[set up a workspace-owned Slack app](${setupUrl})`
- : "set up a workspace-owned Slack app in QM's Slack settings";
- return `${message} A workspace admin can ${setup} for this company. Keep using the available context; do not repeatedly retry the history request.`;
+ if (!setupUrl) return opts.format === "slack" ? undefined : `${message}.`;
+ const setup =
+ opts.format === "slack"
+ ? `<${setupUrl.replace(/&/g, "&amp;").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C")}|set up your own Slack app>`
+ : `[set up your own Slack app](${setupUrl})`;
+ return `${message}, or ${setup}.`;
}
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 73cb1ce79..f3af3eec8 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -1,3 +1,4 @@
+import { createSlackRateLimitNotice } from "./rate-limit-notice.ts";
import { createSlackHistoryReader } from "./history.ts";
import { errMessage, swallow, swallowAs } from "../util/errors.ts";
import { createEnvelopeStaging } from "./envelope-staging.ts";
@@ -210,10 +211,29 @@ export async function startSlackPlugin(
});
const mirror = createMirror({ core, ids, directory, externalParticipantsEnabled });
const historyRateLimitOptions = {
- managed: Boolean(cfg.installationId),
+ managed: Boolean(cfg.sharedServiceUrl?.trim()),
...(cfg.webUiPublicUrl ? { setupUrl: `${cfg.webUiPublicUrl.replace(/\/$/, "")}/admin/?setup=slack` } : {}),
};
- const historyClient = new WebClient(BOT_TOKEN, { ...CLIENT_OPTIONS, ...HISTORY_NO_RETRY });
+ const rateLimitNotice = createSlackRateLimitNotice({
+ ...historyRateLimitOptions,
+ client: new WebClient(BOT_TOKEN, { ...CLIENT_OPTIONS, ...HISTORY_NO_RETRY, timeout: 5000 }),
+ });
+ const historyApi = new WebClient(BOT_TOKEN, { ...CLIENT_OPTIONS, ...HISTORY_NO_RETRY });
+ const historyClient = {
+ conversations: Object.fromEntries(
+ (["history", "replies"] as const).map((method) => [
+ method,
+ async (args: any) => {
+ try {
+ return await historyApi.conversations[method](args);
+ } catch (error) {
+ await rateLimitNotice.observe(error);
+ throw error;
+ }
+ },
+ ]),
+ ) as Pick<typeof historyApi.conversations, "history" | "replies">,
+ };
const readHistory = createSlackHistoryReader({
core,
ids,
@@ -273,6 +293,7 @@ export async function startSlackPlugin(
})();
});
const handler = createTurnHandler({
+ rateLimitNotice,
readHistory,
core,
flow,
@@ -329,6 +350,7 @@ export async function startSlackPlugin(
ensureHeader,
});
const surfaceContext = createSurfaceContextFulfiller({
+ rateLimitNotice,
historyClient,
readHistory,
historyRateLimitOptions,
diff --git a/src/slack/rate-limit-notice.ts b/src/slack/rate-limit-notice.ts
new file mode 100644
index 000000000..055423450
--- /dev/null
+++ b/src/slack/rate-limit-notice.ts
@@ -0,0 +1,54 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import { LRUCache } from "lru-cache";
+import { swallow } from "../util/errors.ts";
+import { slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
+import { parseDeliveryTarget } from "./lib.ts";
+
+interface Recipient {
+ target: string;
+ user: string;
+}
+
+export function createSlackRateLimitNotice(opts: { managed?: boolean; setupUrl?: string; client?: any }) {
+ const recentlyNotified = new LRUCache<string, true>({ max: 1000, ttl: 60_000, ttlResolution: 0 });
+ const active = new AsyncLocalStorage<{ client: any; recipient: Recipient; sent: boolean } | undefined>();
+ return {
+ run<T>(client: any, recipient: Recipient | undefined, fn: () => Promise<T>): Promise<T> {
+ return active.run(recipient ? { client, recipient, sent: false } : undefined, fn);
+ },
+ async observe(error: unknown): Promise<void> {
+ const request = active.getStore();
+ if (!request || request.sent || !opts.managed) return;
+ const text = slackHistoryRateLimitMessage(error, { ...opts, format: "slack" });
+ if (!text) return;
+ request.sent = true;
+ try {
+ const client = opts.client ?? request.client;
+ const { channel, threadTs } = parseDeliveryTarget(request.recipient.target);
+ if (!/^[CDG][A-Z0-9]+$/.test(channel)) return;
+ const user = /^[UW][A-Z0-9]+$/.test(request.recipient.user)
+ ? request.recipient.user
+ : (await client.users.lookupByEmail({ email: request.recipient.user })).user?.id;
+ if (!user) return;
+ const key = `${channel}:${user}`;
+ if (recentlyNotified.has(key)) return;
+ recentlyNotified.set(key, true);
+ if (channel.startsWith("D")) {
+ await client.chat.postMessage({
+ channel,
+ text,
+ ...(threadTs ? { thread_ts: threadTs } : {}),
+ unfurl_links: false,
+ unfurl_media: false,
+ });
+ } else {
+ await client.chat.postEphemeral({ channel, user, text });
+ }
+ } catch (error) {
+ swallow("slack: rate-limit notice", error);
+ }
+ },
+ };
+}
+
+export type SlackRateLimitNotice = ReturnType<typeof createSlackRateLimitNotice>;
diff --git a/src/slack/surface-context.ts b/src/slack/surface-context.ts
index bf34c56c9..081c27fe5 100644
--- a/src/slack/surface-context.ts
+++ b/src/slack/surface-context.ts
@@ -1,3 +1,4 @@
+import type { SlackRateLimitNotice } from "./rate-limit-notice.ts";
import { slackHistoryRateLimitMessage } from "./history-rate-limit.ts";
import type { SlackHistoryReader } from "./history.ts";
import { swallow, swallowAs } from "../util/errors.ts";
@@ -24,6 +25,7 @@ import {
} from "./conversation-view.ts";
export function createSurfaceContextFulfiller(deps: {
+ rateLimitNotice?: SlackRateLimitNotice;
core: SlackCoreClient;
directory: Directory;
serializer: ConversationSerializer;
@@ -279,5 +281,12 @@ export function createSurfaceContextFulfiller(deps: {
}
}
- return { fulfillSurfaceContext };
+ return {
+ fulfillSurfaceContext: (client, request) =>
+ deps.rateLimitNotice
+ ? deps.rateLimitNotice.run(client, request.query.rateLimitRecipient, () =>
+ fulfillSurfaceContext(client, request),
+ )
+ : fulfillSurfaceContext(client, request),
+ };
}
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index 62c04fba6..b511035eb 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -1,3 +1,4 @@
+import type { SlackRateLimitNotice } from "./rate-limit-notice.ts";
import type { SlackHistoryReader } from "./history.ts";
import { performance } from "node:perf_hooks";
import { slackFailureText } from "./turn-flow.ts";
@@ -125,6 +126,7 @@ function channelLocation(
}
export function createTurnHandler(deps: {
+ rateLimitNotice?: SlackRateLimitNotice;
core: SlackCoreClient;
flow: TurnFlow;
directory: Directory;
@@ -425,13 +427,23 @@ export function createTurnHandler(deps: {
let detectOpener: string | undefined;
let earlierFiles: SlackFile[] = [];
if (inc.kind === "channel" || (inc.kind === "dm" && inc.threadTs)) {
- const serialized = await serializer.serializeSlackConversation(client, inc, {
- audience,
- ...(channelName ? { channelName } : {}),
- ...(isPrivate !== undefined ? { isPrivate } : {}),
- kind: conversationKind,
- ...(slackIdsByPrincipal ? { slackIdsByPrincipal } : {}),
- });
+ const serialize = () =>
+ serializer.serializeSlackConversation(client, inc, {
+ audience,
+ ...(channelName ? { channelName } : {}),
+ ...(isPrivate !== undefined ? { isPrivate } : {}),
+ kind: conversationKind,
+ ...(slackIdsByPrincipal ? { slackIdsByPrincipal } : {}),
+ });
+ const serialized = deps.rateLimitNotice
+ ? await deps.rateLimitNotice.run(
+ client,
+ !inc.unprompted && !inc.synthetic && !actor.isBot && inc.userId
+ ? { target: encodeDeliveryTarget(inc.channel, replyThreadTs), user: inc.userId }
+ : undefined,
+ serialize,
+ )
+ : await serialize();
earlierFiles = serialized.earlierFiles;
const rendered = renderConversationView(serialized.view);
if (rendered.header) conversationHeader = rendered.header;
diff --git a/src/types.ts b/src/types.ts
index 8543036be..cee88a14b 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -457,6 +457,7 @@ export interface Delivery {
}
export interface SurfaceContextQuery {
+ rateLimitRecipient?: { target: string; user: string };
conversationTarget?: string;
channelId?: string;
channelName?: string;
diff --git a/test/slack-history-rate-limit.test.ts b/test/slack-history-rate-limit.test.ts
index a1f9f4789..44d60ad17 100644
--- a/test/slack-history-rate-limit.test.ts
+++ b/test/slack-history-rate-limit.test.ts
@@ -11,16 +11,16 @@ test("managed history throttling gives retry timing and workspace app setup with
{ code: "slack_webapi_rate_limited_error", retryAfter: 30, message: "private-token" },
{ managed: true, setupUrl: "https://qm.example/admin/?setup=slack" },
);
- assert.match(message!, /Retry after 30 seconds/);
- assert.match(message!, /Earlier context may be incomplete/);
- assert.match(message!, /workspace admin/);
+ assert.match(message!, /Try again in 30 seconds/);
+ assert.match(message!, /I may be missing earlier context/);
+ assert.doesNotMatch(message!, /workspace admin|ask an admin/);
assert.match(message!, /https:\/\/qm.example\/admin\/\?setup=slack/);
assert.doesNotMatch(message!, /private-token/);
});
test("workspace-owned apps receive retry guidance without instructions to replace their app", () => {
const message = slackHistoryRateLimitMessage({ code: "slack_webapi_rate_limited_error", retryAfter: 2.2 });
- assert.match(message!, /Retry after 3 seconds/);
+ assert.match(message!, /Try again in 3 seconds/);
assert.doesNotMatch(message!, /set up|workspace-owned/);
});
@@ -37,7 +37,7 @@ test("malformed delay and unsafe setup URLs use plain guidance", () => {
{ managed: true, setupUrl },
);
assert.match(message!, /Try again shortly/);
- assert.match(message!, /QM's Slack settings/);
+ assert.doesNotMatch(message!, /set up/);
assert.doesNotMatch(message!, /javascript|secret|NaN/);
}
});
@@ -60,7 +60,7 @@ test("Slack history 429 returns immediately instead of sleeping inside the SDK",
});
try {
await assert.rejects(client.conversations.history({ channel: "C1" }), (error: unknown) => {
- assert.match(slackHistoryRateLimitMessage(error)!, /Retry after 60 seconds/);
+ assert.match(slackHistoryRateLimitMessage(error)!, /Try again in 60 seconds/);
return true;
});
assert.equal(calls, 1);
diff --git a/test/slack-rate-limit-notice.test.ts b/test/slack-rate-limit-notice.test.ts
new file mode 100644
index 000000000..b523a76e5
--- /dev/null
+++ b/test/slack-rate-limit-notice.test.ts
@@ -0,0 +1,151 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createSlackRateLimitNotice } from "../src/slack/rate-limit-notice.ts";
+import { slackAccountConfigsFromEnv, slackPluginConfigFromEnv } from "../src/slack/config.ts";
+
+const rateLimit = { code: "slack_webapi_rate_limited_error", retryAfter: 59.1 };
+const setupUrl = "https://qm.example/admin/?setup=slack";
+const options = { managed: true, setupUrl };
+
+function fixture() {
+ const ephemeral: any[] = [];
+ const messages: any[] = [];
+ const client = {
+ chat: {
+ postEphemeral: async (args: any) => {
+ ephemeral.push(args);
+ },
+ postMessage: async (args: any) => {
+ messages.push(args);
+ },
+ },
+ users: {
+ lookupByEmail: async ({ email }: { email: string }) => {
+ assert.equal(email, "[email protected]");
+ return { user: { id: "U2" } };
+ },
+ },
+ };
+ return { client, ephemeral, messages };
+}
+
+test("channel history failures notify requester in channel before a thread exists, once for partial failures", async () => {
+ const { client, ephemeral, messages } = fixture();
+ const notice = createSlackRateLimitNotice(options);
+ await notice.run(client, { target: "C1:1700.1", user: "U1" }, async () => {
+ await Promise.all([notice.observe(rateLimit), notice.observe(rateLimit)]);
+ await notice.observe(rateLimit);
+ });
+ assert.equal(ephemeral.length, 1);
+ assert.deepEqual(ephemeral[0], {
+ channel: "C1",
+ user: "U1",
+ text: "Slack is temporarily limiting history reads, so I may be missing earlier context. Try again in 60 seconds, or <https://qm.example/admin/?setup=slack|set up your own Slack app>.",
+ });
+ assert.equal(messages.length, 0);
+});
+
+test("DM notice is a normal reply and concurrent channel requester stays isolated", async () => {
+ const { client, ephemeral, messages } = fixture();
+ const notice = createSlackRateLimitNotice(options);
+ await Promise.all([
+ notice.run(client, { target: "D1:1700.2", user: "U1" }, () => notice.observe(rateLimit)),
+ notice.run(client, { target: "G1:1700.3", user: "[email protected]" }, () => notice.observe(rateLimit)),
+ ]);
+ assert.equal(messages[0].channel, "D1");
+ assert.equal(messages[0].thread_ts, "1700.2");
+ assert.equal(ephemeral[0].channel, "G1");
+ assert.equal(ephemeral[0].user, "U2");
+ assert.equal(ephemeral[0].thread_ts, undefined);
+});
+
+test("no shared URL, unsafe setup URL, non429 and background requests stay quiet", async () => {
+ const { client, ephemeral, messages } = fixture();
+ for (const opts of [{ setupUrl }, { managed: true }, { managed: true, setupUrl: "http://qm.example" }]) {
+ const notice = createSlackRateLimitNotice(opts);
+ await notice.run(client, { target: "C1", user: "U1" }, () => notice.observe(rateLimit));
+ }
+ const notice = createSlackRateLimitNotice(options);
+ await notice.observe(rateLimit);
+ await notice.run(client, { target: "C1", user: "U1" }, async () => {
+ await notice.observe(new Error("missing_scope"));
+ await notice.run(client, undefined, () => notice.observe(rateLimit));
+ });
+ assert.equal(ephemeral.length + messages.length, 0);
+});
+
+test("notification failure does not replace history failure or retry repeatedly", async () => {
+ const notice = createSlackRateLimitNotice(options);
+ let posts = 0;
+ const client = {
+ chat: {
+ postEphemeral: async () => {
+ posts++;
+ throw rateLimit;
+ },
+ },
+ };
+ await notice.run(client, { target: "C1", user: "U1" }, async () => {
+ await notice.observe(rateLimit);
+ await notice.observe(rateLimit);
+ });
+ assert.equal(posts, 1);
+});
+
+test("shared URL propagates for managed and own-app accounts without installation ID", () => {
+ const env = { SLACK_BOT_TOKEN: "bot", SLACK_APP_TOKEN: "app", QM_SLACK_SERVICE_URL: "https://slack.example" };
+ assert.equal(slackPluginConfigFromEnv(env)?.sharedServiceUrl, env.QM_SLACK_SERVICE_URL);
+ const [account] = slackAccountConfigsFromEnv({
+ ...env,
+ SLACK_ACCOUNTS: JSON.stringify([{ id: "other", botToken: "bot2", appToken: "app2" }]),
+ });
+ assert.equal(account?.sharedServiceUrl, env.QM_SLACK_SERVICE_URL);
+});
+
+test("explicit read tools notify only for human Slack turns, using their original destination", async () => {
+ const { createSurfaceToolDeps } = await import("../src/core/orchestrator/surface-tools.ts");
+ for (const kind of ["human", "ambient", "automation"] as const) {
+ const queries: any[] = [];
+ const tools = createSurfaceToolDeps({
+ deps: {
+ deliveries: {},
+ surfaceContext: {
+ pull: async (_source: string, query: any) => {
+ queries.push(query);
+ return { messages: [] };
+ },
+ },
+ },
+ input: { surface: "slack", surfaceTools: true, origin: { kind }, background: true },
+ actor: { id: "[email protected]" },
+ conversation: { kind: "channel" },
+ defaultDestination: { type: "slack", target: "C1:1700.1" },
+ } as any)!;
+ await tools.readThread();
+ await tools.whatsNew();
+ await tools.search("needle");
+ assert.equal(queries.length, 3);
+ for (const query of queries)
+ assert.deepEqual(
+ query.rateLimitRecipient,
+ kind === "human" ? { target: "C1:1700.1", user: "[email protected]" } : undefined,
+ );
+ }
+});
+
+test("automatic and tool reads share a cooldown after normalizing the requester, without suppressing other people", async (t) => {
+ let now = 1000;
+ t.mock.method(performance, "now", () => now);
+ const { client, ephemeral } = fixture();
+ const notice = createSlackRateLimitNotice(options);
+ await notice.run(client, { target: "C1:1700.1", user: "U2" }, () => notice.observe(rateLimit));
+ await notice.run(client, { target: "C1:1700.1", user: "[email protected]" }, () => notice.observe(rateLimit));
+ await notice.run(client, { target: "C1:1700.2", user: "U2" }, () => notice.observe(rateLimit));
+ assert.equal(ephemeral.length, 1);
+ await notice.run(client, { target: "C1:1700.1", user: "U1" }, () => notice.observe(rateLimit));
+ await notice.run(client, { target: "C2:1700.1", user: "U2" }, () => notice.observe(rateLimit));
+ assert.equal(ephemeral.length, 3);
+ now += 60_001;
+ await notice.run(client, { target: "C1:1700.1", user: "[email protected]" }, () => notice.observe(rateLimit));
+ assert.equal(ephemeral.length, 4);
+});
diff --git a/test/surface-context.test.ts b/test/surface-context.test.ts
index e94c890ca..9f3452ed1 100644
--- a/test/surface-context.test.ts
+++ b/test/surface-context.test.ts
@@ -123,6 +123,25 @@ describe("surface-context pulls", async () => {
assert.deepEqual((pending as any).requests, []);
});
+ it("only live capabilities supply the original requester target, ignoring body overrides", async () => {
+ for (const path of ["/v1/surface-context", "/v1/surface-file"]) {
+ for (const liveActor of [true, false]) {
+ const asking = post(
+ path,
+ {
+ channel: "#eng",
+ ts: "1700.1",
+ rateLimitRecipient: { target: "SECRET", user: "OTHER" },
+ },
+ { "x-agent-capability": await cap({ liveActor }) },
+ );
+ const query = await fulfillNext(() => ({ messages: [] }));
+ assert.deepEqual(query.rateLimitRecipient, liveActor ? { target: "C9:1700.0001", user: "U1" } : undefined);
+ await asking;
+ }
+ }
+ });
+
it("resolves a public channel by name through the directory", async () => {
const asking = post("/v1/surface-context", { channel: "#eng" }, { "x-agent-capability": await cap() });
const query = await fulfillNext(() => ({ messages: [] }));