Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Hand off Slack work to other people by plain DM through a skill (#2167)

Joshua Francefc54a60b551d
diff --git a/deploy/egress-proxy/envoy.yaml b/deploy/egress-proxy/envoy.yaml
index 1e2ca2b37..b67d37acd 100644
--- a/deploy/egress-proxy/envoy.yaml
+++ b/deploy/egress-proxy/envoy.yaml
@@ -101,6 +101,10 @@ static_resources:
local h, _ = handle:httpCall("egress_authz", check, nil, 10000)
return h[":status"], h["x-egress-upstream-address"]
end)
+ if ok and status == "407" then
+ handle:respond({ [":status"] = "407", ["proxy-authenticate"] = "Basic realm=\"egress\"" }, "proxy authentication required\n")
+ return
+ end
if not ok or status ~= "200" then
handle:respond({ [":status"] = "403" }, "egress denied by policy\n")
return
diff --git a/plugins/web-ui/src/slack-text.ts b/plugins/web-ui/src/slack-text.ts
index 1d9eaee00..cfd6aef7b 100644
--- a/plugins/web-ui/src/slack-text.ts
+++ b/plugins/web-ui/src/slack-text.ts
@@ -68,23 +68,7 @@ export function slackWireToPlain(text: string): string {
const REACTION_DIRECTIVE = /\[\[react:[^\]]*\]\]/gi;
const TRAILING_OPEN_REACTION = /\[\[react:[^\]]*$/i;
-const AGENT_REQUEST_DIRECTIVE = /\[\[ask-agent:[^|\]]{0,400}\|[\s\S]*?\]\]/gi;
-const AGENT_REQUEST_OPENER = /\[\[ask-agent:/gi;
-
-function stripLeftoverAgentRequests(text: string): string {
- let out = "";
- let cursor = 0;
- AGENT_REQUEST_OPENER.lastIndex = 0;
- for (let m = AGENT_REQUEST_OPENER.exec(text); m; m = AGENT_REQUEST_OPENER.exec(text)) {
- out += text.slice(cursor, m.index);
- const close = text.indexOf("]]", m.index + m[0].length);
- if (close < 0) return out;
- cursor = close + 2;
- AGENT_REQUEST_OPENER.lastIndex = cursor;
- }
- return out + text.slice(cursor);
-}
-const ANY_DIRECTIVE = /\[\[(?:react|ask-agent):/i;
+const ANY_DIRECTIVE = /\[\[react:/i;
const CODE_REGION = /```[\s\S]*?```|`[^`\n]*`/g;
const CODE_PLACEHOLDER = /\u0000CODE(\d+)\u0000/g;
@@ -92,9 +76,7 @@ export function stripSlackDirectives(text: string): string {
if (!text || !ANY_DIRECTIVE.test(text)) return text;
const code: string[] = [];
const masked = text.replace(CODE_REGION, (m) => `\u0000CODE${code.push(m) - 1}\u0000`);
- const stripped = stripLeftoverAgentRequests(
- masked.replace(REACTION_DIRECTIVE, "").replace(TRAILING_OPEN_REACTION, "").replace(AGENT_REQUEST_DIRECTIVE, ""),
- );
+ const stripped = masked.replace(REACTION_DIRECTIVE, "").replace(TRAILING_OPEN_REACTION, "");
if (stripped === masked) return text;
return stripped
.replace(CODE_PLACEHOLDER, (_m, i: string) => code[Number(i)] ?? "")
diff --git a/plugins/web-ui/test/slack-text.test.ts b/plugins/web-ui/test/slack-text.test.ts
index 4c927918f..18c081d6a 100644
--- a/plugins/web-ui/test/slack-text.test.ts
+++ b/plugins/web-ui/test/slack-text.test.ts
@@ -90,9 +90,9 @@ test("slackWireToPlain flattens tokens for copy and search", () => {
assert.equal(slackWireToPlain("hi <@U9|alice> see <https://x|doc> and <#C1|eng>"), "hi @alice see doc and #eng");
});
-test("reaction and ask-agent directives are stripped, whitespace tidied", () => {
+test("reaction directives are stripped, whitespace tidied", () => {
assert.equal(stripSlackDirectives("thanks! [[react: tada eyes]]"), "thanks!");
- assert.equal(stripSlackDirectives("done [[ask-agent: <@U9> | file the report]]\n\n\nnext"), "done\n\nnext");
+ assert.equal(stripSlackDirectives("done [[react: eyes]]\n\n\nnext"), "done\n\nnext");
});
test("a trailing unclosed directive is cut, matching the Slack plugin", () => {
@@ -101,7 +101,7 @@ test("a trailing unclosed directive is cut, matching the Slack plugin", () => {
test("directives quoted in code stay visible", () => {
assert.equal(stripSlackDirectives("use `[[react: eyes]]` to react"), "use `[[react: eyes]]` to react");
- const fenced = "```\n[[ask-agent: <@U9> | x]]\n```";
+ const fenced = "```\n[[react: eyes]]\n```";
assert.equal(stripSlackDirectives(fenced), fenced);
});
@@ -110,15 +110,9 @@ test("text without directives is returned as-is", () => {
assert.equal(stripSlackDirectives(text), text);
});
-test("the bounded ask-agent grammar resists catastrophic backtracking", () => {
+test("the directive grammar resists catastrophic backtracking", () => {
const pad = " ".repeat(100000);
- for (const input of [
- "[[ask-agent:" + pad,
- "[[ask-agent: <@U9> |" + pad,
- "thanks [[react:" + pad + "]x",
- "[[react: eyes]] tail" + pad + "no newline",
- "[[ask-agent: <@U9> | do it ]] tail" + pad + "x",
- ]) {
+ for (const input of ["thanks [[react:" + pad + "]x", "[[react: eyes]] tail" + pad + "no newline"]) {
const start = process.hrtime.bigint();
stripSlackDirectives(input);
const ms = Number(process.hrtime.bigint() - start) / 1e6;
@@ -128,23 +122,10 @@ test("the bounded ask-agent grammar resists catastrophic backtracking", () => {
test("the local grammar mirrors the Slack plugin, ReDoS-hardened in lockstep with core", () => {
const reactions = readFileSync(new URL("../../../src/slack/reactions.ts", import.meta.url), "utf8");
- const requests = readFileSync(new URL("../../../src/slack/agent-requests.ts", import.meta.url), "utf8");
const directives = readFileSync(new URL("../../../src/slack/directives.ts", import.meta.url), "utf8");
const local = readFileSync(new URL("../src/slack-text.ts", import.meta.url), "utf8");
assert.ok(reactions.includes("/\\[\\[react:([^\\]]*)\\]\\]/gi"));
assert.ok(local.includes("/\\[\\[react:[^\\]]*\\]\\]/gi"));
- assert.ok(requests.includes("/\\[\\[ask-agent:([^|\\]]{0,400})\\|([\\s\\S]*?)\\]\\]/gi"));
- assert.ok(local.includes("/\\[\\[ask-agent:[^|\\]]{0,400}\\|[\\s\\S]*?\\]\\]/gi"));
- const leftover = /function stripLeftoverAgentRequests\(text: string\): string \{[\s\S]*?\n\}/;
- const serverBody = requests.match(leftover)?.[0];
- assert.ok(
- serverBody && local.match(leftover)?.[0] === serverBody,
- "the positional leftover strip is byte-identical on both sides",
- );
- assert.ok(
- requests.includes("/\\[\\[ask-agent:/gi") && local.includes("/\\[\\[ask-agent:/gi"),
- "the opener regex keeps both flags on both sides",
- );
assert.ok(
!directives.includes("[ \\t]+\\n") && !local.includes("[ \\t]+\\n"),
"the tidy step is linear on both sides",
@@ -161,23 +142,6 @@ test("the local entity decode matches core's decodeSlackEntities", () => {
assert.ok(local.includes(decode));
});
-test("a closed directive with a newline or a long id is stripped whole, never truncating the reply", () => {
- assert.match(stripSlackDirectives("hi [[ask-agent:\n<@U2> | task]] tail text"), /^hi\s+tail text$/);
- const longId = "<@U2>" + " ".repeat(500);
- assert.match(
- stripSlackDirectives(`hi [[ask-agent:${longId}| task]] tail text`),
- /^hi\s+tail text$/,
- "an id past the bound is stripped without eating the rest of the reply",
- );
- assert.match(
- stripSlackDirectives("I'll ask [[ask-agent: <@U2> no pipe here]] and also [[ask-agent: <@U3> | real]] done"),
- /^I'll ask\s+and also\s+done$/,
- "a malformed closed directive never leaks its syntax",
- );
- assert.equal(stripSlackDirectives("[[ask-agent: <@U2> | x]] then [docs](y)]] fine"), "then [docs](y)]] fine");
- assert.equal(stripSlackDirectives("hi [[ask-agent: <@U2> | unterminated"), "hi");
-});
-
test("a labeled user mention never doubles its at-sign", () => {
assert.deepEqual(splitSlackWire("<@U1|@ada>"), [{ kind: "mention", handle: "ada" }]);
assert.deepEqual(splitSlackWire("<@U1|@@ada>"), [{ kind: "mention", handle: "ada" }]);
@@ -189,16 +153,3 @@ test("a literally typed, escaped mention stays text even where plain @names are
{ kind: "mention", handle: "ada" },
]);
});
-
-test("the leftover strip finds openers case-insensitively without shifting indices on non-ASCII text", () => {
- const turkish = "İstanbul plan: İİİ ok [[ask-agent: <@U2> | never closed";
- assert.equal(stripSlackDirectives(turkish), "İstanbul plan: İİİ ok");
- assert.match(stripSlackDirectives("x [[ASK-AGENT: <@U2> no pipe]] y"), /^x\s+y$/);
-});
-
-test("many directive openers with no close strip in linear time", () => {
- const input = ("[[ask-agent:" + "x".repeat(88)).repeat(10000);
- const start = process.hrtime.bigint();
- stripSlackDirectives(input);
- assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 100);
-});
diff --git a/skills-seed/hand-off/SKILL.md b/skills-seed/hand-off/SKILL.md
new file mode 100644
index 000000000..acc23f3b8
--- /dev/null
+++ b/skills-seed/hand-off/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: hand-off
+description: Get work done that needs another person's own logins, files or memory. Decide whether to just do it yourself, and if not, ask that person by DM with the full request.
+---
+
+# Hand work to another person
+
+## First, can you do it yourself?
+
+- **Open posture** (your prompt has `## Sharing posture: Open`): do the work yourself with the
+ requester's own logins. Don't hand it off.
+- **Isolated:** hand off only when the work needs that person's own logins, keys, files or memory.
+ Shared services and org credentials don't need a hand-off. If you only need one of their
+ credentials, use the `request-access` skill instead.
+
+## Ask them by DM
+
+```sh
+curl -fsS -X POST "$AGENT_API_URL/v1/reach" \
+ -H "x-agent-capability: $AGENT_API_TOKEN" -H 'content-type: application/json' \
+ -d '{"recipient":"<their name or Slack id>","text":"<the full request>"}'
+```
+
+- They haven't seen this conversation. Write out the whole request: what's needed and why.
+- Start the DM with the source channel name and a permalink to the originating thread, and ask
+ them to reply there (or DM the requester if they can't post there).
+- One DM to that person. Never post the request in a channel.
+
+## Then
+
+- Say you messaged someone only after reach returns `ok: true`, and name the person it matched
+ (`recipient.displayName`). If it failed or matched the wrong person, say that instead.
+- Don't wait or poll for their reply.
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index 1f03603a5..c575aff47 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -58,26 +58,6 @@ interface SlackRunHooks {
onGoal?(goal: GoalView): void | Promise<void>;
}
-export interface SlackAgentRequestContext {
- requestId: string;
- requesterId: string | undefined;
- targetUserId: string;
- targetDisplayName?: string;
- originChannel: string;
- originConversationKind?: "dm" | "channel" | "group";
- originThreadTs?: string;
- originThreadOnly: boolean;
- originChannelName?: string;
- originStatusTs?: string;
- dmChannel: string;
- dmMessageTs?: string;
- task: string;
- originAgentLabel: string;
- targetAgentLabel: string;
- createdAt: number;
- approvalRequestIds?: string[];
-}
-
interface StoredApprovalView extends Omit<PendingApproval, "reason"> {
createdAt?: number;
reason?: string;
@@ -130,10 +110,6 @@ export interface SlackCoreClient {
reportTurnMetrics(runId: string, patch: { deliverMs?: number; slackInflightMs?: number }): Promise<void>;
reportRunEditRef(runId: string, editRef: string): Promise<void>;
getApproval(requestId: string): Promise<StoredApprovalView | null>;
- putAgentRequest(requestId: string, record: SlackAgentRequestContext): Promise<void>;
- getAgentRequest(requestId: string): Promise<SlackAgentRequestContext | null>;
- takeAgentRequest(requestId: string): Promise<SlackAgentRequestContext | null>;
- agentRequestForApproval(approvalRequestId: string): Promise<SlackAgentRequestContext | null>;
pushDirectory(body: DirectoryPush): Promise<boolean>;
claimDeliveries(type: string, claimMs: number): Promise<Delivery[]>;
ackDelivery(id: string, body?: { recipientThreadRef?: string; slackApiMs?: number }): Promise<void>;
@@ -190,7 +166,6 @@ export interface SlackCoreClientDeps {
runs: RunStore;
turnStream: TurnStream;
tasks: TaskStore;
- agentRequests: DurableMap<SlackAgentRequestContext>;
pickAckEmoji?(text: string, candidates: readonly string[]): Promise<string | undefined>;
ackPicks?: AckEmojiPickStore;
ackModelId?: () => string | undefined;
@@ -204,46 +179,6 @@ export interface SlackCoreClientDeps {
const RUN_FALLBACK_POLL_MS = 1_000;
const RUN_STALL_BUDGET_MS = 300_000;
-const AGENT_REQUEST_TTL_MS = 7 * 24 * 60 * 60 * 1_000;
-
-function agentRequestExpired(record: SlackAgentRequestContext): boolean {
- return Date.now() - record.createdAt > AGENT_REQUEST_TTL_MS;
-}
-
-export type AgentRequestStore = Pick<
- SlackCoreClient,
- "putAgentRequest" | "getAgentRequest" | "takeAgentRequest" | "agentRequestForApproval"
->;
-
-export function createAgentRequestStore(map: DurableMap<SlackAgentRequestContext>): AgentRequestStore {
- return {
- async putAgentRequest(requestId, record) {
- await map.put(requestId, record);
- await (async () => {
- for (const [id, existing] of await map.entries()) {
- if (agentRequestExpired(existing)) await map.delete(id);
- }
- })().catch(swallowAs("agent-requests: expired sweep", undefined));
- },
-
- async getAgentRequest(requestId) {
- const record = await map.get(requestId);
- return record && !agentRequestExpired(record) ? record : null;
- },
-
- async takeAgentRequest(requestId) {
- const record = await map.take(requestId);
- return record && !agentRequestExpired(record) ? record : null;
- },
-
- async agentRequestForApproval(approvalRequestId) {
- for (const [, record] of await map.entries()) {
- if (record.approvalRequestIds?.includes(approvalRequestId) && !agentRequestExpired(record)) return record;
- }
- return null;
- },
- };
-}
export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClient {
const lease = deps.leaderLease ?? createNoopLeaderLease();
@@ -508,8 +443,6 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
};
},
- ...createAgentRequestStore(deps.agentRequests),
-
async pushDirectory(body) {
if (body.workspaceUrl) await deps.app.setDirectoryWorkspaceUrl(body.workspaceUrl);
let applied = true;
diff --git a/src/egress-authz-main.ts b/src/egress-authz-main.ts
index f86f3682f..fc78f311d 100644
--- a/src/egress-authz-main.ts
+++ b/src/egress-authz-main.ts
@@ -7,7 +7,7 @@ import { createEgressAuditSink, type EgressAuditRecord, type EgressAuditSink } f
import { createPostgresEgressAuditSink } from "./admin/postgres-egress-audit-sink.ts";
import { signedRequestHeaders } from "../plugins/chassis/src/source-auth-sign.ts";
import { createSweeper } from "./util/sweeper.ts";
-import { errMessage } from "./util/errors.ts";
+import { errMessage, swallow } from "./util/errors.ts";
import { shutdownOnUncaught } from "./util/process-guard.ts";
import { numEnv } from "./config.ts";
import type { EgressPolicy, ScopeId } from "./types.ts";
@@ -128,7 +128,7 @@ export function buildEgressAuthzServer(deps: EgressAuthzDeps): Server {
async function checkStatus(
req: IncomingMessage,
authority: string,
- ): Promise<{ status: 200 | 403; upstream?: string }> {
+ ): Promise<{ status: 200 | 403 | 407; upstream?: string }> {
const host = hostFromAuthority(authority);
if (!host) return { status: 403 };
const portText = authority.match(/:(\d+)$/)?.[1];
@@ -137,11 +137,14 @@ export function buildEgressAuthzServer(deps: EgressAuthzDeps): Server {
if (portText) port = Number(portText);
if (!Number.isInteger(port) || port < 1 || port > 65_535) return { status: 403 };
const token = tokenFromRequest(req);
- const claims = await claimsFor(token, deps);
+ const challenge = !token && deps.tokenless !== "open";
+ const claims = challenge ? undefined : await claimsFor(token, deps);
let policy: EgressPolicy | undefined = DENY_ALL;
if (claims) policy = claims.egress;
- else if (!token && deps.tokenless === "open") policy = OPEN;
- const d = await decide(host, policy, lookup);
+ else if (!token) policy = OPEN;
+ const d: { allow: boolean; verdict: EgressVerdict; address?: string } = challenge
+ ? { allow: false, verdict: "denied" }
+ : await decide(host, policy, lookup);
try {
deps.audit.record({
source: "proxy",
@@ -152,8 +155,9 @@ export function buildEgressAuthzServer(deps: EgressAuthzDeps): Server {
principalId: claims?.actorId ?? "unknown",
});
} catch (error) {
- void error;
+ swallow("egress-authz: audit record", error);
}
+ if (challenge) return { status: 407 };
if (!d.allow || !d.address) return { status: 403 };
return { status: 200, upstream: isIP(d.address) === 6 ? `[${d.address}]:${port}` : `${d.address}:${port}` };
}
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 30404e7f7..7ae685e1d 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -613,6 +613,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
recordResult(callId, summary, ret, isError, sourceScopeId, false, undefined, { provenance: "external", source });
const EXECUTE_TIMEOUT_GUIDANCE =
+ "Commands may run under a POSIX sh such as dash, not bash: wrap bash-only syntax like ${var/a/b} or arrays in bash -c. " +
`Each command has a wall-clock timeout (default ${execTimeoutSec}s, max ${execCeilingSec}s) — set \`timeout_seconds\` ` +
"higher for builds/installs/tsc/test runs that legitimately take minutes, or lower for " +
"commands you expect to be quick so a hang frees the machine fast. For work that " +
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index df7e3ef06..8ccf48aad 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -379,12 +379,6 @@ export function createMockHarness(): Harness {
reply = `wallclock:${turn.turnWallClockMs ?? 0}`;
} else if (command0 === "!surfacename") {
reply = `surface:${turn.surfaceName ?? "none"}`;
- } else if (command0.startsWith("!askagent ")) {
- const rest = command0.slice("!askagent ".length).trim();
- const sp = rest.indexOf(" ");
- const target = sp === -1 ? rest : rest.slice(0, sp);
- const task = sp === -1 ? "help with this request" : rest.slice(sp + 1).trim();
- reply = `I'll ask their personal agent.\n\n[[ask-agent: ${target} | ${task}]]`;
} else if (command0.startsWith("!think ")) {
await turn.emit({
type: "thinking",
diff --git a/src/slack/README.md b/src/slack/README.md
index 8f582cbc4..7605b58d8 100644
--- a/src/slack/README.md
+++ b/src/slack/README.md
@@ -181,14 +181,10 @@ the tokens, core simply runs without Slack.
approval (`pending_approval`) or _finished with a reply but skipped_ the gated command
(collect-mode `ok` + `pendingApprovals`, what the real Pi harness does) — in the latter case
the buttons are posted alongside the reply. Clicking re-runs the turn with the command approved.
-- **Channel agents can ask personal agents.** If a channel task needs a member's personal setup
- (their env, browser login, resident CLI, connected app, or private files), the channel agent can
- ask that person's personal agent instead of pretending the shared context has the resource. The
- request appears in the original thread as `#channel agent → Name's personal agent`, and the target
- person gets a DM with **Run with my setup** / **Decline** buttons. If they approve, the plugin runs
- a normal DM-scoped turn as that user and posts the result back to the thread as
- `Name's personal agent → #channel agent`. The target must already be an internal participant in
- the channel conversation. In `HARNESS=mock`, use `!askagent <@USERID> task` to test the full flow.
+- **Hand-offs are plain DMs.** When channel work needs another member's own logins, files or
+ memory, the agent follows the `hand-off` skill: in Open conversations it uses the requester's own
+ access; otherwise it sends that person a DM through `POST /v1/reach` with the full request, and
+ says so only after reach confirms who it matched.
- In an **externally-shared (Slack Connect) channel**, or any channel/mpim whose audience
includes a **guest or external member**, it stays silent in-channel and replies privately
(ephemeral) — and uploads no file there — internal-only (spec §9). Group DMs (mpim) aren't
@@ -264,7 +260,6 @@ your per-dev name + tokens live only in your local app and your gitignored `.env
| channel `thread_ts` (root) | `threadRef` = `ch:<channel>:<root>` (one session per thread) |
| `TurnResult.reply` | posted in-thread; unprompted `refused` (`security_quarantine` included) → silent, addressed `refused` → requester-only (ephemeral in channels) except addressed `security_quarantine` → fixed in-thread acknowledgement; `pending_approval` (or `ok` + `pendingApprovals`, collect-mode) → Block Kit approval buttons |
| Block Kit approval button (`block_actions`) | `POST /v1/turns` with `approval` (`once` / `session` / `always` / deny) |
-| `[[ask-agent: <@U…> \| task]]` in a channel reply | Slack strips the directive, DMs that user for consent, then runs `POST /v1/turns` as a DM-scoped personal-agent turn and posts the result back to the original thread |
| Pending `/v1/surface-context` request (hanging long-poll, source-authed) | The agent's mid-turn context pull: core resolved the target (current conversation via the capability's opaque destination, or a directory-resolved public channel) and parked the request; the plugin enforces visibility (public, bot-member, not externally shared — or the current conversation itself, even private), fetches history with `before` paging + `match` filtering, and POSTs the messages back (`buildContextWindow`). The default injected window is small (`MAX_RECENT_MESSAGES`, env `SLACK_RECENT_MESSAGES`); context beyond it is pull, not push |
## Notes / next
diff --git a/src/slack/agent-requests.ts b/src/slack/agent-requests.ts
deleted file mode 100644
index 5f2257c02..000000000
--- a/src/slack/agent-requests.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { button } from "./approval-cards.ts";
-import { extractDirectives } from "./directives.ts";
-
-export const AGENT_REQUEST_ACTION_IDS = ["agent_request_run", "agent_request_deny"] as const;
-export type AgentRequestActionId = (typeof AGENT_REQUEST_ACTION_IDS)[number];
-
-export interface AgentRequestDirective {
- targetUserId: string;
- task: string;
-}
-
-export interface SlackAgentRequest {
- requestId: string;
- originAgentLabel: string;
- targetAgentLabel: string;
- task: string;
-}
-
-export interface SlackAgentRequestMessage {
- text: string;
- blocks: Array<Record<string, unknown>>;
-}
-
-const AGENT_REQUEST_BLOCK_PREFIX = "agent_request:";
-
-function truncateForSlack(text: string, max = 900): string {
- const safe = text.replace(/\s+/g, " ").trim();
- return `${safe.slice(0, max)}${safe.length > max ? "..." : ""}`;
-}
-
-export function agentRequestMessage(req: SlackAgentRequest): SlackAgentRequestMessage {
- const task = truncateForSlack(req.task);
- return {
- text: `${req.originAgentLabel} is asking ${req.targetAgentLabel} to run a personal-scope task.`,
- blocks: [
- {
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*${req.originAgentLabel} → ${req.targetAgentLabel}*\n${task}`,
- },
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: "This runs in your personal agent context. The result can be posted back to the original thread.",
- },
- ],
- },
- {
- type: "actions",
- block_id: `${AGENT_REQUEST_BLOCK_PREFIX}${req.requestId}`.slice(0, 255),
- elements: [
- button("Run with my setup", "agent_request_run", req.requestId, "primary"),
- button("Decline", "agent_request_deny", req.requestId, "danger"),
- ],
- },
- ],
- };
-}
-
-export const AGENT_REQUEST_INSTRUCTION =
- "In a shared Slack channel, you may need a specific person's personal agent because the needed " +
- "resource, login, environment variable, or private setup belongs to that person and cannot be " +
- "borrowed by the channel agent. Do not claim you know what's in their personal setup unless the " +
- "conversation says so. Instead, ask that person's personal agent by writing a directive somewhere " +
- "in your reply: `[[ask-agent: <@USERID> | task for their personal agent]]`. Use the Slack user id " +
- "shown in the People here line, for example `<@U123>`. The task should say exactly what the " +
- "personal agent should try and what result is safe to share back to this thread; never ask it to " +
- "reveal secrets. The plugin strips this directive from what humans see, DMs that person for " +
- "approval, runs their personal agent only if they approve, and posts the result back here with " +
- "clear agent labels. If you do not know which person to ask, ask the channel who should be involved. " +
- "This is only for a person's private setup: another agent already in the channel (shown as `agent` in " +
- "the People here line) is a colleague, not a personal agent to hand off to — just @mention it in your " +
- "normal reply using its `<@…>` id and it will answer here in the thread.";
-
-const AGENT_REQUEST_DIRECTIVE = /\[\[ask-agent:([^|\]]{0,400})\|([\s\S]*?)\]\]/gi;
-const AGENT_REQUEST_OPENER = /\[\[ask-agent:/gi;
-
-function stripLeftoverAgentRequests(text: string): string {
- let out = "";
- let cursor = 0;
- AGENT_REQUEST_OPENER.lastIndex = 0;
- for (let m = AGENT_REQUEST_OPENER.exec(text); m; m = AGENT_REQUEST_OPENER.exec(text)) {
- out += text.slice(cursor, m.index);
- const close = text.indexOf("]]", m.index + m[0].length);
- if (close < 0) return out;
- cursor = close + 2;
- AGENT_REQUEST_OPENER.lastIndex = cursor;
- }
- return out + text.slice(cursor);
-}
-const SLACK_USER_REF = /^(?:<@([A-Z0-9]+)(?:\|[^>]*)?>|@?([A-Z0-9]+))$/i;
-
-function parseSlackUserRef(ref: string): string | undefined {
- const m = SLACK_USER_REF.exec(ref.trim());
- return m?.[1] ?? m?.[2]?.toUpperCase();
-}
-
-export function extractAgentRequests(reply: string): { text: string; requests: AgentRequestDirective[] } {
- const { text, matches } = extractDirectives(
- reply,
- AGENT_REQUEST_DIRECTIVE,
- stripLeftoverAgentRequests,
- ([targetRef, taskRaw]) => {
- const targetUserId = parseSlackUserRef(targetRef ?? "");
- const task = (taskRaw ?? "").trim();
- return targetUserId && task ? { targetUserId, task } : undefined;
- },
- );
- return { text, requests: matches };
-}
-
-export function stripAgentRequestDirectives(partial: string): string {
- if (!partial) return partial ?? "";
- return stripLeftoverAgentRequests(partial.replace(AGENT_REQUEST_DIRECTIVE, ""));
-}
diff --git a/src/slack/approval-cards.ts b/src/slack/approval-cards.ts
index 7bdf01543..b77a737c5 100644
--- a/src/slack/approval-cards.ts
+++ b/src/slack/approval-cards.ts
@@ -1,6 +1,5 @@
import { clip, inlineCode } from "./util.ts";
import { parseDeliveryTarget } from "./delivery.ts";
-import type { AgentRequestActionId } from "./agent-requests.ts";
export const APPROVAL_ACTION_IDS = ["hilo_allow_once", "hilo_allow_session", "hilo_allow_always", "hilo_deny"] as const;
export type ApprovalActionId = (typeof APPROVAL_ACTION_IDS)[number];
@@ -22,9 +21,9 @@ export interface SlackApprovalMessage {
const APPROVAL_BLOCK_PREFIX = "hilo_approval:";
-export function button(
+function button(
text: string,
- actionId: ApprovalActionId | AgentRequestActionId,
+ actionId: ApprovalActionId,
value: string,
style?: "primary" | "danger",
): Record<string, unknown> {
diff --git a/src/slack/approval-context.ts b/src/slack/approval-context.ts
deleted file mode 100644
index e656127ce..000000000
--- a/src/slack/approval-context.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { ActorAssertion, AgentRequestDirective } from "./lib.ts";
-
-export function resolveAgentRequestTarget(
- audience: readonly ActorAssertion[],
- targetUserId: AgentRequestDirective["targetUserId"],
- slackIdsByPrincipal?: ReadonlyMap<string, string>,
-): ActorAssertion | undefined {
- return audience.find((a) => slackIdsByPrincipal?.get(a.externalId) === targetUserId || a.externalId === targetUserId);
-}
diff --git a/src/slack/approvals.ts b/src/slack/approvals.ts
index 0fdc9cdfe..063dad192 100644
--- a/src/slack/approvals.ts
+++ b/src/slack/approvals.ts
@@ -1,23 +1,14 @@
import { isSubagentThreadRef } from "../sessions/session-syscalls.ts";
-import { errMessage, swallow, swallowAs } from "../util/errors.ts";
-import { slackFailureClause, slackFailureText } from "./turn-flow.ts";
-import { randomUUID } from "node:crypto";
+import { errMessage, swallowAs } from "../util/errors.ts";
+import { slackFailureText } from "./turn-flow.ts";
import {
- type ActorAssertion,
- AGENT_REQUEST_ACTION_IDS,
- type AgentRequestActionId,
- type AgentRequestDirective,
APPROVAL_ACTION_IDS,
type ApprovalActionId,
type StoredApproval,
- agentRequestMessage,
approvalMessage,
- botIdentityArgs,
clip,
createApprovalRegistry,
createThreadTracker,
- dmThreadRef,
- encodeDeliveryTarget,
inlineCode,
isBoundaryRefusal,
recoveredApprovalContext,
@@ -28,24 +19,13 @@ import {
uploadAttachments,
uploadFailureNote,
} from "./lib.ts";
-import { resolveAgentRequestTarget } from "./approval-context.ts";
import { parseBlockAction, parseInteractionBody } from "./payloads.ts";
-import type { SlackAgentRequestContext, SlackCoreClient } from "../api/slack-core-client.ts";
+import type { SlackCoreClient } from "../api/slack-core-client.ts";
import type { TurnResult } from "../types.ts";
import { userFacingFailureClause } from "../core/failure-copy.ts";
-import { GENERIC_FAILURE_CLAUSE } from "../../plugins/chassis/src/failure-copy.ts";
import type { CoreTurnBody, TurnFlow } from "./turn-flow.ts";
-import type { BotIdentity, Directory } from "./directory.ts";
-import {
- type SlackConversationKind,
- applyAndLogReactions,
- channelAgentLabel,
- cleanAgentReplyForSlack,
- conversationPlaceLabel,
- personalAgentLabel,
- tryUpdateSlackMessage,
- updateSlackMessage,
-} from "./messaging.ts";
+import type { Directory } from "./directory.ts";
+import { applyAndLogReactions, cleanAgentReplyForSlack, updateSlackMessage } from "./messaging.ts";
interface ActionArgs {
ack: () => Promise<void>;
@@ -70,7 +50,6 @@ interface SlackApprovalContext {
turn: Omit<CoreTurnBody, "approval">;
allowedTs?: Set<string>;
slackIdsByPrincipal?: ReadonlyMap<string, string>;
- agentRequest?: SlackAgentRequestContext;
ackedFirstBlock?: string;
recovered?: boolean;
}
@@ -84,29 +63,11 @@ function approvalScope(actionId: ApprovalActionId): ApprovalScope | "deny" {
return "deny";
}
-function agentRequestAction(actionId: AgentRequestActionId): "run" | "deny" {
- return actionId === "agent_request_run" ? "run" : "deny";
-}
-
export interface Approvals {
rememberSlackApprovals(
approvals: NonNullable<TurnResult["pendingApprovals"]>,
ctx: Omit<SlackApprovalContext, "command" | "reason">,
): void;
- postAgentRequests(
- client: any,
- ctx: {
- requesterId: string | undefined;
- channel: string;
- replyThreadTs?: string;
- threadOnly: boolean;
- kind: SlackConversationKind;
- channelName?: string;
- audience: ActorAssertion[];
- slackIdsByPrincipal?: ReadonlyMap<string, string>;
- },
- requests: readonly AgentRequestDirective[],
- ): Promise<void>;
registerActions(app: { action(pattern: RegExp, handler: (args: any) => Promise<void>): void }): void;
}
@@ -116,9 +77,8 @@ export function createApprovals(deps: {
flow: TurnFlow;
directory: Directory;
threads: ReturnType<typeof createThreadTracker>;
- ids: BotIdentity;
}): Approvals {
- const { core, flow, directory, threads, ids } = deps;
+ const { core, flow, directory, threads } = deps;
interface TurnOutcome {
result: TurnResult;
@@ -177,333 +137,10 @@ export function createApprovals(deps: {
}
}
- type AgentRequestFetch =
- { state: "found"; ctx: SlackAgentRequestContext } | { state: "gone" } | { state: "unavailable" };
-
- async function fetchAgentRequest(requestId: string): Promise<AgentRequestFetch> {
- try {
- const ctx = await core.getAgentRequest(requestId);
- if (!ctx) return { state: "gone" };
- return { state: "found", ctx };
- } catch (err) {
- console.error("[slack-plugin] agent-request recovery fetch failed:", (err as Error).message);
- return { state: "unavailable" };
- }
- }
-
- async function settleAgentRequest(ctx: SlackAgentRequestContext): Promise<void> {
- await core.takeAgentRequest(ctx.requestId).catch(swallowAs("slack: settle agent request", null));
- }
-
- function agentRequestStatusText(
- ctx: SlackAgentRequestContext,
- state: "waiting" | "running" | "declined" | "failed",
- ): string {
- const arrow = `*${ctx.originAgentLabel} → ${ctx.targetAgentLabel}*`;
- if (state === "waiting")
- return `${arrow}\nWaiting for ${ctx.targetDisplayName ?? ctx.targetUserId} to approve running this in their personal setup.`;
- if (state === "running") return `${arrow}\nApproved. Running with ${ctx.targetAgentLabel} now.`;
- if (state === "declined")
- return `${arrow}\n${ctx.targetDisplayName ?? ctx.targetUserId} declined the personal-agent handoff.`;
- return `${arrow}\nThe personal-agent handoff could not be completed.`;
- }
-
- async function failAgentRequest(
- client: any,
- ctx: SlackAgentRequestContext,
- reason: string,
- dmMessageTs?: string,
- ): Promise<void> {
- await settleAgentRequest(ctx);
- const originText = `${agentRequestStatusText(ctx, "failed")}\n${reason}`;
- if (!(await tryUpdateSlackMessage(client, ctx.originChannel, ctx.originStatusTs, originText))) {
- await client.chat
- .postMessage(
- slackReplyArgs(ctx.originChannel, originText, ctx.originThreadTs, { threadOnly: ctx.originThreadOnly }),
- )
- .catch((err: Error) => console.error("[slack-plugin] couldn't post handoff failure:", err.message));
- }
- await tryUpdateSlackMessage(
- client,
- ctx.dmChannel,
- dmMessageTs ?? ctx.dmMessageTs,
- `I couldn't finish the handoff: ${reason}`,
- );
- }
-
- async function completeAgentRequest(
- client: any,
- ctx: SlackAgentRequestContext,
- result: TurnResult,
- dmMessageTs?: string,
- ): Promise<void> {
- await settleAgentRequest(ctx);
- const { text: replyBody } = cleanAgentReplyForSlack(result.reply ?? "");
- let bodyText = "Completed.";
- if (replyBody) bodyText = toSlackMrkdwn(replyBody);
- else if (result.attachments?.length) bodyText = "Completed; attached file(s) below.";
- const posted = `*${ctx.targetAgentLabel} → ${ctx.originAgentLabel}*\n${bodyText}`;
- if (!(await tryUpdateSlackMessage(client, ctx.originChannel, ctx.originStatusTs, posted))) {
- await client.chat.postMessage(
- slackReplyArgs(ctx.originChannel, posted, ctx.originThreadTs, {
- threadOnly: ctx.originThreadOnly,
- unfurlLinks: false,
- }),
- );
- }
- if (result.attachments?.length) {
- try {
- await uploadAttachments(client, ctx.originChannel, ctx.originThreadTs, result.attachments, core);
- } catch (err) {
- console.error("[slack-plugin] file upload failed:", (err as Error).message);
- await client.chat.postMessage(
- slackReplyArgs(ctx.originChannel, uploadFailureNote(err), ctx.originThreadTs, {
- threadOnly: ctx.originThreadOnly,
- }),
- );
- }
- }
- await tryUpdateSlackMessage(
- client,
- ctx.dmChannel,
- dmMessageTs ?? ctx.dmMessageTs,
- `Posted the result from ${ctx.targetAgentLabel} back to ${ctx.originAgentLabel}.`,
- );
- }
-
- async function askForAgentRequestCommandApproval(
- client: any,
- ctx: SlackAgentRequestContext,
- turn: Omit<CoreTurnBody, "approval">,
- approvals: NonNullable<TurnResult["pendingApprovals"]>,
- opts: { approvalMessageTs?: string; handoffMessageTs?: string } = {},
- ): Promise<void> {
- if (!approvals.length) {
- await failAgentRequest(
- client,
- ctx,
- `${ctx.targetAgentLabel} asked for command approval but did not return an approval request.`,
- opts.handoffMessageTs,
- );
- return;
- }
-
- const linked: SlackAgentRequestContext = { ...ctx, approvalRequestIds: approvals.map((p) => p.requestId) };
- try {
- await core.putAgentRequest(linked.requestId, linked);
- } catch (err) {
- swallow("slack: putAgentRequest", err);
- await failAgentRequest(
- client,
- ctx,
- `the pending command approval couldn't be recorded — ${GENERIC_FAILURE_CLAUSE}`,
- opts.handoffMessageTs,
- );
- return;
- }
- rememberSlackApprovals(approvals, {
- requesterId: ctx.targetUserId,
- channel: ctx.dmChannel,
- approvalChannel: ctx.dmChannel,
- ...(ctx.dmMessageTs ? { triggerTs: ctx.dmMessageTs } : {}),
- threadOnly: false,
- turn,
- agentRequest: linked,
- });
- if (opts.approvalMessageTs)
- await updateSlackMessage(
- client,
- ctx.dmChannel,
- opts.approvalMessageTs,
- "Approved. A new command needs approval; its card will arrive separately.",
- );
- await tryUpdateSlackMessage(
- client,
- ctx.originChannel,
- ctx.originStatusTs,
- `${agentRequestStatusText(ctx, "running")}\nWaiting for ${ctx.targetDisplayName ?? ctx.targetUserId} to approve a command in their personal setup.`,
- );
- await tryUpdateSlackMessage(
- client,
- ctx.dmChannel,
- opts.handoffMessageTs ?? ctx.dmMessageTs,
- `This handoff needs command approval before ${ctx.targetAgentLabel} can finish.`,
- );
- }
-
- async function handleAgentRequestResult(
- client: any,
- ctx: SlackAgentRequestContext,
- turn: Omit<CoreTurnBody, "approval">,
- result: TurnResult,
- opts: { approvalMessageTs?: string; handoffMessageTs?: string } = {},
- ): Promise<void> {
- const approvals = result.pendingApprovals ?? [];
- if (approvals.length || result.status === "pending_approval") {
- await askForAgentRequestCommandApproval(client, ctx, turn, approvals, opts);
- return;
- }
- if (result.status === "ok") {
- await completeAgentRequest(client, ctx, result, opts.handoffMessageTs ?? opts.approvalMessageTs);
- if (opts.approvalMessageTs && opts.handoffMessageTs && opts.approvalMessageTs !== opts.handoffMessageTs) {
- await tryUpdateSlackMessage(
- client,
- ctx.dmChannel,
- opts.approvalMessageTs,
- `Posted the result from ${ctx.targetAgentLabel} back to ${ctx.originAgentLabel}.`,
- );
- }
- return;
- }
- await failAgentRequest(
- client,
- ctx,
- userFacingFailureClause(result),
- opts.handoffMessageTs ?? opts.approvalMessageTs,
- );
- }
-
- async function postAgentRequests(
- client: any,
- ctx: {
- requesterId: string | undefined;
- channel: string;
- replyThreadTs?: string;
- threadOnly: boolean;
- kind: SlackConversationKind;
- channelName?: string;
- audience: ActorAssertion[];
- slackIdsByPrincipal?: ReadonlyMap<string, string>;
- },
- requests: readonly AgentRequestDirective[],
- ): Promise<void> {
- for (const req of requests) {
- const target = resolveAgentRequestTarget(ctx.audience, req.targetUserId, ctx.slackIdsByPrincipal);
- const originAgentLabel = channelAgentLabel(ctx.kind, ctx.channelName, ctx.channel);
- if (!target || target.isExternalGuest) {
- await client.chat.postMessage(
- slackReplyArgs(
- ctx.channel,
- `${originAgentLabel} can only ask personal agents for internal people who are already in this conversation.`,
- ctx.replyThreadTs,
- { threadOnly: ctx.threadOnly },
- ),
- );
- continue;
- }
-
- if (target.isBot) {
- await client.chat.postMessage(
- slackReplyArgs(
- ctx.channel,
- `${originAgentLabel}: ${target.displayName ?? "that"} is another agent — just @mention it in your reply to reach it; ask-agent is only for a person's private setup.`,
- ctx.replyThreadTs,
- { threadOnly: ctx.threadOnly },
- ),
- );
- continue;
- }
-
- const requestId = randomUUID();
- const targetAgentLabel = personalAgentLabel(target, req.targetUserId);
- const base: Omit<SlackAgentRequestContext, "originStatusTs" | "dmChannel" | "dmMessageTs"> = {
- requestId,
- createdAt: Date.now(),
- requesterId: ctx.requesterId,
- targetUserId: req.targetUserId,
- ...(target.displayName ? { targetDisplayName: target.displayName } : {}),
- originChannel: ctx.channel,
- originConversationKind: ctx.kind,
- ...(ctx.replyThreadTs ? { originThreadTs: ctx.replyThreadTs } : {}),
- originThreadOnly: ctx.threadOnly,
- ...(ctx.channelName ? { originChannelName: ctx.channelName } : {}),
- task: req.task,
- originAgentLabel,
- targetAgentLabel,
- };
-
- let pendingCtx: SlackAgentRequestContext | undefined;
- try {
- const opened = await client.conversations.open({ users: req.targetUserId });
- const dmChannel = String(opened?.channel?.id ?? "");
- if (!dmChannel) {
- await client.chat.postMessage(
- slackReplyArgs(
- ctx.channel,
- `${originAgentLabel} couldn't open a DM to ${target.displayName ?? req.targetUserId}.`,
- ctx.replyThreadTs,
- {
- threadOnly: ctx.threadOnly,
- },
- ),
- );
- continue;
- }
-
- pendingCtx = { ...base, dmChannel };
- const status = await client.chat.postMessage(
- slackReplyArgs(ctx.channel, agentRequestStatusText(pendingCtx, "waiting"), ctx.replyThreadTs, {
- threadOnly: ctx.threadOnly,
- }),
- );
- if (status?.ts) pendingCtx.originStatusTs = String(status.ts);
-
- const prompt = agentRequestMessage({
- requestId,
- originAgentLabel,
- targetAgentLabel,
- task: req.task,
- });
- const dm = await client.chat.postMessage({
- channel: dmChannel,
- text: prompt.text,
- ...botIdentityArgs(),
- blocks: prompt.blocks,
- });
- if (dm?.ts) pendingCtx.dmMessageTs = String(dm.ts);
- await core.putAgentRequest(requestId, pendingCtx);
- } catch (err) {
- swallow("slack: agent request dispatch", err);
- const reason = `couldn't send the personal-agent request to ${target.displayName ?? req.targetUserId} — ${GENERIC_FAILURE_CLAUSE}`;
- if (pendingCtx?.originStatusTs) {
- await failAgentRequest(client, pendingCtx, reason);
- } else {
- await client.chat.postMessage(
- slackReplyArgs(
- ctx.channel,
- `${originAgentLabel} couldn't ask ${targetAgentLabel} — ${GENERIC_FAILURE_CLAUSE}`,
- ctx.replyThreadTs,
- {
- threadOnly: ctx.threadOnly,
- },
- ),
- );
- }
- }
- }
- }
-
async function postApprovalFollowup(client: any, ctx: SlackApprovalContext, text: string): Promise<void> {
await client.chat.postMessage(slackReplyArgs(ctx.channel, text, ctx.replyThreadTs, { threadOnly: ctx.threadOnly }));
}
- function personalAgentTurnText(ctx: SlackAgentRequestContext): string {
- const destination = conversationPlaceLabel(
- ctx.originConversationKind ?? "channel",
- ctx.originChannelName,
- ctx.originChannel,
- );
- return [
- "[Agent-to-agent request]",
- `${ctx.originAgentLabel} asked ${ctx.targetAgentLabel} to help with a task that may require this user's personal setup.`,
- "",
- "Task:",
- ctx.task,
- "",
- `Run this in the user's personal context if appropriate. Do not reveal API keys, credentials, tokens, or other secrets. Return only the concrete outcome, evidence, or blocker that is safe to share back to ${destination}.`,
- ].join("\n");
- }
-
async function handleApprovalAction({ ack, body, action, client }: ActionArgs): Promise<void> {
await ack();
const parsed = parseBlockAction(action, APPROVAL_ACTION_IDS);
@@ -569,15 +206,7 @@ export function createApprovals(deps: {
})
: null;
if (rebuilt && !ctx) {
- const handoffId = (rebuilt.turn.gatewayContext as CoreTurnBody["gatewayContext"])?.details?.agent_request_id;
- const handoff = await (
- typeof handoffId === "string" ? core.getAgentRequest(handoffId) : core.agentRequestForApproval(requestId)
- ).catch(swallowAs("slack: agent-request recovery", null));
- pendingSlackApprovals.remember(requestId, {
- ...rebuilt,
- ...(handoff ? { agentRequest: handoff } : {}),
- recovered: true,
- } as SlackApprovalContext);
+ pendingSlackApprovals.remember(requestId, { ...rebuilt, recovered: true } as SlackApprovalContext);
ctx = pendingSlackApprovals.get(requestId);
console.log(`[slack-plugin] recovered approval ${requestId} from core (in-memory context was lost)`);
} else if (rebuilt && ctx) {
@@ -696,14 +325,6 @@ export function createApprovals(deps: {
settle();
if (await sealedOut(outcome.result)) return;
await updateSlackMessage(client, cardChannel, messageTs, `Denied ${inlineCode(ctx.command)}.`);
- if (ctx.agentRequest) {
- await failAgentRequest(
- client,
- ctx.agentRequest,
- `${inlineCode(ctx.command)} was denied.`,
- ctx.agentRequest.dmMessageTs,
- );
- }
ackConveyedQuarantine(outcome);
return;
}
@@ -730,24 +351,14 @@ export function createApprovals(deps: {
return;
}
- if (ctx.agentRequest) {
- await handleAgentRequestResult(client, ctx.agentRequest, ctx.turn, result, {
- approvalMessageTs: messageTs,
- handoffMessageTs: ctx.agentRequest.dmMessageTs,
- });
- ackConveyedQuarantine(outcome);
- return;
- }
-
if (result.status === "ok") {
if (ctx.threadOnly && ctx.replyThreadTs) threads.mark(ctx.channel, ctx.replyThreadTs, true);
const cleanedContinuation = cleanAgentReplyForSlack(result.reply ?? "");
const replyBody = stripAckPrefix(cleanedContinuation.text, ctx.ackedFirstBlock);
- const { reactions, agentRequests } = cleanedContinuation;
- const actionableAgentRequests = !ctx.turn.externalSlack && ctx.threadOnly ? agentRequests : [];
+ const { reactions } = cleanedContinuation;
let reply = result.stopped ? "Stopped." : "(no response)";
if (replyBody) reply = toSlackMrkdwn(replyBody);
- else if (result.attachments?.length || reactions.length || actionableAgentRequests.length) reply = "Done.";
+ else if (result.attachments?.length || reactions.length) reply = "Done.";
if (cardIsRemote) {
await updateSlackMessage(client, cardChannel, messageTs, `Approved; ran ${inlineCode(ctx.command)}.`);
await postApprovalFollowup(client, ctx, reply);
@@ -764,22 +375,6 @@ export function createApprovals(deps: {
}
const { directives } = resolveReactionTargets(reactions, ctx.allowedTs ?? new Set());
await applyAndLogReactions(client, ctx.channel, ctx.triggerTs, directives);
- if (actionableAgentRequests.length) {
- await postAgentRequests(
- client,
- {
- requesterId: ctx.requesterId,
- channel: ctx.channel,
- ...(ctx.replyThreadTs ? { replyThreadTs: ctx.replyThreadTs } : {}),
- threadOnly: ctx.threadOnly,
- kind: ctx.turn.conversation.kind,
- ...(ctx.turn.conversation.channelName ? { channelName: ctx.turn.conversation.channelName } : {}),
- audience: ctx.turn.conversation.audience ?? [],
- ...(ctx.slackIdsByPrincipal ? { slackIdsByPrincipal: ctx.slackIdsByPrincipal } : {}),
- },
- actionableAgentRequests,
- );
- }
return;
}
@@ -822,9 +417,6 @@ export function createApprovals(deps: {
await updateSlackMessage(client, cardChannel, messageTs, `⚠️ ${msg}`).catch(
swallowAs("slack: update approval message", undefined),
);
- if (ctx.agentRequest) {
- await failAgentRequest(client, ctx.agentRequest, slackFailureClause(err), ctx.agentRequest.dmMessageTs);
- }
return;
}
pendingSlackApprovals.release(requestId);
@@ -855,147 +447,9 @@ export function createApprovals(deps: {
}
}
- async function handleAgentRequestAction({ ack, body, action, client }: ActionArgs): Promise<void> {
- await ack();
- if (deps.externalAccess) return;
- const parsed = parseBlockAction(action, AGENT_REQUEST_ACTION_IDS);
- if (!parsed) return;
- const { actionId, value: requestId } = parsed;
-
- const click = parseInteractionBody(body);
- const { clickerId, messageTs } = click;
- const fetched = await fetchAgentRequest(requestId);
- const channel = click.channel ?? (fetched.state === "found" ? fetched.ctx.dmChannel : "");
-
- if (fetched.state === "unavailable") {
- if (channel && clickerId) {
- await client.chat
- .postEphemeral({
- channel,
- user: clickerId,
- text: "I couldn't check on that agent request just now — try the button again in a moment.",
- })
- .catch(swallowAs("slack: chat.postEphemeral", undefined));
- }
- return;
- }
-
- if (fetched.state === "gone") {
- if (channel && messageTs) {
- await updateSlackMessage(
- client,
- channel,
- messageTs,
- "_That agent request expired — ask the channel agent to send it again._",
- ).catch(swallowAs("slack: update agent-request message", undefined));
- } else if (channel && clickerId) {
- await client.chat
- .postEphemeral({
- channel,
- user: clickerId,
- text: "That agent request expired — ask the channel agent to send it again.",
- })
- .catch(swallowAs("slack: chat.postEphemeral", undefined));
- }
- return;
- }
-
- if (clickerId !== fetched.ctx.targetUserId) {
- await client.chat
- .postEphemeral({
- channel: fetched.ctx.dmChannel,
- user: clickerId,
- text: "Only the person whose personal agent was asked can approve or decline this request.",
- })
- .catch(swallowAs("slack: chat.postEphemeral", undefined));
- return;
- }
-
- let claimed: SlackAgentRequestContext | null | undefined;
- try {
- claimed = await core.takeAgentRequest(requestId);
- } catch (err) {
- console.error("[slack-plugin] agent-request claim failed:", (err as Error).message);
- }
- if (claimed === undefined) {
- await client.chat
- .postEphemeral({
- channel: fetched.ctx.dmChannel,
- user: clickerId,
- text: "I couldn't check on that agent request just now — try the button again in a moment.",
- })
- .catch(swallowAs("slack: chat.postEphemeral", undefined));
- return;
- }
- if (!claimed) return;
- const decision = agentRequestAction(actionId);
- const ctx = decision === "run" ? { ...claimed, requestId: randomUUID() } : claimed;
- if (decision === "deny") {
- await tryUpdateSlackMessage(
- client,
- ctx.dmChannel,
- messageTs ?? ctx.dmMessageTs,
- `Declined. I won't run this in ${ctx.targetAgentLabel}.`,
- );
- await tryUpdateSlackMessage(
- client,
- ctx.originChannel,
- ctx.originStatusTs,
- agentRequestStatusText(ctx, "declined"),
- );
- return;
- }
-
- try {
- await updateSlackMessage(
- client,
- ctx.dmChannel,
- messageTs ?? ctx.dmMessageTs,
- `Approved. Running with ${ctx.targetAgentLabel} now...`,
- );
- await updateSlackMessage(client, ctx.originChannel, ctx.originStatusTs, agentRequestStatusText(ctx, "running"));
- const classified = await directory.classifyUserCached(client, ctx.targetUserId);
- const actor = classified.actor;
- if (actor.isExternalGuest) throw new Error("the target user is not internal");
- const personalTurn: Omit<CoreTurnBody, "approval"> = {
- actor,
- conversation: {
- kind: "dm",
- threadRef: dmThreadRef(ctx.dmChannel),
- audience: [actor],
- },
- deliveryTarget: encodeDeliveryTarget(ctx.dmChannel),
- text: personalAgentTurnText(ctx),
- gatewayContext: {
- location: `an agent-to-agent handoff in a direct message with ${actor.displayName ?? ctx.targetUserId}`,
- details: {
- channel: ctx.dmChannel,
- requested_by_channel: ctx.originChannel,
- agent_request_id: ctx.requestId,
- ...(ctx.originThreadTs ? { requested_by_thread_ts: ctx.originThreadTs } : {}),
- },
- instructions:
- "You are answering an agent-to-agent handoff. Work only with this user's personal context and return a concise result safe to share back to the originating Slack thread.",
- ...(ids.botHandle ? { botHandle: ids.botHandle } : {}),
- },
- ...(classified.timezone ? { timezone: classified.timezone } : {}),
- };
- await core.putAgentRequest(ctx.requestId, ctx);
- const outcome = await runTurn(personalTurn);
- await handleAgentRequestResult(client, ctx, personalTurn, outcome.result, {
- handoffMessageTs: messageTs ?? ctx.dmMessageTs,
- });
- ackConveyedQuarantine(outcome);
- } catch (err) {
- console.error("[slack-plugin] agent-request action failed:", errMessage(err));
- await failAgentRequest(client, ctx, slackFailureClause(err), messageTs ?? ctx.dmMessageTs);
- }
- }
-
function registerActions(app: { action(pattern: RegExp, handler: (args: any) => Promise<void>): void }): void {
app.action(/^hilo_/, handleApprovalAction);
- app.action(/^agent_request_/, handleAgentRequestAction);
}
- return { rememberSlackApprovals, postAgentRequests, registerActions };
+ return { rememberSlackApprovals, registerActions };
}
diff --git a/src/slack/external-access.ts b/src/slack/external-access.ts
index 64b2a11ff..322075bbd 100644
--- a/src/slack/external-access.ts
+++ b/src/slack/external-access.ts
@@ -63,7 +63,7 @@ export function externalSlackNamespace(teamId: string, policy: ExternalSlackAcce
}
export const PRIVATE_CONTINUATION_INSTRUCTION =
- "This Slack workspace has an external audience. Answer and run code here only with the explicitly available external-safe services. Before any personal memory, files, account, calendar, email, or confidential company service is needed, end this turn with [[continue-private: a concise description of the remaining work]]. The platform acknowledges here and automatically continues in the requesting employee's private DM with this request and its channel context. Do not ask them to repeat it or ask for an additional handoff approval. Do not use ask-agent, and do not promise a result back to this channel. Private results stay in the DM. This directive can continue only the current requester's work, never another person's.";
+ "This Slack workspace has an external audience. Answer and run code here only with the explicitly available external-safe services. Before any personal memory, files, account, calendar, email, or confidential company service is needed, end this turn with [[continue-private: a concise description of the remaining work]]. The platform acknowledges here and automatically continues in the requesting employee's private DM with this request and its channel context. Do not ask them to repeat it or ask for an additional handoff approval. Do not promise a result back to this channel. Private results stay in the DM. This directive can continue only the current requester's work, never another person's.";
export function extractPrivateContinuation(text: string): { text: string; task?: string } {
if (!/\[\[continue-private:/i.test(text)) return { text };
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 2ffb20c31..e3d3b1a0f 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -280,7 +280,7 @@ export async function startSlackPlugin(
externalParticipantsEnabled,
...(cfg.recentMessages ? { recentMessages: cfg.recentMessages } : {}),
});
- const approvals = createApprovals({ core, flow, directory, threads, ids, externalAccess: !!cfg.externalAccess });
+ const approvals = createApprovals({ core, flow, directory, threads, externalAccess: !!cfg.externalAccess });
registerKeychainApprovalActions(app, { core, directory, webUiPublicUrl: cfg.webUiPublicUrl });
registerDeployAccessActions(app, { core, directory });
const ensureHeader = createSurfaceHeaderEnsurer({
@@ -364,7 +364,6 @@ export async function startSlackPlugin(
directory,
mirror,
serializer,
- approvals,
ackEmoji,
ackEmojiCandidates: ackEmojiOverride,
ids,
diff --git a/src/slack/lib.ts b/src/slack/lib.ts
index 861b49586..5d9260ab8 100644
--- a/src/slack/lib.ts
+++ b/src/slack/lib.ts
@@ -75,15 +75,6 @@ export {
recoveredApprovalContext,
createApprovalRegistry,
} from "./approval-cards.ts";
-export {
- type AgentRequestActionId,
- AGENT_REQUEST_ACTION_IDS,
- type AgentRequestDirective,
- agentRequestMessage,
- AGENT_REQUEST_INSTRUCTION,
- extractAgentRequests,
- stripAgentRequestDirectives,
-} from "./agent-requests.ts";
export {
encodeTs,
decodeTs,
diff --git a/src/slack/messaging.ts b/src/slack/messaging.ts
index cf9a52170..9c466d6f9 100644
--- a/src/slack/messaging.ts
+++ b/src/slack/messaging.ts
@@ -1,17 +1,11 @@
import { extractPrivateContinuation } from "./external-access.ts";
import {
- type ActorAssertion,
- type AgentRequestDirective,
type ReactionDirective,
- AGENT_REQUEST_INSTRUCTION,
MAX_REACTIONS_PER_TURN,
- REACTION_INSTRUCTION,
SLACK_TEXT_LIMIT,
applyReactions,
botIdentityArgs,
- extractAgentRequests,
extractReactions,
- stripAgentRequestDirectives,
stripReactionDirectives,
} from "./lib.ts";
@@ -38,41 +32,16 @@ export async function updateSlackMessage(
return true;
}
-export async function tryUpdateSlackMessage(
- client: any,
- channel: string,
- ts: string | undefined,
- text: string,
- blocks?: Array<Record<string, unknown>>,
-): Promise<boolean> {
- try {
- return await updateSlackMessage(client, channel, ts, text, blocks);
- } catch (err) {
- console.error("[slack-plugin] chat.update failed:", (err as Error).message);
- return false;
- }
-}
-
-export function cleanAgentReplyForSlack(text: string): {
- text: string;
- reactions: ReactionDirective[];
- agentRequests: AgentRequestDirective[];
-} {
- const extractedReactions = extractReactions(text);
- const extractedRequests = extractAgentRequests(extractedReactions.text);
- return {
- text: extractPrivateContinuation(extractedRequests.text).text,
- reactions: extractedReactions.reactions,
- agentRequests: extractedRequests.requests,
- };
-}
+export const HANDOFF_INSTRUCTION =
+ "When work needs another person's own logins, files or memory, follow the `hand-off` skill.";
-export function slackSurfaceInstructions(kind: SlackConversationKind): string {
- return kind === "dm" ? REACTION_INSTRUCTION : `${REACTION_INSTRUCTION}\n\n${AGENT_REQUEST_INSTRUCTION}`;
+export function cleanAgentReplyForSlack(text: string): { text: string; reactions: ReactionDirective[] } {
+ const extracted = extractReactions(text);
+ return { text: extractPrivateContinuation(extracted.text).text, reactions: extracted.reactions };
}
export function stripSlackDirectives(text: string): string {
- return extractPrivateContinuation(stripAgentRequestDirectives(stripReactionDirectives(text))).text;
+ return extractPrivateContinuation(stripReactionDirectives(text)).text;
}
export async function applyAndLogReactions(
@@ -96,12 +65,6 @@ export async function applyAndLogReactions(
}
}
-function possessive(name: string): string {
- const trimmed = name.trim();
- if (!trimmed) return "Their";
- return trimmed.endsWith("s") || trimmed.endsWith("S") ? `${trimmed}'` : `${trimmed}'s`;
-}
-
export function conversationPlaceLabel(
kind: SlackConversationKind,
channelName: string | undefined,
@@ -110,17 +73,3 @@ export function conversationPlaceLabel(
if (kind === "group") return channelName ? `group DM (${channelName})` : "group DM";
return channelName ? `#${channelName}` : `channel ${channel}`;
}
-
-export function channelAgentLabel(
- kind: SlackConversationKind,
- channelName: string | undefined,
- channel: string,
-): string {
- if (kind === "group") return channelName ? `group DM (${channelName}) agent` : "group DM agent";
- return channelName ? `#${channelName} agent` : `channel ${channel} agent`;
-}
-
-export function personalAgentLabel(actor: ActorAssertion | undefined, userId: string): string {
- const name = actor?.displayName?.trim() || userId;
- return `${possessive(name)} personal agent`;
-}
diff --git a/src/slack/turn-flow.ts b/src/slack/turn-flow.ts
index c76d5b599..f0a7f0989 100644
--- a/src/slack/turn-flow.ts
+++ b/src/slack/turn-flow.ts
@@ -2,7 +2,7 @@ import { swallow } from "../util/errors.ts";
import { sleep, createInFlightThreadMap, type GoalNoticeView, type RunTaskView } from "./lib.ts";
import type { SlackCoreClient } from "../api/slack-core-client.ts";
import type { TurnRequest, TurnResult } from "../types.ts";
-import { GENERIC_FAILURE_CLAUSE, GENERIC_FAILURE_TEXT } from "../../plugins/chassis/src/failure-copy.ts";
+import { GENERIC_FAILURE_TEXT } from "../../plugins/chassis/src/failure-copy.ts";
class SlackTurnFailure extends Error {
constructor(message: string, cause: unknown) {
@@ -14,10 +14,6 @@ export function slackFailureText(err: unknown): string {
return err instanceof SlackTurnFailure ? err.message : GENERIC_FAILURE_TEXT;
}
-export function slackFailureClause(err: unknown): string {
- return err instanceof SlackTurnFailure ? err.message : GENERIC_FAILURE_CLAUSE;
-}
-
export type CoreTurnBody = Omit<TurnRequest, "surface">;
interface TurnHooks {
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index 68c24058a..bea22c302 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -23,6 +23,7 @@ import {
type TaskListPresenter,
DEFAULT_ACK_REACTIONS,
REACTION_DETECT_GUIDANCE,
+ REACTION_INSTRUCTION,
botIdentityArgs,
buildReactionTurnText,
createAckPresenter,
@@ -74,14 +75,13 @@ import type { Mirror } from "./mirror.ts";
import type { ConversationSerializer } from "./conversation-view.ts";
import { reactionTallies } from "./conversation-view.ts";
import type { SlackReactionEvent } from "./payloads.ts";
-import type { Approvals } from "./approvals.ts";
import type { AckEmojiPicker } from "./ack-emoji.ts";
import {
type SlackConversationKind,
applyAndLogReactions,
+ HANDOFF_INSTRUCTION,
cleanAgentReplyForSlack,
conversationPlaceLabel,
- slackSurfaceInstructions,
} from "./messaging.ts";
interface Incoming {
@@ -147,7 +147,6 @@ export function createTurnHandler(deps: {
mirror: Mirror;
readHistory?: SlackHistoryReader;
serializer: ConversationSerializer;
- approvals: Approvals;
ackEmoji: AckEmojiPicker;
ackEmojiCandidates?: () => readonly string[] | null;
ids: BotIdentity;
@@ -166,19 +165,8 @@ export function createTurnHandler(deps: {
ensureOpts?: { pinNew?: boolean },
) => void;
}): TurnHandler {
- const {
- core,
- flow,
- directory,
- mirror,
- serializer,
- approvals,
- ackEmoji,
- ids,
- threads,
- deduper,
- externalParticipantsEnabled,
- } = deps;
+ const { core, flow, directory, mirror, serializer, ackEmoji, ids, threads, deduper, externalParticipantsEnabled } =
+ deps;
const { classifyUserCached, classifyActor, getChannelInfo, channelMembership } = directory;
const { mirrorMessageEvent } = mirror;
const { callCore, inFlightRuns, inFlightRunByThread, ackRunDelivery } = flow;
@@ -334,7 +322,7 @@ export function createTurnHandler(deps: {
? {
location: "a direct message with the user",
details: { channel: inc.channel, ...(inc.threadTs ? { thread_ts: inc.threadTs } : {}) },
- instructions: slackSurfaceInstructions(inc.kind),
+ instructions: REACTION_INSTRUCTION,
reactionGuidance: REACTION_DETECT_GUIDANCE,
...(ids.botHandle ? { botHandle: ids.botHandle } : {}),
}
@@ -347,7 +335,7 @@ export function createTurnHandler(deps: {
: {}),
...(replyThreadTs ? { thread_ts: replyThreadTs } : {}),
},
- instructions: slackSurfaceInstructions(inc.kind),
+ instructions: `${REACTION_INSTRUCTION}\n\n${HANDOFF_INSTRUCTION}`,
reactionGuidance: REACTION_DETECT_GUIDANCE,
...(ids.botHandle ? { botHandle: ids.botHandle } : {}),
};
@@ -706,14 +694,8 @@ export function createTurnHandler(deps: {
return;
}
if (inc.kind === "channel" && replyThreadTs) threads.mark(inc.channel, replyThreadTs, true);
- const { text: replyBody, reactions, agentRequests } = cleanAgentReplyForSlack(result.reply ?? "");
- const actionableAgentRequests = !deps.externalAccess && inc.kind === "channel" ? agentRequests : [];
- const hasNonText = !!(
- result.attachments?.length ||
- reactions.length ||
- actionableAgentRequests.length ||
- result.pendingApprovals?.length
- );
+ const { text: replyBody, reactions } = cleanAgentReplyForSlack(result.reply ?? "");
+ const hasNonText = !!(result.attachments?.length || reactions.length || result.pendingApprovals?.length);
let reply = result.stopped ? "Stopped." : "(no response)";
if (replyBody) reply = toSlackMrkdwn(replyBody);
else if (hasNonText) reply = "";
@@ -739,22 +721,6 @@ export function createTurnHandler(deps: {
const { directives, dropped } = resolveReactionTargets(reactions, allowedTs);
if (dropped) console.error(`[slack-plugin] dropped ${dropped} reaction(s) with an unresolvable message id`);
await applyAndLogReactions(client, inc.channel, inc.ts, directives);
- if (actionableAgentRequests.length) {
- await approvals.postAgentRequests(
- client,
- {
- requesterId: inc.userId,
- channel: inc.channel,
- ...(replyThreadTs ? { replyThreadTs } : {}),
- threadOnly: true,
- kind: conversationKind,
- ...(channelName ? { channelName } : {}),
- audience,
- ...(slackIdsByPrincipal ? { slackIdsByPrincipal } : {}),
- },
- actionableAgentRequests,
- );
- }
await settleAck();
await finishTaskAck();
};
diff --git a/src/wiring.ts b/src/wiring.ts
index dc6ab1fa2..dbdbac7ad 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -365,7 +365,7 @@ import { createApp, type App } from "./api/app.ts";
import { startSession } from "./api/start-session.ts";
import { createSwarmStore, type SwarmStorage } from "./swarms/swarm-store.ts";
import { createSwarmService } from "./swarms/swarm-service.ts";
-import { createSlackCoreClient, type SlackAgentRequestContext, type SlackCoreClient } from "./api/slack-core-client.ts";
+import { createSlackCoreClient, type SlackCoreClient } from "./api/slack-core-client.ts";
import { createSurfaceContextPuller } from "./api/surface-context-puller.ts";
import { createEngagedRegistry } from "./wake/engaged-registry.ts";
import { createWakeSweep, type WakeSweep } from "./wake/sweep.ts";
@@ -2262,7 +2262,6 @@ export function buildApp(
runs,
turnStream,
tasks,
- agentRequests: artifactMap<SlackAgentRequestContext>("slack_agent_requests"),
ackPicks: ackEmojiPicks,
ackModelId: () => auxiliaryModelForProvider("anthropic"),
...(config.brandingDefault ? { brandingDefault: config.brandingDefault } : {}),
diff --git a/test/egress-authz.test.ts b/test/egress-authz.test.ts
index 0f851b604..79786fb8b 100644
--- a/test/egress-authz.test.ts
+++ b/test/egress-authz.test.ts
@@ -185,12 +185,12 @@ test("allowlist present => non-matching host is 403 not_allowlisted, matching ho
}
});
-test("NO token fails closed by default and is audited as unknown", async () => {
+test("NO token asks for proxy credentials by default and is audited as unknown", async () => {
const { server, records } = boot();
const port = await listen(server);
try {
- assert.equal(await check(port, "example.com:443"), 403);
- assert.equal(records.at(-1)?.verdict, "not_allowlisted");
+ assert.equal(await check(port, "example.com:443"), 407);
+ assert.equal(records.at(-1)?.verdict, "denied");
assert.equal(records.at(-1)?.scopeLabel, "unknown");
assert.equal(records.at(-1)?.principalId, "unknown");
} finally {
@@ -248,7 +248,7 @@ test("IMDS + link-local + cloud metadata names are denied even tokenless / with
"metadata.google.internal:80",
"metadata.google.internal",
]) {
- assert.equal(await check(port, authority), 403, `tokenless ${authority}`);
+ assert.equal(await check(port, authority), 407, `tokenless ${authority}`);
assert.equal(await check(port, authority, open), 403, `open-policy ${authority}`);
assert.equal(records.at(-1)?.verdict, "denied");
}
diff --git a/test/external-slack-policy.test.ts b/test/external-slack-policy.test.ts
index 4d242f9b1..1bca19e00 100644
--- a/test/external-slack-policy.test.ts
+++ b/test/external-slack-policy.test.ts
@@ -339,40 +339,6 @@ test("delivery recovery routes private result only through its originating accou
assert.deepEqual(acks, ["delivery"]);
});
-test("external workspace refuses legacy personal-agent approval before reading its stored request", async () => {
- const { createApprovals } = await import("../src/slack/approvals.ts");
- const handlers: Array<{ pattern: RegExp; handler: (args: any) => Promise<void> }> = [];
- const approvals = createApprovals({
- externalAccess: true,
- core: {
- getAgentRequest: async () => {
- throw new Error("legacy private request read");
- },
- } as never,
- flow: {} as never,
- directory: {} as never,
- threads: {} as never,
- ids: {} as never,
- });
- approvals.registerActions({
- action: (pattern, handler) => {
- handlers.push({ pattern, handler });
- },
- });
- let acknowledged = false;
- await handlers
- .find(({ pattern }) => pattern.test("agent_request_run"))!
- .handler({
- ack: async () => {
- acknowledged = true;
- },
- body: {},
- action: { action_id: "agent_request_run", value: "legacy-private-bridge" },
- client: {},
- });
- assert.equal(acknowledged, true);
-});
-
test("external account poller neither claims default identity nor releases pre-policy answers", async () => {
for (const [hasDefault, target, slackPolicyNamespace] of [
[false, "CSHARED", undefined],
diff --git a/test/slack-agent-requests.test.ts b/test/slack-agent-requests.test.ts
deleted file mode 100644
index 152cba771..000000000
--- a/test/slack-agent-requests.test.ts
+++ /dev/null
@@ -1,414 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import {
- agentRequestMessage,
- createThreadTracker,
- extractAgentRequests,
- stripAgentRequestDirectives,
-} from "../src/slack/lib.ts";
-import { createApprovals } from "../src/slack/approvals.ts";
-import { createTurnFlow } from "../src/slack/turn-flow.ts";
-import {
- createAgentRequestStore,
- type SlackAgentRequestContext,
- type SlackCoreClient,
-} from "../src/api/slack-core-client.ts";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
-import type { TurnResult } from "../src/types.ts";
-import { extractReactions } from "../src/slack/reactions.ts";
-
-test("agentRequestMessage builds a personal-agent approval prompt", () => {
- const msg = agentRequestMessage({
- requestId: "agent-req-1",
- originAgentLabel: "#project-alpha agent",
- targetAgentLabel: "Carol's personal agent",
- task: "Check whether browse-agent works with the personal ANTHROPIC_API_KEY, but do not reveal the key.",
- });
- assert.match(msg.text, /asking Carol's personal agent/);
- const section = msg.blocks.find((b) => b.type === "section") as any;
- assert.match(section.text.text, /#project-alpha agent → Carol's personal agent/);
- const actions = msg.blocks.find((b) => b.type === "actions") as any;
- assert.deepEqual(
- actions.elements.map((e: any) => [e.text.text, e.action_id, e.value]),
- [
- ["Run with my setup", "agent_request_run", "agent-req-1"],
- ["Decline", "agent_request_deny", "agent-req-1"],
- ],
- );
-});
-
-test("extractAgentRequests pulls an ask-agent directive out and strips it from the reply", () => {
- const r = extractAgentRequests(
- "I need Carol's personal setup for that.\n\n[[ask-agent: <@U2> | Check whether browse-agent can use your ANTHROPIC_API_KEY without revealing it.]]",
- );
- assert.deepEqual(r.requests, [
- {
- targetUserId: "U2",
- task: "Check whether browse-agent can use your ANTHROPIC_API_KEY without revealing it.",
- },
- ]);
- assert.equal(r.text, "I need Carol's personal setup for that.");
-});
-
-test("extractAgentRequests handles raw user ids, streamed partial stripping, and code examples", () => {
- assert.deepEqual(extractAgentRequests("[[ask-agent: U2 | run a quick check]]").requests, [
- { targetUserId: "U2", task: "run a quick check" },
- ]);
- assert.equal(stripAgentRequestDirectives("asking [[ask-agent: <@U2> | run it]] now"), "asking now");
- assert.equal(stripAgentRequestDirectives("asking [[ask-agent: <@U2> | run"), "asking ");
-
- const inline = extractAgentRequests("Use `[[ask-agent: <@U2> | task]]` to ask a personal agent.");
- assert.deepEqual(inline.requests, []);
- assert.equal(inline.text, "Use `[[ask-agent: <@U2> | task]]` to ask a personal agent.");
-});
-
-function durableFixture(opts: { turnResults?: TurnResult[]; coreOverrides?: Record<string, unknown> } = {}) {
- const store = new Map<string, SlackAgentRequestContext>();
- const storedApprovals = new Map<string, unknown>();
- const submitted: any[] = [];
- const turnResults = [...(opts.turnResults ?? [])];
- const core = {
- submitTurn: async (body: any) => {
- submitted.push(body);
- return turnResults.shift() ?? ({ status: "ok", reply: "personal result" } as TurnResult);
- },
- ackRunDelivery: async () => {},
- reportRunEditRef: async () => {},
- getApproval: async (id: string) => storedApprovals.get(id) ?? null,
- putAgentRequest: async (id: string, record: SlackAgentRequestContext) => void store.set(id, record),
- getAgentRequest: async (id: string) => store.get(id) ?? null,
- takeAgentRequest: async (id: string) => {
- const record = store.get(id) ?? null;
- store.delete(id);
- return record;
- },
- agentRequestForApproval: async (approvalId: string) => {
- for (const record of store.values()) {
- if (record.approvalRequestIds?.includes(approvalId)) return record;
- }
- return null;
- },
- ...opts.coreOverrides,
- } as unknown as SlackCoreClient;
- const directory = {
- classifyActor: async () => ({ externalId: "[email protected]", displayName: "Carol" }),
- classifyUserCached: async () => ({ actor: { externalId: "[email protected]", displayName: "Carol" } }),
- } as never;
- const posts: any[] = [];
- const updates: any[] = [];
- const ephemerals: any[] = [];
- let nextTs = 0;
- const client = {
- conversations: { open: async () => ({ channel: { id: "D-CAROL" } }) },
- chat: {
- postMessage: async (body: any) => {
- posts.push(body);
- nextTs += 1;
- return { ok: true, ts: `100.${nextTs}` };
- },
- update: async (body: any) => {
- updates.push(body);
- return { ok: true };
- },
- postEphemeral: async (body: any) => {
- ephemerals.push(body);
- return { ok: true };
- },
- },
- };
- const newInstance = () => {
- const approvals = createApprovals({
- core,
- flow: createTurnFlow(core),
- directory,
- threads: createThreadTracker(),
- ids: {} as never,
- });
- const handlers: Array<{ pattern: RegExp; handler: (args: any) => Promise<void> }> = [];
- approvals.registerActions({ action: (pattern, handler) => void handlers.push({ pattern, handler }) });
- const click = (actionId: string, value: string, click2: { user?: string; ts?: string } = {}) =>
- handlers
- .find((h) => h.pattern.test(actionId))!
- .handler({
- ack: async () => {},
- body: {
- user: { id: click2.user ?? "U2" },
- channel: { id: "D-CAROL" },
- ...(click2.ts ? { message: { ts: click2.ts } } : {}),
- },
- action: { action_id: actionId, value },
- client,
- });
- return { approvals, click };
- };
- const postRequest = async () => {
- await newInstance().approvals.postAgentRequests(
- client,
- {
- requesterId: "U1",
- channel: "C1",
- replyThreadTs: "1.1",
- threadOnly: true,
- kind: "channel",
- channelName: "proj",
- audience: [{ externalId: "U2", displayName: "Carol" }],
- },
- [{ targetUserId: "U2", task: "run the check" }],
- );
- const card = posts.find((p) => p.channel === "D-CAROL");
- const actions = card.blocks.find((b: any) => b.type === "actions");
- return { requestId: String(actions.elements[0].value), cardTs: "100.2", statusTs: "100.1" };
- };
- return { core, store, storedApprovals, submitted, posts, updates, ephemerals, client, newInstance, postRequest };
-}
-
-test("a Run click on an instance that did not post the card recovers the request and completes the handoff", async () => {
- const f = durableFixture();
- const { requestId, cardTs, statusTs } = await f.postRequest();
- assert.equal(f.store.size, 1, "posting the card persists the request durably");
- assert.equal(f.store.get(requestId)?.originStatusTs, statusTs);
-
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
-
- assert.equal(f.submitted.length, 1, "the personal turn runs despite the empty in-memory state");
- assert.match(String(f.submitted[0].text), /run the check/);
- const cardEdits = f.updates.filter((u) => u.channel === "D-CAROL" && u.ts === cardTs);
- assert.match(String(cardEdits[0]?.text), /Approved\. Running with Carol's personal agent now/);
- const statusEdits = f.updates.filter((u) => u.channel === "C1" && u.ts === statusTs);
- assert.match(String(statusEdits.at(-1)?.text), /personal result/, "the origin status message carries the outcome");
- assert.equal(f.store.size, 0, "the durable record is settled on resolution");
-});
-
-test("a Deny click after a restart recovers the request and updates both the card and the origin status", async () => {
- const f = durableFixture();
- const { requestId, cardTs, statusTs } = await f.postRequest();
-
- await f.newInstance().click("agent_request_deny", requestId, { ts: cardTs });
-
- assert.equal(f.submitted.length, 0);
- const cardEdit = f.updates.find((u) => u.channel === "D-CAROL" && u.ts === cardTs);
- assert.match(String(cardEdit?.text), /Declined/);
- const statusEdit = f.updates.find((u) => u.channel === "C1" && u.ts === statusTs);
- assert.match(String(statusEdit?.text), /declined the personal-agent handoff/);
- assert.equal(f.store.size, 0);
-});
-
-test("a click on a request that no longer exists anywhere edits the card to the expired notice", async () => {
- const f = durableFixture();
- await f.newInstance().click("agent_request_run", "missing-req", { ts: "42.1" });
- assert.match(String(f.updates[0]?.text), /That agent request expired/);
- assert.equal(f.submitted.length, 0);
-});
-
-test("a click that loses the claim race to another instance stays silent", async () => {
- const f = durableFixture({ coreOverrides: { takeAgentRequest: async () => null } });
- const { requestId, cardTs } = await f.postRequest();
- const updatesBefore = f.updates.length;
-
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
-
- assert.equal(f.submitted.length, 0);
- assert.equal(f.updates.length, updatesBefore);
- assert.equal(f.ephemerals.length, 0);
-});
-
-test("a store outage answers the click with a retry nudge instead of expiring the card", async () => {
- const f = durableFixture({
- coreOverrides: {
- getAgentRequest: async () => {
- throw new Error("db down");
- },
- },
- });
- const { requestId, cardTs } = await f.postRequest();
-
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
-
- assert.equal(f.updates.length, 0);
- assert.match(String(f.ephemerals[0]?.text), /try the button again/);
- assert.equal(f.store.size, 1, "the pending request is left intact");
-});
-
-test("a click by anyone but the target user is rejected and leaves the request pending", async () => {
- const f = durableFixture();
- const { requestId, cardTs } = await f.postRequest();
-
- await f.newInstance().click("agent_request_run", requestId, { user: "U-EVIL", ts: cardTs });
-
- assert.equal(f.submitted.length, 0);
- assert.equal(f.updates.length, 0);
- assert.match(String(f.ephemerals[0]?.text), /Only the person whose personal agent was asked/);
- assert.equal(f.store.size, 1);
-});
-
-test("a handoff fails loudly when the command-approval link cannot be recorded", async () => {
- const f = durableFixture({
- turnResults: [
- {
- status: "pending_approval",
- pendingApprovals: [{ requestId: "req-9", command: "deploy", reason: "flagged" }],
- },
- ],
- });
- const { requestId, cardTs, statusTs } = await f.postRequest();
- const put = f.core.putAgentRequest.bind(f.core);
- f.core.putAgentRequest = async (id: string, record: SlackAgentRequestContext) => {
- if (record.approvalRequestIds?.length) throw new Error("db down");
- await put(id, record);
- };
-
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
-
- const statusEdit = f.updates.filter((u) => u.channel === "C1" && u.ts === statusTs).at(-1);
- assert.match(String(statusEdit?.text), /could not be completed[\s\S]*couldn't be recorded/);
- const approvalCards = f.posts.filter((p) => JSON.stringify(p.blocks ?? []).includes("hilo_allow_once"));
- assert.equal(approvalCards.length, 0, "no approval card is posted without a durable link");
- assert.equal(f.store.size, 0);
-});
-
-test("the agent-request store expires stale records and sweeps them on put", async () => {
- const map = createMemoryMap<SlackAgentRequestContext>();
- const store = createAgentRequestStore(map);
- const record = (id: string, ageMs: number, approvalIds?: string[]): SlackAgentRequestContext => ({
- requestId: id,
- requesterId: "U1",
- targetUserId: "U2",
- originChannel: "C1",
- originThreadOnly: true,
- dmChannel: "D1",
- task: "t",
- originAgentLabel: "o",
- targetAgentLabel: "t",
- createdAt: Date.now() - ageMs,
- ...(approvalIds ? { approvalRequestIds: approvalIds } : {}),
- });
- const eightDays = 8 * 24 * 60 * 60 * 1000;
-
- await map.put("stale", record("stale", eightDays, ["req-old"]));
- assert.equal(await store.getAgentRequest("stale"), null);
- assert.equal(await store.agentRequestForApproval("req-old"), null);
- assert.equal(await store.takeAgentRequest("stale"), null);
-
- await map.put("stale2", record("stale2", eightDays));
- await store.putAgentRequest("fresh", record("fresh", 0, ["req-new"]));
- assert.deepEqual(
- (await map.entries()).map(([id]) => id),
- ["fresh"],
- );
-
- await map.put("stale3", record("stale3", eightDays));
- const brittle = createAgentRequestStore({
- ...map,
- delete: async () => {
- throw new Error("gc hiccup");
- },
- });
- await brittle.putAgentRequest("fresh2", record("fresh2", 0));
- assert.equal((await brittle.getAgentRequest("fresh2"))?.requestId, "fresh2", "a failed sweep never aborts the put");
- assert.equal((await store.getAgentRequest("fresh"))?.requestId, "fresh");
- assert.equal((await store.agentRequestForApproval("req-new"))?.requestId, "fresh");
- assert.equal((await store.takeAgentRequest("fresh"))?.requestId, "fresh");
- assert.equal(await map.get("fresh"), null);
-});
-
-test("a handoff command approval recovered on a fresh instance still reports back to the origin channel", async () => {
- const f = durableFixture({
- turnResults: [
- {
- status: "pending_approval",
- pendingApprovals: [{ requestId: "req-9", command: "deploy", reason: "flagged" }],
- },
- { status: "ok", reply: "deploy finished" },
- ],
- });
- const { requestId, cardTs, statusTs } = await f.postRequest();
-
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
- const continuationId = f.submitted[0].gatewayContext.details.agent_request_id;
- assert.notEqual(continuationId, requestId);
- assert.deepEqual(f.store.get(continuationId)?.approvalRequestIds, ["req-9"]);
- const waiting = f.updates.filter((u) => u.channel === "C1" && u.ts === statusTs);
- assert.match(String(waiting.at(-1)?.text), /approve a command/);
-
- f.storedApprovals.set("req-9", {
- requestId: "req-9",
- command: "deploy",
- reason: "flagged",
- request: { ...f.submitted[0], surface: "slack" },
- });
- await f.newInstance().click("hilo_allow_once", "req-9", { ts: "100.9" });
-
- assert.equal(f.submitted.length, 2, "the approved command re-runs on the fresh instance");
- assert.equal(f.submitted[1].approval.requestId, "req-9");
- const statusEdits = f.updates.filter((u) => u.channel === "C1" && u.ts === statusTs);
- assert.match(String(statusEdits.at(-1)?.text), /deploy finished/, "the origin status message gets the result");
- assert.equal(f.store.size, 0, "the durable record is settled once the handoff completes");
-});
-
-test("a directive wrapped onto a new line or with a long id still files the request and keeps the tail", () => {
- const wrapped = extractAgentRequests("hi [[ask-agent:\n<@U2> | task]] tail text");
- assert.equal(wrapped.requests.length, 1);
- assert.match(wrapped.text, /tail text$/);
- const longId = "<@U2>" + " ".repeat(500);
- const over = extractAgentRequests(`hi [[ask-agent:${longId}| task]] tail text`);
- assert.equal(over.requests.length, 0);
- assert.match(over.text, /tail text$/, "an over-long id is left alone instead of truncating the reply");
-});
-
-test("a react directive followed by a huge whitespace run strips in linear time", () => {
- const start = process.hrtime.bigint();
- extractReactions("thanks [[react:" + " ".repeat(100000) + "]x");
- extractReactions("[[react: eyes]] tail" + " ".repeat(100000) + "no newline");
- assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 200);
-});
-
-test("a malformed closed directive is stripped without filing, and an unrelated ]] later does not resurrect a trailing one", () => {
- const leak = extractAgentRequests(
- "I'll ask [[ask-agent: <@U2> no pipe here]] and also [[ask-agent: <@U3> | real]] done",
- );
- assert.equal(leak.requests.length, 1);
- assert.match(leak.text, /^I'll ask\s+and also\s+done$/);
- const open = extractAgentRequests("see [docs](y)]] then [[ask-agent: <@U2> | never closed");
- assert.equal(open.requests.length, 0);
- assert.equal(open.text, "see [docs](y)]] then");
-});
-
-test("the leftover strip is case-insensitive and safe on non-ASCII text", () => {
- const out = extractAgentRequests("İstanbul plan: İİİ ok [[ask-agent: <@U2> | never closed");
- assert.equal(out.text, "İstanbul plan: İİİ ok");
- assert.equal(out.requests.length, 0);
- const start = process.hrtime.bigint();
- extractAgentRequests(("[[ask-agent:" + "x".repeat(88)).repeat(10000));
- assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 100);
-});
-
-test("an early approval has durable handoff context without making the original Run button reusable", async () => {
- const f = durableFixture();
- const { requestId, cardTs } = await f.postRequest();
- let release!: () => void;
- let started!: () => void;
- const ready = new Promise<void>((resolve) => {
- started = resolve;
- });
- const pending = new Promise<void>((resolve) => {
- release = resolve;
- });
- f.core.submitTurn = async (body) => {
- f.submitted.push(body);
- const continuationId = body.gatewayContext?.details?.agent_request_id;
- assert.equal(typeof continuationId, "string");
- assert.notEqual(continuationId, requestId);
- assert.ok(f.store.has(String(continuationId)));
- assert.equal(f.store.has(requestId), false);
- started();
- await pending;
- return { status: "ok", reply: "done" };
- };
- const first = f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
- await ready;
- await f.newInstance().click("agent_request_run", requestId, { ts: cardTs });
- assert.equal(f.submitted.length, 1);
- release();
- await first;
- assert.equal(f.store.size, 0);
-});
diff --git a/test/slack-approval-context.test.ts b/test/slack-approval-context.test.ts
deleted file mode 100644
index 7b31c3f42..000000000
--- a/test/slack-approval-context.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { resolveAgentRequestTarget } from "../src/slack/approval-context.ts";
-import type { ActorAssertion } from "../src/slack/lib.ts";
-
-const TEAMMATE: ActorAssertion = { externalId: "[email protected]", displayName: "Dana" };
-const REQUESTER: ActorAssertion = { externalId: "[email protected]", displayName: "Amy" };
-const DIRECTIVE_TARGET = "U_DANA";
-const emailBridge = new Map<string, string>([
- ["[email protected]", "U_AMY"],
- ["[email protected]", DIRECTIVE_TARGET],
-]);
-
-test("email mode: a Slack-id directive resolves the co-present teammate when the map is present", () => {
- const target = resolveAgentRequestTarget([REQUESTER, TEAMMATE], DIRECTIVE_TARGET, emailBridge);
- assert.equal(target, TEAMMATE);
-});
-
-test("email mode: dropping the map leaves the same teammate unresolvable (the refusal regression)", () => {
- const target = resolveAgentRequestTarget([REQUESTER, TEAMMATE], DIRECTIVE_TARGET, undefined);
- assert.equal(target, undefined);
-});
-
-test("slack-id mode: a bot/member whose externalId is already the Slack id resolves without a map", () => {
- const bot: ActorAssertion = { externalId: "B_HELPER", isBot: true, displayName: "Helper" };
- assert.equal(resolveAgentRequestTarget([REQUESTER, bot], "B_HELPER"), bot);
-});
-
-test("no audience member matches the directive target", () => {
- assert.equal(resolveAgentRequestTarget([REQUESTER, TEAMMATE], "U_STRANGER", emailBridge), undefined);
-});
diff --git a/test/slack-approval-repost.test.ts b/test/slack-approval-repost.test.ts
index 0a378c30e..2922e2979 100644
--- a/test/slack-approval-repost.test.ts
+++ b/test/slack-approval-repost.test.ts
@@ -52,14 +52,13 @@ function fixture() {
}
: null;
},
- agentRequestForApproval: async () => null,
} as unknown as SlackCoreClient;
const flow = createTurnFlow(core);
const directory = {
classifyActor: async (_client: any, userId: string) => ({ externalId: userId, displayName: userId }),
classifyUserCached: async (_client: any, userId: string) => ({ actor: { externalId: userId } }),
} as never;
- const approvals = createApprovals({ core, flow, directory, threads: createThreadTracker(), ids: {} as never });
+ const approvals = createApprovals({ core, flow, directory, threads: createThreadTracker() });
const handlers: Array<{ pattern: RegExp; handler: ActionHandler }> = [];
approvals.registerActions({ action: (pattern, handler) => void handlers.push({ pattern, handler }) });
const ephemerals: any[] = [];
diff --git a/test/slack-approvals-quarantine.test.ts b/test/slack-approvals-quarantine.test.ts
index d0a5b5640..46e8f137c 100644
--- a/test/slack-approvals-quarantine.test.ts
+++ b/test/slack-approvals-quarantine.test.ts
@@ -25,7 +25,7 @@ function fixture(results: { submit: TurnResult; wait: TurnResult | null }) {
classifyActor: async () => ({ externalId: "U1", displayName: "Alice" }),
classifyUserCached: async () => ({ actor: { externalId: "U1", displayName: "Alice" } }),
} as never;
- const approvals = createApprovals({ core, flow, directory, threads: createThreadTracker(), ids: {} as never });
+ const approvals = createApprovals({ core, flow, directory, threads: createThreadTracker() });
const handlers: Array<{ pattern: RegExp; handler: ActionHandler }> = [];
approvals.registerActions({ action: (pattern, handler) => void handlers.push({ pattern, handler }) });
approvals.rememberSlackApprovals([{ requestId: "req-1", command: "rm -rf /tmp/x", reason: "destructive" }], {
diff --git a/test/slack-dev-introspection.test.ts b/test/slack-dev-introspection.test.ts
index 3f1d35564..e04a61d5e 100644
--- a/test/slack-dev-introspection.test.ts
+++ b/test/slack-dev-introspection.test.ts
@@ -176,7 +176,7 @@ test("lastActivityAt tracks dispatched turns and interactions but never canary t
dev.markEvent();
const afterReaction = dev.state.lastActivityAt;
assert.ok(afterReaction);
- emitFrame(app, { type: "interactive", payload: { actions: [{ action_id: "agent_request_approve" }] } });
+ emitFrame(app, { type: "interactive", payload: { actions: [{ action_id: "hilo_allow_once" }] } });
assert.ok((dev.state.lastActivityAt ?? 0) >= (afterReaction ?? 0));
const before = dev.state.lastActivityAt;
await new Promise((r) => setTimeout(r, 5));
diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.ts
index 301a29ac5..89066ee11 100644
--- a/test/slack-index.integration.test.ts
+++ b/test/slack-index.integration.test.ts
@@ -1,7 +1,6 @@
import assert from "node:assert/strict";
import { mock, test } from "node:test";
import type { SlackCoreClient } from "../src/slack/index.ts";
-import type { SlackAgentRequestContext } from "../src/api/slack-core-client.ts";
import type { TurnResult } from "../src/types.ts";
type Handler = (args: any) => Promise<void>;
@@ -338,24 +337,7 @@ class FakeCore implements SlackCoreClient {
async getApproval(): Promise<null> {
return null;
}
- readonly agentRequests = new Map<string, SlackAgentRequestContext>();
- async putAgentRequest(requestId: string, record: SlackAgentRequestContext): Promise<void> {
- this.agentRequests.set(requestId, record);
- }
- async getAgentRequest(requestId: string): Promise<SlackAgentRequestContext | null> {
- return this.agentRequests.get(requestId) ?? null;
- }
- async takeAgentRequest(requestId: string): Promise<SlackAgentRequestContext | null> {
- const record = this.agentRequests.get(requestId) ?? null;
- this.agentRequests.delete(requestId);
- return record;
- }
- async agentRequestForApproval(approvalRequestId: string): Promise<SlackAgentRequestContext | null> {
- for (const record of this.agentRequests.values()) {
- if (record.approvalRequestIds?.includes(approvalRequestId)) return record;
- }
- return null;
- }
+
async pushDirectory(body: any): Promise<boolean> {
this.directories.push(body);
return true;
diff --git a/test/slack-reactions.test.ts b/test/slack-reactions.test.ts
index 7bd977a59..a4ad75791 100644
--- a/test/slack-reactions.test.ts
+++ b/test/slack-reactions.test.ts
@@ -482,3 +482,10 @@ test("a given message's encoded id is STABLE — the same ts always encodes to t
const ts = "1717360800.000100";
assert.equal(encodeTs(ts), encodeTs(ts));
});
+
+test("a react directive followed by a huge whitespace run strips in linear time", () => {
+ const start = process.hrtime.bigint();
+ extractReactions("thanks [[react:" + " ".repeat(100000) + "]x");
+ extractReactions("[[react: eyes]] tail" + " ".repeat(100000) + "no newline");
+ assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 200);
+});
diff --git a/test/slack-session-status.test.ts b/test/slack-session-status.test.ts
index aa02b4570..2cb9e7a29 100644
--- a/test/slack-session-status.test.ts
+++ b/test/slack-session-status.test.ts
@@ -360,7 +360,6 @@ test("core engagement is signaled once for local or durable replies, never quiet
turnStream: stream,
tasks: { list: async () => [] },
app: { getRun: async () => ({ result: { status: "silent" } }) },
- agentRequests: createMemoryMap(),
} as unknown as SlackCoreClientDeps);
await core.waitRun("r1", {
onReplying: () => {