Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions charts/agent-relay/Chart.lock
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ dependencies:
version: 0.1.0
- name: slack-relay
repository: file://../slack-relay
version: 0.3.10
version: 0.3.11
- name: relaygate
repository: file://../relaygate
version: 0.1.9
digest: sha256:b3226269223efd3b118304080a5fe629877c7959c7a762a72d923d33ba75b6a3
generated: "2026-11-16T16:09:07.393594-08:00"
digest: sha256:e6d994526661f32b635fcd811278e8a9cabd8c96ac4efaec114adc068e8cbbbd
generated: "2026-11-16T17:46:13.285579-08:00"
4 changes: 2 additions & 2 deletions charts/agent-relay/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ apiVersion: v2
name: agent-relay
description: Self-hosted Agent Relay messaging and sessions suite
type: application
version: 0.7.49
version: 0.7.50
appVersion: "0.1.0"
kubeVersion: ">=1.28.0-0"
annotations:
Expand Down Expand Up @@ -59,7 +59,7 @@ dependencies:
repository: file://../relay-chief
condition: components.relayChief
- name: slack-relay
version: 0.3.10
version: 0.3.11
repository: file://../slack-relay
condition: components.slackRelay
- name: relaygate
Expand Down
2 changes: 1 addition & 1 deletion charts/slack-relay/Chart.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
apiVersion: v2
name: slack-relay
type: application
version: 0.3.10
version: 0.3.11
appVersion: "0.1.0"
kubeVersion: ">=1.27.0-0"
description: >-
Expand Down
2 changes: 2 additions & 0 deletions charts/slack-relay/templates/router.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ spec:
value: {{ join "," .Values.slack.allowedChannels | quote }}
- name: SLACK_ALLOW_DMS
value: {{ .Values.slack.allowDms | quote }}
- name: SLACK_ACK_REACTION
value: {{ .Values.slack.ackReaction | default "" | quote }}
{{- include "slack-relay.secretEnv" (dict "env" "SLACK_BOT_TOKEN" "ref" .Values.secrets.slackBotToken) | nindent 12 }}
{{- if eq .Values.slack.mode "socket" }}
{{- include "slack-relay.secretEnv" (dict "env" "SLACK_APP_TOKEN" "ref" .Values.secrets.slackAppToken) | nindent 12 }}
Expand Down
4 changes: 4 additions & 0 deletions charts/slack-relay/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ slack:
# Refuse channels shared outside the workspace (Slack Connect), for answers
# and ingest. Unknown sharing state counts as shared.
refuseSharedChannels: true
# Reaction the router adds to each message it routes to an agent, as soon as
# it takes it (before the agent starts). Needs the bot scope reactions:write;
# without it the router logs once and carries on. Empty turns it off.
ackReaction: eyes

# Remote MCP servers behind OAuth client credentials, e.g. a gbrain company
# brain. Agents get the ones listed in host.mcpServers as tools (add
Expand Down
3 changes: 2 additions & 1 deletion components/slack-relay/manifest/slack-app-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"chat:write",
"groups:history",
"groups:read",
"im:history"
"im:history",
"reactions:write"
]
}
},
Expand Down
1 change: 1 addition & 0 deletions components/slack-relay/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ async function runRouter(): Promise<void> {
channel,
selfName: routerName,
log,
ackReaction: env.SLACK_ACK_REACTION ?? "eyes",
// Slack posts don't pass through relaygate, so each one is asked about first.
egress: gate ? (ref, text) => checkWithRetry(gate, routerToken, { op: "w", resource: { kind: "stream", id: slackStreamId(ref) }, content: text }) : undefined,
});
Expand Down
40 changes: 39 additions & 1 deletion components/slack-relay/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// is written to the ledger and never asked again
// 4. deliver post to the relay thread for that Slack thread, addressed to
// the owning agent, with its session and the roster
// 0. ack an :eyes: reaction on the human's message as soon as the
// router takes it, fire-and-forget (never delays routing)
// 5. return an agent's reply in that relay thread goes back to the Slack
// thread the ledger maps it to
//
Expand All @@ -16,7 +18,7 @@ import { sessionIdFor } from "./session-id.ts";
import type { Ledger, ThreadKey } from "./ledger.ts";
import type { Orchestrator } from "./orchestrator.ts";
import { dataOf, replyOf, type InboundData, type RelayEventLike, type RelayMessageLike, type RosterEntry } from "./protocol.ts";
import type { SlackInbound, SlackWebLike } from "./slack.ts";
import { SlackApiError, type SlackInbound, type SlackWebLike } from "./slack.ts";

export interface RouterRelay {
message?(id: string): Promise<RelayMessageLike>;
Expand All @@ -36,6 +38,8 @@ export class Router {
readonly #chains = new Map<string, Promise<unknown>>();
readonly #retryDelaysMs: number[];
readonly #egress: ((ref: { team: string; channel: string; thread_ts: string }, text: string) => Promise<void>) | undefined;
/** Reaction name for step 0; empty when off (or after Slack said the token lacks reactions:write). */
#ackReaction: string;

constructor(opts: {
ledger: Ledger;
Expand All @@ -52,6 +56,8 @@ export class Router {
* rejects to withhold. Absent: posts go straight out.
*/
egress?: (ref: { team: string; channel: string; thread_ts: string }, text: string) => Promise<void>;
/** Reaction added to each message the router takes (default "eyes"); "" turns it off. */
ackReaction?: string;
}) {
this.#ledger = opts.ledger;
this.#relay = opts.relay;
Expand All @@ -62,6 +68,7 @@ export class Router {
this.#log = opts.log ?? (() => {});
this.#retryDelaysMs = opts.retryDelaysMs ?? [500, 2000, 5000];
this.#egress = opts.egress;
this.#ackReaction = (opts.ackReaction ?? "eyes").trim().replace(/^:|:$/g, "");
}

/**
Expand All @@ -74,6 +81,10 @@ export class Router {

/** Steps 1-4 for one Slack message. Serialized per Slack thread. */
fromSlack(m: SlackInbound & { team: string }): Promise<string | null> {
// Every message reaching here is one the router routes (the caller has
// already dropped ignored ones), so acknowledge it now, before it waits
// behind earlier messages in its thread or for the orchestrator.
this.#ack(m.channel, m.ts);
const key: ThreadKey = { team: m.team, channel: m.channel, threadTs: m.threadTs };
const chainKey = `${key.team}/${key.channel}/${key.threadTs}`;
const prior = this.#chains.get(chainKey) ?? Promise.resolve();
Expand Down Expand Up @@ -151,6 +162,33 @@ export class Router {
return relayId;
}

/**
* Step 0: react to the human's message. Fire-and-forget: routing never waits
* on it or fails with it. Only Slack's error code is logged, never the text.
* A token without reactions:write is reported once and not asked again.
*/
#ack(channel: string, ts: string): void {
const name = this.#ackReaction;
if (!name || !this.#slack.addReaction) return;
let pending: Promise<void>;
try {
pending = this.#slack.addReaction({ channel, timestamp: ts, name });
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
} catch (err) {
pending = Promise.reject(err);
}
pending.catch((err: unknown) => {
const code = err instanceof SlackApiError ? err.code : "request_failed";
if (code === "already_reacted") return;
if (code === "missing_scope") {
if (!this.#ackReaction) return;
this.#ackReaction = "";
this.#log(`ack reaction off: the bot token lacks reactions:write (add reactions:write and reinstall the app)`);
return;
}
this.#log(`ack reaction failed for ${channel}:${ts} (${code})`);
});
}

/** Step 5: an agent's reply in a relay thread goes back to its Slack thread. */
async fromRelay(ev: RelayEventLike): Promise<boolean> {
if (ev.type !== "thread.reply" || !ev.parentId) return false;
Expand Down
18 changes: 17 additions & 1 deletion components/slack-relay/src/slack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,18 @@ export class ChannelDirectory {

export interface SlackWebLike {
postMessage(args: { channel: string; text: string; threadTs?: string }): Promise<{ ts?: string }>;
/** reactions.add; rejects with a SlackApiError carrying Slack's error code. */
addReaction?(args: { channel: string; timestamp: string; name: string }): Promise<void>;
}

/** A Web API call Slack answered with ok:false (or a non-2xx status). `code` is Slack's error code only. */
export class SlackApiError extends Error {
readonly code: string;
constructor(method: string, status: number, code: string) {
super(`slack ${method} failed: ${status} ${code}`);
this.name = "SlackApiError";
this.code = code;
}
}

/** Slack form arguments: strings as-is, everything else JSON (Slack's convention for blocks etc.). */
Expand Down Expand Up @@ -180,7 +192,7 @@ export class SlackWeb implements SlackWebLike {
}
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok || json.ok !== true) {
throw new Error(`slack ${method} failed: ${res.status} ${String(json.error ?? "unknown_error")}`);
throw new SlackApiError(method, res.status, String(json.error ?? "unknown_error"));
}
return json;
}
Expand All @@ -201,6 +213,10 @@ export class SlackWeb implements SlackWebLike {
return { ts: typeof r.ts === "string" ? r.ts : undefined };
}

async addReaction(args: { channel: string; timestamp: string; name: string }): Promise<void> {
await this.call("reactions.add", { channel: args.channel, timestamp: args.timestamp, name: args.name });
}

async openSocketUrl(appToken: string): Promise<string> {
const r = await this.call("apps.connections.open", {}, appToken);
if (typeof r.url !== "string") throw new Error("slack apps.connections.open returned no url");
Expand Down
149 changes: 149 additions & 0 deletions components/slack-relay/test/ack.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Step 0 of the router: an :eyes: reaction on each message it takes.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { test } from "node:test";
import { Ledger } from "../src/ledger.ts";
import { DeterministicOrchestrator } from "../src/orchestrator.ts";
import { Router } from "../src/router.ts";
import { normalizeSlackEvent, SlackApiError, SlackWeb, type SlackWebLike } from "../src/slack.ts";

type Reaction = { channel: string; timestamp: string; name: string };

function setup(opts: { addReaction?: SlackWebLike["addReaction"]; ackReaction?: string } = {}) {
const ledger = new Ledger(":memory:");
const reactions: Reaction[] = [];
const logs: string[] = [];
let n = 0;
const slack: SlackWebLike = {
postMessage: async () => ({}),
addReaction: opts.addReaction ?? (async (a) => void reactions.push(a)),
};
const router = new Router({
ledger,
relay: { send: async () => ({ id: `r${++n}` }), reply: async () => ({ id: `r${++n}` }) },
slack,
orchestrator: new DeterministicOrchestrator(),
channel: "slack",
selfName: "router",
log: (m) => logs.push(m),
retryDelaysMs: [1],
...(opts.ackReaction !== undefined ? { ackReaction: opts.ackReaction } : {}),
});
// What the router's Slack handler does: normalize, then route what isn't ignored.
const onEvent = async (event: Record<string, unknown>) => {
const m = normalizeSlackEvent(event, { botUserId: "UBOT", teamId: "T1", isTrackedThread: (ch, ts) => router.isTrackedThread("T1", ch, ts) });
return m ? router.fromSlack({ ...m, team: "T1" }) : null;
};
return { ledger, router, reactions, logs, onEvent };
}

const tick = () => new Promise((r) => setImmediate(r));

test("a routed mention and a reply in its thread each get :eyes:", async () => {
const { reactions, onEvent } = setup();
assert.ok(await onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> help" }));
assert.ok(await onEvent({ type: "message", channel: "C1", ts: "1.2", thread_ts: "1.1", user: "U1", text: "more detail" }));
assert.ok(await onEvent({ type: "message", channel_type: "im", channel: "D1", ts: "2.1", user: "U1", text: "a dm" }));
await tick();
assert.deepEqual(reactions, [
{ channel: "C1", timestamp: "1.1", name: "eyes" },
{ channel: "C1", timestamp: "1.2", name: "eyes" },
{ channel: "D1", timestamp: "2.1", name: "eyes" },
]);
});

test("ignored messages get no reaction", async () => {
const { reactions, onEvent } = setup();
// Plain channel message, reply in a thread the router doesn't hold, bot message, edit.
assert.equal(await onEvent({ type: "message", channel: "C1", ts: "1.1", user: "U1", text: "chatter" }), null);
assert.equal(await onEvent({ type: "message", channel: "C1", ts: "1.3", thread_ts: "1.2", user: "U1", text: "elsewhere" }), null);
assert.equal(await onEvent({ type: "message", channel: "C1", ts: "1.4", user: "U2", bot_id: "B1", text: "bot" }), null);
assert.equal(await onEvent({ type: "message", subtype: "message_changed", channel: "C1", ts: "1.5", user: "U1", text: "edit" }), null);
await tick();
assert.deepEqual(reactions, []);
});

test("ackReaction '' turns the reaction off; a custom name is used as given", async () => {
const off = setup({ ackReaction: "" });
await off.onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> hi" });
await tick();
assert.deepEqual(off.reactions, []);
const custom = setup({ ackReaction: ":robot_face:" });
await custom.onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> hi" });
await tick();
assert.equal(custom.reactions[0]?.name, "robot_face");
});

test("missing_scope is logged once and the router stops trying; routing goes on", async () => {
let calls = 0;
const { onEvent, logs } = setup({
addReaction: async () => {
calls++;
throw new SlackApiError("reactions.add", 200, "missing_scope");
},
});
assert.ok(await onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> one secret" }));
await tick();
assert.ok(await onEvent({ type: "app_mention", channel: "C1", ts: "2.1", user: "U1", text: "<@UBOT> two" }));
await tick();
assert.equal(calls, 1, "not asked again after missing_scope");
const scopeLogs = logs.filter((l) => l.includes("reactions:write"));
assert.equal(scopeLogs.length, 1);
assert.match(scopeLogs[0]!, /add reactions:write and reinstall the app/);
assert.ok(!logs.some((l) => l.includes("secret")), "message text is never logged");
});

test("already_reacted is ignored; other failures log the code only", async () => {
const codes = ["already_reacted", "ratelimited"];
const { onEvent, logs } = setup({
addReaction: async () => {
throw new SlackApiError("reactions.add", 200, codes.shift()!);
},
});
await onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> private words" });
await onEvent({ type: "app_mention", channel: "C1", ts: "2.1", user: "U1", text: "<@UBOT> private words" });
await tick();
const ack = logs.filter((l) => l.startsWith("ack reaction"));
assert.deepEqual(ack, ["ack reaction failed for C1:2.1 (ratelimited)"]);
assert.ok(!logs.some((l) => l.includes("private words")));
});

test("a slow or failing reaction never blocks or fails routing", async () => {
// Never settles.
const slow = setup({ addReaction: () => new Promise<void>(() => {}) });
const routed = await Promise.race([
slow.onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> hi" }),
new Promise((r) => setTimeout(() => r("timeout"), 1000)),
]);
assert.match(String(routed), /^r\d+$/, "routed while the reaction is still pending");
// Throws synchronously, and rejects with a non-Slack error.
const sync = setup({ addReaction: () => { throw new Error("boom"); } });
assert.ok(await sync.onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> hi" }));
const net = setup({ addReaction: async () => { throw new TypeError("fetch failed"); } });
assert.ok(await net.onEvent({ type: "app_mention", channel: "C1", ts: "1.1", user: "U1", text: "<@UBOT> hi" }));
await tick();
assert.deepEqual(net.logs.filter((l) => l.startsWith("ack")), ["ack reaction failed for C1:1.1 (request_failed)"]);
});

test("SlackWeb.addReaction posts reactions.add and surfaces Slack's error code", async () => {
const seen: string[] = [];
const server = createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
seen.push(`${req.url} ${body}`);
const ok = !body.includes("timestamp=2.2");
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(ok ? { ok: true } : { ok: false, error: "missing_scope" }));
});
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
try {
const web = new SlackWeb("xoxb-test", `http://127.0.0.1:${(server.address() as AddressInfo).port}`);
await web.addReaction({ channel: "C1", timestamp: "1.1", name: "eyes" });
assert.deepEqual(seen, ["/reactions.add channel=C1&timestamp=1.1&name=eyes"]);
await assert.rejects(web.addReaction({ channel: "C1", timestamp: "2.2", name: "eyes" }), (err: unknown) => err instanceof SlackApiError && err.code === "missing_scope");
} finally {
server.close();
}
});
Loading
Loading