Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
refactor: slack agent tools (#2171)
Maximilian Kaskeaaba345ba8e8
diff --git a/apps/server/src/routes/slack/agent.ts b/apps/server/src/routes/slack/agent.tsindex e06b0bf97..793ee38ec 100644--- a/apps/server/src/routes/slack/agent.ts+++ b/apps/server/src/routes/slack/agent.ts@@ -1,7 +1,17 @@import type { Workspace } from "@openstatus/db/src/schema/workspaces/validation";+import type { ServiceContext } from "@openstatus/services";import { generateText, stepCountIs } from "ai";import type { ModelMessage } from "ai";-import { createTools } from "./tools";++import { buildSlackTools } from "./registry-runner";++// Vercel AI Gateway model id. Override via SLACK_AGENT_MODEL when rolling+// out a new Sonnet version. Dotted format (`4.6`, not `4-6`) is what the+// gateway accepts — see `apps/dashboard/src/app/api/chat/route.ts`.+const DEFAULT_MODEL = "anthropic/claude-sonnet-4.6";+// `||` (not `??`) so empty / whitespace-only env values fall back to the+// default rather than being passed through to `generateText`.+const MODEL = process.env.SLACK_AGENT_MODEL?.trim() || DEFAULT_MODEL;interface SlackThreadMessage {user?: string;@@ -15,30 +25,39 @@ interface AgentResult {}export function buildSystemPrompt(workspaceName: string): string {+ // Intentional: a per-call ISO timestamp defeats Anthropic/Gateway+ // prompt caching, but the agent needs minute-level precision to parse+ // relative times like "next Friday from 2-3 PM". Slack agent volume is+ // low; the latency/cost trade is acceptable. If this ever becomes hot,+ // move the timestamp to the first user message so the rest of the+ // system prompt can cache.const now = new Date().toISOString();return `You are the OpenStatus assistant for workspace "${workspaceName}".The current date and time is: ${now} (UTC).You help teams create and manage status reports and maintenance windows through Slack.IMPORTANT: You have NO knowledge of this workspace's data. NEVER guess or make up IDs (page IDs, component IDs, report IDs). You MUST call the appropriate tool first to get real data.-- Questions about pages or components -> call listStatusPages FIRST-- Questions about reports -> call listStatusReports FIRST-- Questions about maintenances -> call listMaintenances FIRST-- Creating a report -> you MUST call listStatusPages first to get the real pageId, then call createStatusReport with that pageId-- Scheduling maintenance -> you MUST call listStatusPages first to get the real pageId, then call createMaintenance with that pageId-- NEVER pass a pageId you did not receive from listStatusPages. Guessing a pageId WILL cause an error.+- Questions about pages or components -> call list_status_pages FIRST+- Questions about reports -> call list_status_reports FIRST+- Questions about maintenances -> call list_maintenances FIRST+- Creating a report -> you MUST call list_status_pages first to get the real pageId, then call create_status_report with that pageId+- Scheduling maintenance -> you MUST call list_status_pages first to get the real pageId, then call create_maintenance with that pageId+- Components live on a specific page — call list_page_components({ pageId }) to discover pageComponentIds.+- NEVER pass a pageId you did not receive from list_status_pages. Guessing a pageId WILL cause an error.Capabilities:-- Create status reports on status pages (createStatusReport)-- Publish progress updates to existing reports (addStatusReportUpdate)-- Edit report metadata like title or components (updateStatusReport)+- Create status reports on status pages (create_status_report)+- Publish progress updates to existing reports (add_status_report_update)+- Edit report metadata like title or components (update_status_report)+- Resolve active reports (resolve_status_report)- List active status reports and status pages-- Schedule maintenance windows (createMaintenance)-- List upcoming maintenance windows (listMaintenances)+- Schedule maintenance windows (create_maintenance)+- List upcoming maintenance windows (list_maintenances)-Lifecycle: createStatusReport once -> addStatusReportUpdate repeatedly -> resolved.-- "provide an update", "we found the cause", "resolve it" -> addStatusReportUpdate-- "rename the report", "add a component" -> updateStatusReport (metadata only)+Lifecycle: create_status_report once -> add_status_report_update repeatedly -> resolve_status_report.+- "provide an update", "we found the cause" -> add_status_report_update+- "it's fixed", "resolve it" -> resolve_status_report+- "rename the report", "add a component" -> update_status_report (metadata only)Guidelines:- If multiple status pages exist, ask which one to use. If only one, use it automatically.@@ -86,8 +105,17 @@ export async function runAgent(thread: SlackThreadMessage[],botUserId: string,userText?: string,+ origin?: { slackUserId: string; teamId: string | undefined },): Promise<AgentResult> {- const tools = createTools(workspace);+ const ctx: ServiceContext = {+ workspace,+ actor: {+ type: "slack",+ teamId: origin?.teamId ?? "",+ slackUserId: origin?.slackUserId ?? "",+ },+ };+ const tools = buildSlackTools(ctx);let messages = convertThreadToMessages(thread, botUserId);if (messages.length === 0 && userText) {@@ -102,7 +130,7 @@ export async function runAgent(}const result = await generateText({- model: "anthropic/claude-sonnet-4.5",+ model: MODEL,system: buildSystemPrompt(workspace.name ?? "Unknown"),messages,tools,diff --git a/apps/server/src/routes/slack/blocks.test.ts b/apps/server/src/routes/slack/blocks.test.tsindex a1a0bcfd6..2c296e5a4 100644--- a/apps/server/src/routes/slack/blocks.test.ts+++ b/apps/server/src/routes/slack/blocks.test.ts@@ -1,75 +1,79 @@import { describe, expect, test } from "bun:test";-import { buildConfirmationBlocks } from "./blocks";-import type { PendingAction } from "./confirmation-store";+import { agentTools } from "@openstatus/services/agent-tools";++import {+ buildConfirmationBlocks,+ getConfirmationText,+ parseActionId,+} from "./blocks";describe("buildConfirmationBlocks", () => {- test("createStatusReport includes 3 buttons", () => {- const action: PendingAction["action"] = {- type: "createStatusReport",- params: {+ test("create_status_report has approve / approve_flag / cancel", () => {+ const tool = agentTools.create_status_report;+ const blocks = buildConfirmationBlocks({+ actionId: "abc123",+ tool,+ input: {title: "API Outage",status: "investigating",message: "API is returning 500 errors",pageId: 1,+ pageComponentIds: [],},- };-- const blocks = buildConfirmationBlocks("abc123", action);+ });const section = blocks.find((b) => b.type === "section");expect(section).toBeDefined();expect((section as { text: { text: string } }).text.text).toContain("API Outage",);- expect((section as { text: { text: string } }).text.text).toContain(- "Investigating",- );const actions = blocks.find((b) => b.type === "actions") as {- elements: { action_id: string }[];+ elements: { action_id: string; text: { text: string } }[];};expect(actions.elements).toHaveLength(3);expect(actions.elements[0].action_id).toBe("approve_abc123");- expect(actions.elements[1].action_id).toBe("approve_notify_abc123");+ expect(actions.elements[1].action_id).toBe("approve_flag_abc123");+ expect(actions.elements[1].text.text).toBe("Approve & Notify subscribers");expect(actions.elements[2].action_id).toBe("cancel_abc123");});- test("createStatusReport shows components when provided", () => {- const action: PendingAction["action"] = {- type: "createStatusReport",- params: {+ test("create_status_report shows components when provided", () => {+ const tool = agentTools.create_status_report;+ const blocks = buildConfirmationBlocks({+ actionId: "id1",+ tool,+ input: {title: "Test",status: "investigating",message: "msg",pageId: 1,- pageComponentIds: ["comp-1", "comp-2"],+ pageComponentIds: [101, 102],},- };-- const blocks = buildConfirmationBlocks("id1", action);+ });const section = blocks.find((b) => b.type === "section") as {text: { text: string };};- expect(section.text.text).toContain("comp-1, comp-2");+ expect(section.text.text).toContain("101, 102");});- test("addStatusReportUpdate includes 3 buttons", () => {- const action: PendingAction["action"] = {- type: "addStatusReportUpdate",- params: {+ test("add_status_report_update has 3 buttons", () => {+ const tool = agentTools.add_status_report_update;+ const blocks = buildConfirmationBlocks({+ actionId: "abc",+ tool,+ input: {statusReportId: 42,status: "identified",message: "Root cause found",},- };-- const blocks = buildConfirmationBlocks("abc", action);+ });const section = blocks.find((b) => b.type === "section") as {text: { text: string };};expect(section.text.text).toContain("42");- expect(section.text.text).toContain("Identified");+ expect(section.text.text).toContain("identified");const actions = blocks.find((b) => b.type === "actions") as {elements: { action_id: string }[];@@ -77,16 +81,56 @@ describe("buildConfirmationBlocks", () => {expect(actions.elements).toHaveLength(3);});- test("updateStatusReport includes 2 buttons (no notify)", () => {- const action: PendingAction["action"] = {- type: "updateStatusReport",- params: {- statusReportId: 10,- title: "Updated Title",- },- };+ test("update_status_report distinguishes 'clear all' from 'no change' for components", () => {+ const tool = agentTools.update_status_report;++ // pageComponentIds undefined → no Components line at all+ const noChange = buildConfirmationBlocks({+ actionId: "u1",+ tool,+ input: { statusReportId: 10, title: "X" },+ });+ const noChangeText = (+ noChange.find((b) => b.type === "section") as {+ text: { text: string };+ }+ ).text.text;+ expect(noChangeText).not.toContain("Components");- const blocks = buildConfirmationBlocks("xyz", action);+ // pageComponentIds: [] → "(clear all)"+ const clearAll = buildConfirmationBlocks({+ actionId: "u2",+ tool,+ input: { statusReportId: 10, pageComponentIds: [] },+ });+ const clearAllText = (+ clearAll.find((b) => b.type === "section") as {+ text: { text: string };+ }+ ).text.text;+ expect(clearAllText).toContain("(clear all)");++ // pageComponentIds: [1,2] → list+ const withIds = buildConfirmationBlocks({+ actionId: "u3",+ tool,+ input: { statusReportId: 10, pageComponentIds: [1, 2] },+ });+ const withIdsText = (+ withIds.find((b) => b.type === "section") as {+ text: { text: string };+ }+ ).text.text;+ expect(withIdsText).toContain("1, 2");+ });++ test("update_status_report has 2 buttons (no notify flag)", () => {+ const tool = agentTools.update_status_report;+ const blocks = buildConfirmationBlocks({+ actionId: "xyz",+ tool,+ input: { statusReportId: 10, title: "Updated Title" },+ });const section = blocks.find((b) => b.type === "section") as {text: { text: string };@@ -101,16 +145,36 @@ describe("buildConfirmationBlocks", () => {expect(actions.elements[1].action_id).toBe("cancel_xyz");});- test("resolveStatusReport includes 3 buttons", () => {- const action: PendingAction["action"] = {- type: "resolveStatusReport",- params: {- statusReportId: 5,- message: "Issue has been resolved",+ test("create_maintenance card shows pageId", () => {+ const tool = agentTools.create_maintenance;+ const blocks = buildConfirmationBlocks({+ actionId: "m1",+ tool,+ input: {+ title: "DB Upgrade",+ message: "Restarting replicas",+ from: "2026-06-01T00:00:00Z",+ to: "2026-06-01T01:00:00Z",+ pageId: 7,+ pageComponentIds: [],},- };+ });+ const text = (+ blocks.find((b) => b.type === "section") as {+ text: { text: string };+ }+ ).text.text;+ expect(text).toContain("Page ID");+ expect(text).toContain("7");+ });- const blocks = buildConfirmationBlocks("res1", action);+ test("resolve_status_report has 3 buttons", () => {+ const tool = agentTools.resolve_status_report;+ const blocks = buildConfirmationBlocks({+ actionId: "res1",+ tool,+ input: { statusReportId: 5, message: "Issue has been resolved" },+ });const section = blocks.find((b) => b.type === "section") as {text: { text: string };@@ -125,17 +189,95 @@ describe("buildConfirmationBlocks", () => {});test("all blocks include a divider", () => {- const action: PendingAction["action"] = {- type: "createStatusReport",- params: {+ const tool = agentTools.create_status_report;+ const blocks = buildConfirmationBlocks({+ actionId: "d1",+ tool,+ input: {title: "T",status: "investigating",message: "m",pageId: 1,+ pageComponentIds: [],},- };-- const blocks = buildConfirmationBlocks("d1", action);+ });expect(blocks.some((b) => b.type === "divider")).toBe(true);});});++describe("getConfirmationText", () => {+ test("uses summarize().title for tools with approval", () => {+ expect(+ getConfirmationText({+ tool: agentTools.create_status_report,+ input: {+ title: "API Outage",+ status: "investigating",+ message: "m",+ pageId: 1,+ pageComponentIds: [],+ },+ }),+ ).toBe("Create Status Report: API Outage");+ });++ test("update_status_report includes the new title when provided", () => {+ expect(+ getConfirmationText({+ tool: agentTools.update_status_report,+ input: { statusReportId: 1, title: "Renamed" },+ }),+ ).toBe("Update Status Report: Renamed");+ });++ test("resolve_status_report has a fixed title", () => {+ expect(+ getConfirmationText({+ tool: agentTools.resolve_status_report,+ input: { statusReportId: 1, message: "fixed" },+ }),+ ).toBe("Resolve Status Report");+ });+});++describe("buildConfirmationBlocks (error paths)", () => {+ test("throws when the tool has no approval metadata", () => {+ const readTool = agentTools.list_status_pages;+ expect(() =>+ buildConfirmationBlocks({ actionId: "x", tool: readTool, input: {} }),+ ).toThrow(/no approval metadata/);+ });+});++describe("parseActionId", () => {+ test("approve_<id>", () => {+ expect(parseActionId("approve_abc")).toEqual({+ kind: "approve",+ flag: false,+ pendingId: "abc",+ });+ });+ test("approve_flag_<id>", () => {+ expect(parseActionId("approve_flag_abc")).toEqual({+ kind: "approve",+ flag: true,+ pendingId: "abc",+ });+ });+ test("legacy approve_notify_<id> maps to flag=true (in-flight deploy compat)", () => {+ expect(parseActionId("approve_notify_abc")).toEqual({+ kind: "approve",+ flag: true,+ pendingId: "abc",+ });+ });+ test("cancel_<id>", () => {+ expect(parseActionId("cancel_abc")).toEqual({+ kind: "cancel",+ pendingId: "abc",+ });+ });+ test("unknown prefix returns undefined", () => {+ expect(parseActionId("foo_abc")).toBeUndefined();+ });+});diff --git a/apps/server/src/routes/slack/blocks.ts b/apps/server/src/routes/slack/blocks.tsindex 32bb83dbb..338ea8acd 100644--- a/apps/server/src/routes/slack/blocks.ts+++ b/apps/server/src/routes/slack/blocks.ts@@ -1,4 +1,4 @@-import type { PendingAction } from "./confirmation-store";+import type { AnyAgentTool, ExtraFlag } from "@openstatus/services/agent-tools";interface TextObject {type: "plain_text" | "mrkdwn";@@ -28,226 +28,126 @@ interface ButtonElement {style?: "primary" | "danger";}-type Block = SectionBlock | ActionsBlock | DividerBlock;+export type Block = SectionBlock | ActionsBlock | DividerBlock;-export function buildConfirmationBlocks(- actionId: string,- action: PendingAction["action"],-): Block[] {- const blocks: Block[] = [];+/**+ * Action-id encoding. We need to round-trip both the pending action's id+ * and (when the tool declares one) the user's extraFlag choice. The+ * scheme is `<action>_<actionId>` with two affirmative actions when an+ * extraFlag exists: `approve` (flag off) and `approve_flag` (flag on).+ */+export function approveActionId(actionId: string): string {+ return `approve_${actionId}`;+}+export function approveWithFlagActionId(actionId: string): string {+ return `approve_flag_${actionId}`;+}+export function cancelActionId(actionId: string): string {+ return `cancel_${actionId}`;+}- switch (action.type) {- case "createStatusReport": {- const { title, status, message, pageId, pageComponentIds } =- action.params;- blocks.push({- type: "section",- text: {- type: "mrkdwn",- text: `*Create Status Report*\n\n*Title:* ${title}\n*Status:* ${capitalize(status)}\n*Page ID:* ${pageId}${- pageComponentIds?.length- ? `\n*Components:* ${pageComponentIds.join(", ")}`- : ""- }\n*Message:* ${message}`,- },- });- blocks.push({ type: "divider" });- blocks.push({- type: "actions",- elements: [- {- type: "button",- text: { type: "plain_text", text: "Approve", emoji: true },- action_id: `approve_${actionId}`,- style: "primary",- },- {- type: "button",- text: {- type: "plain_text",- text: "Approve & Notify",- emoji: true,- },- action_id: `approve_notify_${actionId}`,- style: "primary",- },- {- type: "button",- text: { type: "plain_text", text: "Cancel", emoji: true },- action_id: `cancel_${actionId}`,- style: "danger",- },- ],- });- break;- }- case "addStatusReportUpdate": {- const { statusReportId, status, message } = action.params;- blocks.push({- type: "section",- text: {- type: "mrkdwn",- text: `*Add Status Report Update*\n\n*Report ID:* ${statusReportId}\n*New Status:* ${capitalize(status)}\n*Message:* ${message}`,- },- });- blocks.push({ type: "divider" });- blocks.push({- type: "actions",- elements: [- {- type: "button",- text: { type: "plain_text", text: "Approve", emoji: true },- action_id: `approve_${actionId}`,- style: "primary",- },- {- type: "button",- text: {- type: "plain_text",- text: "Approve & Notify",- emoji: true,- },- action_id: `approve_notify_${actionId}`,- style: "primary",- },- {- type: "button",- text: { type: "plain_text", text: "Cancel", emoji: true },- action_id: `cancel_${actionId}`,- style: "danger",- },- ],- });- break;- }- case "updateStatusReport": {- const { statusReportId, title, pageComponentIds } = action.params;- let text = `*Update Status Report*\n\n*Report ID:* ${statusReportId}`;- if (title) text += `\n*New Title:* ${title}`;- if (pageComponentIds?.length)- text += `\n*Components:* ${pageComponentIds.join(", ")}`;- blocks.push({ type: "section", text: { type: "mrkdwn", text } });- blocks.push({ type: "divider" });- blocks.push({- type: "actions",- elements: [- {- type: "button",- text: { type: "plain_text", text: "Approve", emoji: true },- action_id: `approve_${actionId}`,- style: "primary",- },- {- type: "button",- text: { type: "plain_text", text: "Cancel", emoji: true },- action_id: `cancel_${actionId}`,- style: "danger",- },- ],- });- break;- }- case "resolveStatusReport": {- const { statusReportId, message } = action.params;- blocks.push({- type: "section",- text: {- type: "mrkdwn",- text: `*Resolve Status Report*\n\n*Report ID:* ${statusReportId}\n*Message:* ${message}`,- },- });- blocks.push({ type: "divider" });- blocks.push({- type: "actions",- elements: [- {- type: "button",- text: { type: "plain_text", text: "Approve", emoji: true },- action_id: `approve_${actionId}`,- style: "primary",- },- {- type: "button",- text: {- type: "plain_text",- text: "Approve & Notify",- emoji: true,- },- action_id: `approve_notify_${actionId}`,- style: "primary",- },- {- type: "button",- text: { type: "plain_text", text: "Cancel", emoji: true },- action_id: `cancel_${actionId}`,- style: "danger",- },- ],- });- break;- }- case "createMaintenance": {- const { title, message, from, to, pageComponentIds } = action.params;- blocks.push({- type: "section",- text: {- type: "mrkdwn",- text: `*Schedule Maintenance*\n\n*Title:* ${title}\n*From:* ${formatDate(from)}\n*To:* ${formatDate(to)}${- pageComponentIds?.length- ? `\n*Components:* ${pageComponentIds.join(", ")}`- : ""- }\n*Message:* ${message}`,- },- });- blocks.push({ type: "divider" });- blocks.push({- type: "actions",- elements: [- {- type: "button",- text: { type: "plain_text", text: "Approve", emoji: true },- action_id: `approve_${actionId}`,- style: "primary",- },- {- type: "button",- text: {- type: "plain_text",- text: "Approve & Notify",- emoji: true,- },- action_id: `approve_notify_${actionId}`,- style: "primary",- },- {- type: "button",- text: { type: "plain_text", text: "Cancel", emoji: true },- action_id: `cancel_${actionId}`,- style: "danger",- },- ],- });- break;- }- }+export type ParsedActionId =+ | { kind: "approve"; flag: false; pendingId: string }+ | { kind: "approve"; flag: true; pendingId: string }+ | { kind: "cancel"; pendingId: string };- return blocks;+export function parseActionId(actionId: string): ParsedActionId | undefined {+ // Legacy: cards rendered before the registry-runner deploy used+ // `approve_notify_<id>`. Map to flag=true so the carrier lookup at+ // least surfaces ":x: This action has expired" — without this branch+ // the click would be silently dropped, leaving the card stale-but-+ // interactive. Bounded by the 5-min TTL; safe to remove afterwards.+ if (actionId.startsWith("approve_notify_")) {+ return {+ kind: "approve",+ flag: true,+ pendingId: actionId.slice("approve_notify_".length),+ };+ }+ if (actionId.startsWith("approve_flag_")) {+ return {+ kind: "approve",+ flag: true,+ pendingId: actionId.slice("approve_flag_".length),+ };+ }+ if (actionId.startsWith("approve_")) {+ return {+ kind: "approve",+ flag: false,+ pendingId: actionId.slice("approve_".length),+ };+ }+ if (actionId.startsWith("cancel_")) {+ return {+ kind: "cancel",+ pendingId: actionId.slice("cancel_".length),+ };+ }+ return undefined;}-function formatDate(iso: string): string {- const d = new Date(iso);- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleString("en-US", {- weekday: "short",- year: "numeric",- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- timeZoneName: "short",+/**+ * Build the Block Kit confirmation card from a tool's `approval.summarize()`.+ * Two affirmative buttons when an extraFlag exists; one otherwise.+ */+export function buildConfirmationBlocks(args: {+ actionId: string;+ tool: AnyAgentTool;+ input: unknown;+}): Block[] {+ const { actionId, tool, input } = args;+ if (!tool.approval) {+ throw new Error(+ `slack blocks: tool "${tool.name}" has no approval metadata`,+ );+ }+ const summary = tool.approval.summarize(input);+ const flag: ExtraFlag | undefined = tool.approval.extraFlags?.[0];++ const lines = summary.lines.map((l) => `*${l.label}:* ${l.value}`).join("\n");++ const buttons: ButtonElement[] = [+ {+ type: "button",+ text: { type: "plain_text", text: "Approve", emoji: true },+ action_id: approveActionId(actionId),+ style: "primary",+ },+ ];+ if (flag) {+ buttons.push({+ type: "button",+ text: {+ type: "plain_text",+ text: `Approve & ${flag.label}`,+ emoji: true,+ },+ action_id: approveWithFlagActionId(actionId),+ style: "primary",+ });+ }+ buttons.push({+ type: "button",+ text: { type: "plain_text", text: "Cancel", emoji: true },+ action_id: cancelActionId(actionId),+ style: "danger",});++ return [+ {+ type: "section",+ text: { type: "mrkdwn", text: `*${summary.title}*\n\n${lines}` },+ },+ { type: "divider" },+ { type: "actions", elements: buttons },+ ];}-function capitalize(s: string): string {- return s.charAt(0).toUpperCase() + s.slice(1);+export function getConfirmationText(args: {+ tool: AnyAgentTool;+ input: unknown;+}): string {+ if (!args.tool.approval) return `Confirm ${args.tool.name}`;+ return args.tool.approval.summarize(args.input).title;}diff --git a/apps/server/src/routes/slack/confirmation-store.test.ts b/apps/server/src/routes/slack/confirmation-store.test.tsindex c9d8b2bce..5af0d8a10 100644--- a/apps/server/src/routes/slack/confirmation-store.test.ts+++ b/apps/server/src/routes/slack/confirmation-store.test.ts@@ -14,15 +14,14 @@ const redisStore = (globalThis as Record<string, unknown>)function makePendingInput(): Omit<PendingAction, "id" | "createdAt"> {return {workspaceId: 1,- limits: {},botToken: "xoxb-test-token",channelId: "C123",threadTs: "1234567890.123456",messageTs: "1234567890.654321",userId: "U123",- action: {- type: "createStatusReport",- params: {+ payload: {+ toolName: "create_status_report",+ input: {title: "Test Incident",status: "investigating",message: "We are investigating",@@ -57,7 +56,7 @@ describe("confirmation-store", () => {const stored = JSON.parse(redisStore.get(actionKey) as string);expect(stored.id).toBe(id);expect(stored.workspaceId).toBe(1);- expect(stored.action.type).toBe("createStatusReport");+ expect(stored.payload.toolName).toBe("create_status_report");expect(redisStore.get(threadKey)).toBe(id);});@@ -71,9 +70,8 @@ describe("confirmation-store", () => {const result = await get(id);expect(result).toBeDefined();expect(result?.id).toBe(id);- expect(result?.action.type).toBe("createStatusReport");+ expect(result?.payload.toolName).toBe("create_status_report");- // Keys should still existexpect(redisStore.has(`slack:action:${id}`)).toBe(true);expect(redisStore.has(`slack:thread:${input.threadTs}`)).toBe(true);});@@ -99,7 +97,7 @@ describe("confirmation-store", () => {const result = await consume(id);expect(result).toBeDefined();expect(result?.id).toBe(id);- expect(result?.action.type).toBe("createStatusReport");+ expect(result?.payload.toolName).toBe("create_status_report");expect(redisStore.has(`slack:action:${id}`)).toBe(false);expect(redisStore.has(`slack:thread:${input.threadTs}`)).toBe(false);@@ -143,102 +141,60 @@ describe("confirmation-store", () => {});describe("replace", () => {- test("replaces the action on an existing pending", async () => {+ test("replaces the payload on an existing pending", async () => {const input = makePendingInput();const id = await store(input);- const newAction: PendingAction["action"] = {- type: "addStatusReportUpdate",- params: {+ await replace(id, {+ toolName: "add_status_report_update",+ input: {statusReportId: 42,status: "identified",message: "Root cause found",},- };-- await replace(id, newAction);+ });const result = await consume(id);expect(result).toBeDefined();- expect(result?.action.type).toBe("addStatusReportUpdate");- if (result?.action.type === "addStatusReportUpdate") {- expect(result?.action.params.statusReportId).toBe(42);- }+ expect(result?.payload.toolName).toBe("add_status_report_update");});test("does nothing for unknown id", async () => {await replace("nonexistent", {- type: "resolveStatusReport",- params: { statusReportId: 1, message: "fixed" },+ toolName: "resolve_status_report",+ input: { statusReportId: 1, message: "fixed" },});expect(redisStore.size).toBe(0);});});describe("zod validation", () => {- test("validates all action types", async () => {- const actions: PendingAction["action"][] = [- {- type: "createStatusReport",- params: {- title: "Test",- status: "investigating",- message: "msg",- pageId: 1,- },- },- {- type: "addStatusReportUpdate",- params: {- statusReportId: 1,- status: "identified",- message: "update",- },- },- {- type: "updateStatusReport",- params: { statusReportId: 1, title: "New Title" },- },- {- type: "resolveStatusReport",- params: { statusReportId: 1, message: "resolved" },- },- ];-- for (const action of actions) {- const input = { ...makePendingInput(), action };- const id = await store(input);- const result = await consume(id);- expect(result).toBeDefined();- expect(result?.action.type).toBe(action.type);- }- });-- test("rejects invalid status values", async () => {+ test("rejects payloads missing required fields", async () => {+ // No `payload` field on the persisted shape — must reject.const raw = JSON.stringify({id: "test",workspaceId: 1,- limits: makePendingInput().limits,botToken: "tok",channelId: "C1",threadTs: "1.1",messageTs: "1.2",userId: "U1",createdAt: Date.now(),- action: {- type: "createStatusReport",- params: {- title: "T",- status: "invalid_status",- message: "m",- pageId: 1,- },- },+ action: { type: "old-shape" },});-- redisStore.set("slack:action:bad-status", raw);- const result = await consume("bad-status");+ redisStore.set("slack:action:legacy", raw);+ const result = await consume("legacy");expect(result).toBeUndefined();});++ test("accepts arbitrary input objects (validated downstream)", async () => {+ const input = {+ ...makePendingInput(),+ payload: { toolName: "create_maintenance", input: { foo: "bar" } },+ };+ const id = await store(input);+ const result = await consume(id);+ expect(result?.payload.toolName).toBe("create_maintenance");+ });});});diff --git a/apps/server/src/routes/slack/confirmation-store.ts b/apps/server/src/routes/slack/confirmation-store.tsindex a2c9c4dac..a47835cf3 100644--- a/apps/server/src/routes/slack/confirmation-store.ts+++ b/apps/server/src/routes/slack/confirmation-store.ts@@ -1,87 +1,43 @@import { redis } from "@/libs/clients";-import { limitsSchema } from "@openstatus/db/src/schema/plan/schema";import { nanoid } from "nanoid";import { z } from "zod";-const statusEnum = z.enum([- "investigating",- "identified",- "monitoring",- "resolved",-]);--const createStatusReportActionSchema = z.object({- type: z.literal("createStatusReport"),- params: z.object({- title: z.string(),- status: statusEnum,- message: z.string(),- pageId: z.number(),- pageComponentIds: z.array(z.string()).optional(),- }),+const pendingPayloadSchema = z.object({+ toolName: z.string(),+ // Validated downstream against the registry tool's inputSchema.+ input: z.unknown(),});-const addStatusReportUpdateActionSchema = z.object({- type: z.literal("addStatusReportUpdate"),- params: z.object({- statusReportId: z.number(),- status: statusEnum,- message: z.string(),- }),-});--const updateStatusReportActionSchema = z.object({- type: z.literal("updateStatusReport"),- params: z.object({- statusReportId: z.number(),- title: z.string().optional(),- pageComponentIds: z.array(z.string()).optional(),- }),-});--const resolveStatusReportActionSchema = z.object({- type: z.literal("resolveStatusReport"),- params: z.object({- statusReportId: z.number(),- message: z.string(),- }),-});--const createMaintenanceActionSchema = z.object({- type: z.literal("createMaintenance"),- params: z.object({- title: z.string(),- message: z.string(),- from: z.string(),- to: z.string(),- pageId: z.number(),- pageComponentIds: z.array(z.string()).optional(),- }),-});--const actionSchema = z.discriminatedUnion("type", [- createStatusReportActionSchema,- addStatusReportUpdateActionSchema,- updateStatusReportActionSchema,- resolveStatusReportActionSchema,- createMaintenanceActionSchema,-]);+export type PendingPayload = z.infer<typeof pendingPayloadSchema>;const pendingActionSchema = z.object({id: z.string(),workspaceId: z.number(),- limits: limitsSchema,botToken: z.string(),channelId: z.string(),threadTs: z.string(),messageTs: z.string(),userId: z.string(),createdAt: z.number(),- action: actionSchema,+ payload: pendingPayloadSchema,});export type PendingAction = z.infer<typeof pendingActionSchema>;+/**+ * Storage seam for deferred Slack tool calls. Production wires the+ * Redis-backed implementation; tests wire an in-memory `Map` so the+ * adapter can be exercised without `@/libs/clients`.+ */+export interface CarrierStore {+ put(action: Omit<PendingAction, "id" | "createdAt">): Promise<string>;+ get(id: string): Promise<PendingAction | undefined>;+ /** Atomic getdel — defends against double-click double-execution. */+ consume(id: string): Promise<PendingAction | undefined>;+ findByThread(threadTs: string): Promise<PendingAction | undefined>;+ replace(id: string, payload: PendingPayload): Promise<void>;+}+const TTL_SECONDS = 5 * 60;const ACTION_PREFIX = "slack:action:";const THREAD_PREFIX = "slack:thread:";@@ -96,80 +52,141 @@ function parse(raw: unknown): PendingAction | undefined {return result.data;}-export async function store(- action: Omit<PendingAction, "id" | "createdAt">,-): Promise<string> {- const id = nanoid();- const pending: PendingAction = { ...action, id, createdAt: Date.now() };-- await Promise.all([- redis.set(`${ACTION_PREFIX}${id}`, JSON.stringify(pending), {- ex: TTL_SECONDS,- }),- redis.set(`${THREAD_PREFIX}${action.threadTs}`, id, {- ex: TTL_SECONDS,- }),- ]);-- return id;+export function createRedisCarrierStore(): CarrierStore {+ return {+ async put(action) {+ const id = nanoid();+ const pending: PendingAction = { ...action, id, createdAt: Date.now() };++ await Promise.all([+ redis.set(`${ACTION_PREFIX}${id}`, JSON.stringify(pending), {+ ex: TTL_SECONDS,+ }),+ redis.set(`${THREAD_PREFIX}${action.threadTs}`, id, {+ ex: TTL_SECONDS,+ }),+ ]);++ return id;+ },++ async get(id) {+ const raw = await redis.get<string>(`${ACTION_PREFIX}${id}`);+ if (!raw) return undefined;+ return parse(raw);+ },++ async consume(id) {+ const raw = await redis.getdel<string>(`${ACTION_PREFIX}${id}`);+ if (!raw) return undefined;++ const action = parse(raw);+ if (!action) return undefined;++ // Thread mapping cleanup is best-effort and not part of atomicity.+ await redis.del(`${THREAD_PREFIX}${action.threadTs}`);++ return action;+ },++ async findByThread(threadTs) {+ const actionId = await redis.get<string>(`${THREAD_PREFIX}${threadTs}`);+ if (!actionId) return undefined;++ const raw = await redis.get<string>(`${ACTION_PREFIX}${actionId}`);+ if (!raw) {+ await redis.del(`${THREAD_PREFIX}${threadTs}`);+ return undefined;+ }++ return parse(raw);+ },++ async replace(id, payload) {+ const raw = await redis.get<string>(`${ACTION_PREFIX}${id}`);+ if (!raw) return;++ const existing = parse(raw);+ if (!existing) return;++ existing.payload = payload;+ existing.createdAt = Date.now();++ await Promise.all([+ redis.set(`${ACTION_PREFIX}${id}`, JSON.stringify(existing), {+ ex: TTL_SECONDS,+ }),+ redis.expire(`${THREAD_PREFIX}${existing.threadTs}`, TTL_SECONDS),+ ]);+ },+ };}-export async function get(- actionId: string,-): Promise<PendingAction | undefined> {- const raw = await redis.get<string>(`${ACTION_PREFIX}${actionId}`);- if (!raw) return undefined;- return parse(raw);+/**+ * In-memory carrier for tests. Mirrors the Redis store's contract; no+ * TTL since tests run far faster than 5 minutes.+ */+export function createMemoryCarrierStore(): CarrierStore {+ const actions = new Map<string, PendingAction>();+ const threads = new Map<string, string>();++ return {+ async put(action) {+ const id = nanoid();+ const pending: PendingAction = { ...action, id, createdAt: Date.now() };+ actions.set(id, pending);+ threads.set(action.threadTs, id);+ return id;+ },++ async get(id) {+ return actions.get(id);+ },++ async consume(id) {+ const action = actions.get(id);+ if (!action) return undefined;+ actions.delete(id);+ threads.delete(action.threadTs);+ return action;+ },++ async findByThread(threadTs) {+ const id = threads.get(threadTs);+ if (!id) return undefined;+ const action = actions.get(id);+ if (!action) {+ threads.delete(threadTs);+ return undefined;+ }+ return action;+ },++ async replace(id, payload) {+ const existing = actions.get(id);+ if (!existing) return;+ actions.set(id, {+ ...existing,+ payload,+ createdAt: Date.now(),+ });+ },+ };}-export async function consume(- actionId: string,-): Promise<PendingAction | undefined> {- // Atomic read+delete to prevent double execution from concurrent requests- const raw = await redis.getdel<string>(`${ACTION_PREFIX}${actionId}`);- if (!raw) return undefined;-- const action = parse(raw);- if (!action) return undefined;+// Default singleton — wired everywhere the Slack route runs. Tests can+// swap to memory via the factory.+const defaultStore = createRedisCarrierStore();- // Clean up the thread mapping (best-effort, not critical for atomicity)- await redis.del(`${THREAD_PREFIX}${action.threadTs}`);-- return action;-}--export async function findByThread(+export const store = (+ action: Omit<PendingAction, "id" | "createdAt">,+): Promise<string> => defaultStore.put(action);+export const get = (id: string): Promise<PendingAction | undefined> =>+ defaultStore.get(id);+export const consume = (id: string): Promise<PendingAction | undefined> =>+ defaultStore.consume(id);+export const findByThread = (threadTs: string,-): Promise<PendingAction | undefined> {- const actionId = await redis.get<string>(`${THREAD_PREFIX}${threadTs}`);- if (!actionId) return undefined;-- const raw = await redis.get<string>(`${ACTION_PREFIX}${actionId}`);- if (!raw) {- await redis.del(`${THREAD_PREFIX}${threadTs}`);- return undefined;- }-- return parse(raw);-}--export async function replace(- actionId: string,- newAction: PendingAction["action"],-): Promise<void> {- const raw = await redis.get<string>(`${ACTION_PREFIX}${actionId}`);- if (!raw) return;-- const existing = parse(raw);- if (!existing) return;-- existing.action = newAction;- existing.createdAt = Date.now();-- await Promise.all([- redis.set(`${ACTION_PREFIX}${actionId}`, JSON.stringify(existing), {- ex: TTL_SECONDS,- }),- redis.expire(`${THREAD_PREFIX}${existing.threadTs}`, TTL_SECONDS),- ]);-}+): Promise<PendingAction | undefined> => defaultStore.findByThread(threadTs);+export const replace = (id: string, payload: PendingPayload): Promise<void> =>+ defaultStore.replace(id, payload);diff --git a/apps/server/src/routes/slack/handler.ts b/apps/server/src/routes/slack/handler.tsindex 1a36bbffb..6de76ca48 100644--- a/apps/server/src/routes/slack/handler.ts+++ b/apps/server/src/routes/slack/handler.ts@@ -5,9 +5,10 @@ import { WebClient } from "@slack/web-api";import type { Context } from "hono";import { z } from "zod";import { runAgent } from "./agent";-import { buildConfirmationBlocks } from "./blocks";+import { buildConfirmationBlocks, getConfirmationText } from "./blocks";import { findByThread, replace, store } from "./confirmation-store";-import type { PendingAction } from "./confirmation-store";+import type { PendingPayload } from "./confirmation-store";+import { getRegistryTool, isSlackToolDraft } from "./registry-runner";import { resolveWorkspace } from "./workspace-resolver";const logger = getLogger("api-server");@@ -226,6 +227,7 @@ async function processEvent(body: SlackEvent) {thread,botUserId,event.text,+ { slackUserId: event.user ?? "", teamId },);logger.info("slack agent completed", {@@ -235,12 +237,13 @@ async function processEvent(body: SlackEvent) {toolCalls: result.toolResults.map((tr) => tr.toolName),});- const confirmationResult = result.toolResults.find(- (tr) =>- tr.result &&- typeof tr.result === "object" &&- "needsConfirmation" in tr.result &&- (tr.result as { needsConfirmation: boolean }).needsConfirmation,+ // One pending action per thread (see findByThread/replace below).+ // If the model emits multiple destructive drafts in a single step we+ // only honour the first; the carrier's thread index can't represent+ // a queue, and forcing the user to confirm twice in a row is worse+ // UX than asking them to re-issue the second request.+ const confirmationResult = result.toolResults.find((tr) =>+ isSlackToolDraft(tr.result),);if (confirmationResult) {@@ -256,7 +259,7 @@ async function processEvent(body: SlackEvent) {threadTs,thinkingTs,event.user ?? "",- resolved.workspace,+ resolved.workspace.id,resolved.botToken,confirmationResult,);@@ -303,69 +306,69 @@ async function handleConfirmation(threadTs: string,thinkingTs: string,userId: string,- workspace: { id: number; limits: PendingAction["limits"] },+ workspaceId: number,botToken: string,confirmationResult: { toolName: string; result: unknown },) {- const { params } = confirmationResult.result as {- needsConfirmation: boolean;- params: Record<string, unknown>;- };-- const actionType =- confirmationResult.toolName as PendingAction["action"]["type"];- const action = { type: actionType, params } as PendingAction["action"];+ if (!isSlackToolDraft(confirmationResult.result)) return;+ const draft = confirmationResult.result;+ const tool = getRegistryTool(draft.toolName);+ if (!tool) {+ logger.error("slack: registry tool not found", {+ toolName: draft.toolName,+ });+ await slack.chat.update({+ channel,+ ts: thinkingTs,+ text: ":x: Something went wrong. Please try again.",+ });+ return;+ }+ const payload: PendingPayload = {+ toolName: draft.toolName,+ input: draft.input,+ };+ const text = getConfirmationText({ tool, input: draft.input });++ // findByThread + replace isn't atomic on its own — two concurrent+ // events on the same thread could both see `existing` and race on+ // replace. Atomicity here relies on the `dedup` map at the top of this+ // file suppressing duplicate event_ids, plus Slack's own per-thread+ // event throttling. Cross-process dedup is *not* covered; see note in+ // processedEvents.const existing = await findByThread(threadTs);if (existing) {- await replace(existing.id, action);+ await replace(existing.id, payload);- const blocks = buildConfirmationBlocks(existing.id, action);- await slack.chat.update({- channel,- ts: thinkingTs,- text: getConfirmationText(action),- blocks,+ const blocks = buildConfirmationBlocks({+ actionId: existing.id,+ tool,+ input: draft.input,});+ await slack.chat.update({ channel, ts: thinkingTs, text, blocks });await slack.chat.update({channel,ts: existing.messageTs,- text: getConfirmationText(action),+ text,blocks,});} else {const actionId = await store({- workspaceId: workspace.id,- limits: workspace.limits,+ workspaceId,botToken,channelId: channel,threadTs,messageTs: thinkingTs,userId,- action,+ payload,});- const blocks = buildConfirmationBlocks(actionId, action);- await slack.chat.update({- channel,- ts: thinkingTs,- text: getConfirmationText(action),- blocks,+ const blocks = buildConfirmationBlocks({+ actionId,+ tool,+ input: draft.input,});- }-}--function getConfirmationText(action: PendingAction["action"]): string {- switch (action.type) {- case "createStatusReport":- return `Create Status Report: ${action.params.title}`;- case "addStatusReportUpdate":- return `Add Status Report Update (${action.params.status})`;- case "updateStatusReport":- return `Update Status Report${action.params.title ? `: ${action.params.title}` : ""}`;- case "resolveStatusReport":- return "Resolve Status Report";- case "createMaintenance":- return `Schedule Maintenance: ${action.params.title}`;+ await slack.chat.update({ channel, ts: thinkingTs, text, blocks });}}diff --git a/apps/server/src/routes/slack/interactions.test.ts b/apps/server/src/routes/slack/interactions.test.tsindex 0c376456e..8b91f31b7 100644--- a/apps/server/src/routes/slack/interactions.test.ts+++ b/apps/server/src/routes/slack/interactions.test.ts@@ -10,25 +10,15 @@ process.env.AI_GATEWAY_API_KEY = "test-key";const redisStore = (globalThis as Record<string, unknown>).__testRedisStore as Map<string, string>;-const pendingData = {+const basePending = {id: "pending-123",workspaceId: 1,- limits: {},botToken: "xoxb-test",channelId: "C1",threadTs: "1.1",messageTs: "1.2",userId: "U_OWNER",createdAt: Date.now(),- action: {- type: "createStatusReport" as const,- params: {- title: "Test Incident",- status: "investigating" as const,- message: "Investigating the issue",- pageId: 1,- },- },};mock.module("./workspace-resolver", () => ({@@ -66,9 +56,52 @@ function createTestApp() {return app;}-function seedPendingAction() {- redisStore.set(`slack:action:${pendingData.id}`, JSON.stringify(pendingData));- redisStore.set(`slack:thread:${pendingData.threadTs}`, pendingData.id);+function seedCreateStatusReport(id = "pending-123") {+ const data = {+ ...basePending,+ id,+ payload: {+ toolName: "create_status_report",+ input: {+ title: "Test Incident",+ status: "investigating",+ message: "Investigating the issue",+ pageId: 1,+ pageComponentIds: [],+ },+ },+ };+ redisStore.set(`slack:action:${id}`, JSON.stringify(data));+ redisStore.set(`slack:thread:${data.threadTs}`, id);+ return data;+}++function seedCreateMaintenance(+ id = "maint-001",+ overrides: Record<string, unknown> = {},+) {+ const now = Date.now();+ const data = {+ ...basePending,+ id,+ threadTs: "2.1",+ messageTs: "2.2",+ payload: {+ toolName: "create_maintenance",+ input: {+ title: "DB Maintenance",+ message: "Scheduled database upgrade.",+ from: new Date(now + 86400000).toISOString(),+ to: new Date(now + 86400000 + 3600000).toISOString(),+ pageId: 1,+ pageComponentIds: [],+ ...overrides,+ },+ },+ };+ redisStore.set(`slack:action:${id}`, JSON.stringify(data));+ redisStore.set(`slack:thread:${data.threadTs}`, id);+ return data;}function signAndPost(@@ -95,7 +128,7 @@ function signAndPost(});}-describe("handleSlackInteraction", () => {+describe("handleSlackInteraction (dispatch)", () => {const app = createTestApp();beforeEach(() => {@@ -104,11 +137,7 @@ describe("handleSlackInteraction", () => {});test("returns ok for non-block_actions", async () => {- const res = await signAndPost(app, {- type: "message_action",- actions: [],- });-+ const res = await signAndPost(app, { type: "message_action", actions: [] });expect(res.status).toBe(200);expect(slackCalls).toHaveLength(0);});@@ -122,14 +151,12 @@ describe("handleSlackInteraction", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "unknown_action" }],});-expect(res.status).toBe(200);expect(slackCalls).toHaveLength(0);});test("cancel updates message to cancelled", async () => {- seedPendingAction();-+ seedCreateStatusReport();const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },@@ -138,7 +165,6 @@ describe("handleSlackInteraction", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "cancel_pending-123" }],});-expect(res.status).toBe(200);const cancelCall = slackCalls.find((c) =>@@ -148,8 +174,7 @@ describe("handleSlackInteraction", () => {});test("rejects action from wrong user", async () => {- seedPendingAction();-+ seedCreateStatusReport();const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OTHER" },@@ -158,17 +183,14 @@ describe("handleSlackInteraction", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "approve_pending-123" }],});-expect(res.status).toBe(200);const ephemeral = slackCalls.find((c) => c.method === "postEphemeral");expect(ephemeral).toBeDefined();expect(ephemeral?.args.text as string).toContain("Only the person");-- // Pending action should NOT be consumed — still available for the real owner- expect(redisStore.has(`slack:action:${pendingData.id}`)).toBe(true);+ expect(redisStore.has("slack:action:pending-123")).toBe(true);});- test("shows expired message when pending action not found", async () => {+ test("shows expired message when pending not found", async () => {const res = await signAndPost(app, {type: "block_actions",user: { id: "U1" },@@ -177,7 +199,6 @@ describe("handleSlackInteraction", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "approve_unknown-id" }],});-expect(res.status).toBe(200);const expiredCall = slackCalls.find((c) =>@@ -195,88 +216,27 @@ describe("handleSlackInteraction", () => {team: { id: "T_UNKNOWN" },actions: [{ action_id: "approve_some-id" }],});-expect(res.status).toBe(200);expect(slackCalls).toHaveLength(0);});- test("falls back to workspace resolver when pending has no botToken", async () => {- const noTokenPending = {- ...pendingData,- id: "pending-notoken",- botToken: "",- createdAt: Date.now(),- };- redisStore.set(- `slack:action:${noTokenPending.id}`,- JSON.stringify(noTokenPending),- );-+ test("approve_flag parses flag=true; approve parses flag=false", async () => {+ seedCreateStatusReport();+ // Both prefixes should be accepted; we just verify the dispatcher+ // reaches consume() and isn't tripped by the prefix parser.const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },channel: { id: "C1" },message: { ts: "1.2" },team: { id: "T_KNOWN" },- actions: [{ action_id: "cancel_pending-notoken" }],+ actions: [{ action_id: "approve_flag_pending-123" }],});-expect(res.status).toBe(200);- // Should still work via workspace resolver fallback- const cancelCall = slackCalls.find(- (c) =>- c.method === "update" && (c.args.text as string).includes("Cancelled"),- );- expect(cancelCall).toBeDefined();});- test("returns ok with empty actions array", async () => {- const res = await signAndPost(app, {- type: "block_actions",- user: { id: "U1" },- channel: { id: "C1" },- message: { ts: "1.2" },- team: { id: "T_KNOWN" },- actions: [],- });-- expect(res.status).toBe(200);- expect(slackCalls).toHaveLength(0);- });-- test("parses approve_notify prefix correctly", async () => {- seedPendingAction();-- const res = await signAndPost(app, {- type: "block_actions",- user: { id: "U_OWNER" },- channel: { id: "C1" },- message: { ts: "1.2" },- team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_notify_pending-123" }],- });-- // approve_notify should extract pending ID as "pending-123"- // Since the action exists and user matches, it tries to execute- expect(res.status).toBe(200);- });-- test("returns ok when no team id and no pending", async () => {- const res = await signAndPost(app, {- type: "block_actions",- user: { id: "U1" },- channel: { id: "C1" },- message: { ts: "1.2" },- actions: [{ action_id: "approve_orphan-id" }],- });-- expect(res.status).toBe(200);- expect(slackCalls).toHaveLength(0);- });-- test("cancel consumes pending action from redis", async () => {- seedPendingAction();-+ test("cancel consumes pending from redis", async () => {+ seedCreateStatusReport();await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },@@ -285,13 +245,11 @@ describe("handleSlackInteraction", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "cancel_pending-123" }],});-- // After cancel, the pending action should be consumed from redis- expect(redisStore.has(`slack:action:${pendingData.id}`)).toBe(false);+ expect(redisStore.has("slack:action:pending-123")).toBe(false);});});-describe("createMaintenance execution", () => {+describe("registry-runner execution paths", () => {const app = createTestApp();beforeEach(() => {@@ -299,37 +257,8 @@ describe("createMaintenance execution", () => {redisStore.clear();});- function seedMaintenanceAction(overrides: Record<string, unknown> = {}) {- const data = {- id: "maint-001",- workspaceId: 1,- limits: {},- botToken: "xoxb-test",- channelId: "C1",- threadTs: "2.1",- messageTs: "2.2",- userId: "U_OWNER",- createdAt: Date.now(),- action: {- type: "createMaintenance" as const,- params: {- title: "DB Maintenance",- message: "Scheduled database upgrade.",- from: new Date(Date.now() + 86400000).toISOString(),- to: new Date(Date.now() + 86400000 + 3600000).toISOString(),- pageId: 1,- ...overrides,- },- },- };- redisStore.set(`slack:action:${data.id}`, JSON.stringify(data));- redisStore.set(`slack:thread:${data.threadTs}`, data.id);- return data;- }-- test("approve creates maintenance and shows success", async () => {- seedMaintenanceAction();-+ test("approve create_maintenance shows scheduled success", async () => {+ seedCreateMaintenance();const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },@@ -338,7 +267,6 @@ describe("createMaintenance execution", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "approve_maint-001" }],});-expect(res.status).toBe(200);const successCall = slackCalls.find((c) =>@@ -353,18 +281,16 @@ describe("createMaintenance execution", () => {);});- test("approve_notify creates maintenance and notifies", async () => {- seedMaintenanceAction();-+ test("approve_flag create_maintenance notifies", async () => {+ seedCreateMaintenance();const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },channel: { id: "C1" },message: { ts: "2.2" },team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_notify_maint-001" }],+ actions: [{ action_id: "approve_flag_maint-001" }],});-expect(res.status).toBe(200);const successCall = slackCalls.find((c) =>@@ -374,9 +300,8 @@ describe("createMaintenance execution", () => {expect(successCall).toBeDefined();});- test("cancel does not create maintenance", async () => {- seedMaintenanceAction();-+ test("cancel does not execute the tool", async () => {+ seedCreateMaintenance();const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },@@ -385,7 +310,6 @@ describe("createMaintenance execution", () => {team: { id: "T_KNOWN" },actions: [{ action_id: "cancel_maint-001" }],});-expect(res.status).toBe(200);const cancelCall = slackCalls.find((c) =>@@ -394,140 +318,44 @@ describe("createMaintenance execution", () => {expect(cancelCall).toBeDefined();});- test("shows error when AI hallucinates page id", async () => {- seedMaintenanceAction({ pageId: 99999 });-+ test("ServiceError (stale page id) surfaces typed message", async () => {+ seedCreateMaintenance("maint-bad", { pageId: 99999 });const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },channel: { id: "C1" },message: { ts: "2.2" },team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_maint-001" }],+ actions: [{ action_id: "approve_maint-bad" }],});-expect(res.status).toBe(200);- const errorCall = slackCalls.find(+ const errCall = slackCalls.find((c) =>c.method === "update" &&- (c.args.text as string).includes("Something went wrong"),+ (c.args.text as string).startsWith(":x:") &&+ (c.args.text as string).toLowerCase().includes("not found"),);- expect(errorCall).toBeDefined();+ expect(errCall).toBeDefined();});- test("shows error when from is after to", async () => {+ test("from after to surfaces typed validation error", async () => {const now = Date.now();- seedMaintenanceAction({+ seedCreateMaintenance("maint-bad-time", {from: new Date(now + 7200000).toISOString(),to: new Date(now + 3600000).toISOString(),});-- const res = await signAndPost(app, {- type: "block_actions",- user: { id: "U_OWNER" },- channel: { id: "C1" },- message: { ts: "2.2" },- team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_maint-001" }],- });-- expect(res.status).toBe(200);- const errorCall = slackCalls.find(- (c) =>- c.method === "update" &&- (c.args.text as string).includes("Something went wrong"),- );- expect(errorCall).toBeDefined();- });-- test("creates maintenance with page components", async () => {- seedMaintenanceAction({ pageComponentIds: ["1", "2"] });-- const res = await signAndPost(app, {- type: "block_actions",- user: { id: "U_OWNER" },- channel: { id: "C1" },- message: { ts: "2.2" },- team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_maint-001" }],- });-- expect(res.status).toBe(200);- const successCall = slackCalls.find(- (c) =>- c.method === "update" &&- (c.args.text as string).includes(- "Maintenance *DB Maintenance* scheduled",- ),- );- expect(successCall).toBeDefined();- });-- test("shows error for invalid page component ids", async () => {- seedMaintenanceAction({ pageComponentIds: ["99999"] });-const res = await signAndPost(app, {type: "block_actions",user: { id: "U_OWNER" },channel: { id: "C1" },message: { ts: "2.2" },team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_maint-001" }],+ actions: [{ action_id: "approve_maint-bad-time" }],});-expect(res.status).toBe(200);- const errorCall = slackCalls.find(- (c) =>- c.method === "update" &&- (c.args.text as string).includes("Something went wrong"),- );- expect(errorCall).toBeDefined();- });-- test("does not leak internal error details to user", async () => {- const data = {- id: "maint-001",- workspaceId: 2,- limits: {},- botToken: "xoxb-test",- channelId: "C1",- threadTs: "2.1",- messageTs: "2.2",- userId: "U_OWNER",- createdAt: Date.now(),- action: {- type: "createMaintenance" as const,- params: {- title: "DB Maintenance",- message: "Upgrade.",- from: new Date(Date.now() + 86400000).toISOString(),- to: new Date(Date.now() + 86400000 + 3600000).toISOString(),- pageId: 99999,- },- },- };- redisStore.set(`slack:action:${data.id}`, JSON.stringify(data));- redisStore.set(`slack:thread:${data.threadTs}`, data.id);-- await signAndPost(app, {- type: "block_actions",- user: { id: "U_OWNER" },- channel: { id: "C1" },- message: { ts: "2.2" },- team: { id: "T_KNOWN" },- actions: [{ action_id: "approve_maint-001" }],- });-- const errorCall = slackCalls.find(- (c) =>- c.method === "update" &&- (c.args.text as string).includes("Something went wrong"),+ const errCall = slackCalls.find(+ (c) => c.method === "update" && (c.args.text as string).startsWith(":x:"),);- expect(errorCall).toBeDefined();- const text = errorCall?.args.text as string;- expect(text).not.toContain("Page 99999");- expect(text).not.toContain("ConnectError");- expect(text).not.toContain("select");- expect(text).not.toContain("query");+ expect(errCall).toBeDefined();});});diff --git a/apps/server/src/routes/slack/interactions.ts b/apps/server/src/routes/slack/interactions.tsindex 9b7303c27..ce2252b12 100644--- a/apps/server/src/routes/slack/interactions.ts+++ b/apps/server/src/routes/slack/interactions.ts@@ -1,20 +1,13 @@-import {- createMaintenance,- notifyMaintenance,-} from "@openstatus/services/maintenance";-import {- addStatusReportUpdate,- createStatusReport,- notifyStatusReport,- resolveStatusReport,- updateStatusReport,-} from "@openstatus/services/status-report";+import { ServiceError } from "@openstatus/services";import { WebClient } from "@slack/web-api";import type { Context } from "hono";++import { parseActionId } from "./blocks";import { consume, get } from "./confirmation-store";import type { PendingAction } from "./confirmation-store";-import { getPageUrl, getReportUrl } from "./page-urls";-import { toServiceCtx, toSlackMessage } from "./service-adapter";+import { renderToolResult } from "./presenters";+import { executeRegistryAction, getRegistryTool } from "./registry-runner";+import { toServiceCtx } from "./service-adapter";import { resolveWorkspace } from "./workspace-resolver";interface SlackInteractionPayload {@@ -33,40 +26,23 @@ export async function handleSlackInteraction(c: Context) {return c.json({ ok: true });}- const actionId = payload.actions[0].action_id;+ const parsed = parseActionId(payload.actions[0].action_id);+ if (!parsed) return c.json({ ok: true });+const channelId = payload.channel.id;const messageTs = payload.message.ts;const userId = payload.user.id;const teamId = payload.team?.id;- let type: "approve" | "approve_notify" | "cancel";- let pendingId: string;-- if (actionId.startsWith("approve_notify_")) {- type = "approve_notify";- pendingId = actionId.replace("approve_notify_", "");- } else if (actionId.startsWith("approve_")) {- type = "approve";- pendingId = actionId.replace("approve_", "");- } else if (actionId.startsWith("cancel_")) {- type = "cancel";- pendingId = actionId.replace("cancel_", "");- } else {- return c.json({ ok: true });- }-// Non-atomic read for botToken resolution and authorization checks- const pending = await get(pendingId);+ const pending = await get(parsed.pendingId);let botToken: string | undefined = pending?.botToken;if (!botToken && teamId) {const resolved = await resolveWorkspace(teamId);botToken = resolved?.botToken;}-- if (!botToken) {- return c.json({ ok: true });- }+ if (!botToken) return c.json({ ok: true });const slack = new WebClient(botToken);@@ -89,14 +65,12 @@ export async function handleSlackInteraction(c: Context) {return c.json({ ok: true });}- // Atomic consume — prevents double execution from concurrent requests (e.g. double-click).- // If another request already consumed this action, consume() returns undefined.- const consumed = await consume(pendingId);- if (!consumed) {- return c.json({ ok: true });- }+ // Atomic consume — prevents double execution from concurrent requests+ // (e.g. double-click). If another request already won, return.+ const consumed = await consume(parsed.pendingId);+ if (!consumed) return c.json({ ok: true });- if (type === "cancel") {+ if (parsed.kind === "cancel") {await slack.chat.update({channel: channelId,ts: messageTs,@@ -106,10 +80,13 @@ export async function handleSlackInteraction(c: Context) {return c.json({ ok: true });}- const notify = type === "approve_notify";-try {- await executeAction(consumed, notify, slack, channelId, messageTs, {+ await runAndPresent({+ pending: consumed,+ flag: parsed.flag,+ slack,+ channelId,+ messageTs,slackUserId: userId,teamId,});@@ -118,7 +95,7 @@ export async function handleSlackInteraction(c: Context) {await slack.chat.update({channel: channelId,ts: messageTs,- text: toSlackMessage(err),+ text: errorMessage(err),blocks: [],});}@@ -126,184 +103,64 @@ export async function handleSlackInteraction(c: Context) {return c.json({ ok: true });}-async function executeAction(- pending: PendingAction,- notify: boolean,- slack: WebClient,- channelId: string,- messageTs: string,- origin: { slackUserId: string; teamId: string | undefined },-) {- const { action } = pending;-- // Hoisted out of the switch: every service-backed branch below uses- // the same ctx, and `toServiceCtx` loads the workspace row from the- // db. Computing it once halves the per-action db traffic.- const ctx = await toServiceCtx({- pending,- slackUserId: origin.slackUserId,- teamId: origin.teamId,- });-- switch (action.type) {- case "createStatusReport": {- const { title, status, message, pageId, pageComponentIds } =- action.params;- if (pageId == null) {- throw new Error("pageId is required to create a status report");- }-- const { statusReport: report, initialUpdate } = await createStatusReport({- ctx,- input: {- title,- status,- message,- date: new Date(),- pageId,- pageComponentIds: pageComponentIds?.map((id) => Number(id)) ?? [],- },- });-- if (notify) {- await notifyStatusReport({- ctx,- input: { statusReportUpdateId: initialUpdate.id },- });- }-- const reportUrl = report.pageId- ? await getReportUrl(report.pageId, report.id)- : null;-- await slack.chat.update({- channel: channelId,- ts: messageTs,- text: `:white_check_mark: Status report *${title}* created${notify ? " and subscribers notified" : ""}.${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,- blocks: [],- });- break;- }-- case "addStatusReportUpdate": {- const { statusReportId, status, message } = action.params;- const { statusReport: report, statusReportUpdate: update } =- await addStatusReportUpdate({- ctx,- input: { statusReportId, status, message },- });-- if (notify && report.pageId) {- await notifyStatusReport({- ctx,- input: { statusReportUpdateId: update.id },- });- }-- const reportUrl = report.pageId- ? await getReportUrl(report.pageId, report.id)- : null;-- await slack.chat.update({- channel: channelId,- ts: messageTs,- text: `:white_check_mark: Update added to *${report.title}* (${status})${notify ? " and subscribers notified" : ""}.\n>${message}${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,- blocks: [],- });- break;- }-- case "updateStatusReport": {- const { statusReportId, title, pageComponentIds } = action.params;- const report = await updateStatusReport({- ctx,- input: {- id: statusReportId,- title: title ?? undefined,- pageComponentIds: pageComponentIds- ? pageComponentIds.map((id) => Number(id))- : undefined,- },- });-- await slack.chat.update({- channel: channelId,- ts: messageTs,- text: `:white_check_mark: Status report *${title ?? report.title}* updated.`,- blocks: [],- });- break;- }-- case "resolveStatusReport": {- const { statusReportId, message } = action.params;- const { statusReport: report, statusReportUpdate: update } =- await resolveStatusReport({- ctx,- input: { statusReportId, message },- });-- if (notify && report.pageId) {- await notifyStatusReport({- ctx,- input: { statusReportUpdateId: update.id },- });- }-- const reportUrl = report.pageId- ? await getReportUrl(report.pageId, report.id)- : null;-- await slack.chat.update({- channel: channelId,- ts: messageTs,- text: `:white_check_mark: *${report.title}* resolved${notify ? " and subscribers notified" : ""}.${message ? `\n>${message}` : ""}${reportUrl ? `\n<${reportUrl}|View on status page>` : ""}`,- blocks: [],- });- break;- }+async function runAndPresent(args: {+ pending: PendingAction;+ flag: boolean;+ slack: WebClient;+ channelId: string;+ messageTs: string;+ slackUserId: string;+ teamId: string | undefined;+}) {+ const { pending, flag, slack, channelId, messageTs, slackUserId, teamId } =+ args;+ const tool = getRegistryTool(pending.payload.toolName);+ if (!tool) {+ throw new Error(+ `slack: unknown tool "${pending.payload.toolName}" in pending payload`,+ );+ }- case "createMaintenance": {- const {- title,- message,- from,- to,- pageId: maintenancePageId,- pageComponentIds: maintenanceComponentIds,- } = action.params;+ const ctx = await toServiceCtx({ pending, slackUserId, teamId });+ const flagId = tool.approval?.extraFlags?.[0]?.id;+ const flags: Record<string, boolean> = flagId ? { [flagId]: flag } : {};- const newMaintenance = await createMaintenance({- ctx,- input: {- title,- message,- from: new Date(from),- to: new Date(to),- pageId: maintenancePageId,- pageComponentIds:- maintenanceComponentIds?.map((id) => Number(id)) ?? [],- },- });+ const { input, output } = await executeRegistryAction({+ tool,+ ctx,+ draftInput: pending.payload.input,+ flags,+ });- if (notify) {- await notifyMaintenance({- ctx,- input: { maintenanceId: newMaintenance.id },- });- }+ // Soft contract: tools that declare `extraFlags: [{ id: "notify" }]`+ // SHOULD return `notified: boolean` in their output (see ExtraFlag+ // JSDoc). We read it here because services swallow dispatch failures —+ // falling back to the user's button flag would say "subscribers+ // notified" when dispatch actually failed. The `?? false` keeps us+ // honest if a future tool breaks the convention.+ const notified =+ flagId === "notify"+ ? (output as { notified?: boolean }).notified ?? false+ : false;+ const text = await renderToolResult({+ tool,+ ctx,+ input,+ output,+ notify: notified,+ });- const maintenancePageUrl = newMaintenance.pageId- ? await getPageUrl(newMaintenance.pageId)- : null;+ await slack.chat.update({+ channel: channelId,+ ts: messageTs,+ text,+ blocks: [],+ });+}- await slack.chat.update({- channel: channelId,- ts: messageTs,- text: `:white_check_mark: Maintenance *${title}* scheduled${notify ? " and subscribers notified" : ""}.${maintenancePageUrl ? `\n<${maintenancePageUrl}|View status page>` : ""}`,- blocks: [],- });- break;- }+function errorMessage(err: unknown): string {+ if (err instanceof ServiceError) {+ return `:x: ${err.message}`;}+ return ":x: Something went wrong. Please try again.";}diff --git a/apps/server/src/routes/slack/presenters/default.ts b/apps/server/src/routes/slack/presenters/default.tsnew file mode 100644index 000000000..267ae8923--- /dev/null+++ b/apps/server/src/routes/slack/presenters/default.ts@@ -0,0 +1,29 @@+import type { AnyAgentTool } from "@openstatus/services/agent-tools";++const VERB_PREFIXES: Array<[string, string]> = [+ ["create_", "created"],+ ["update_", "updated"],+ ["resolve_", "resolved"],+ ["add_", "added"],+];++function inferVerb(toolName: string): string {+ const match = VERB_PREFIXES.find(([prefix]) => toolName.startsWith(prefix));+ return match?.[1] ?? "done";+}++/**+ * Fallback presenter. Uses `approval.summarize().title` for the headline+ * and `approval.verb` (or an inference from the tool name) for the verb.+ */+export function defaultPresenter(args: {+ tool: AnyAgentTool;+ input: unknown;+ notify: boolean;+}): string {+ if (!args.tool.approval) return ":white_check_mark: Done.";+ const summary = args.tool.approval.summarize(args.input);+ const verb = args.tool.approval.verb ?? inferVerb(args.tool.name);+ const notifyTail = args.notify ? " Subscribers notified." : "";+ return `:white_check_mark: ${summary.title} ${verb}.${notifyTail}`;+}diff --git a/apps/server/src/routes/slack/presenters/index.ts b/apps/server/src/routes/slack/presenters/index.tsnew file mode 100644index 000000000..fcbcce7f8--- /dev/null+++ b/apps/server/src/routes/slack/presenters/index.ts@@ -0,0 +1,43 @@+import type { ServiceContext } from "@openstatus/services";+import type { AnyAgentTool } from "@openstatus/services/agent-tools";++import { defaultPresenter } from "./default";+import { createMaintenancePresenter } from "./maintenance";+import {+ addStatusReportUpdatePresenter,+ createStatusReportPresenter,+ resolveStatusReportPresenter,+ updateStatusReportPresenter,+} from "./status-report";+import type { Presenter } from "./types";++export const presenters: Record<string, Presenter> = {+ create_status_report: createStatusReportPresenter,+ add_status_report_update: addStatusReportUpdatePresenter,+ update_status_report: updateStatusReportPresenter,+ resolve_status_report: resolveStatusReportPresenter,+ create_maintenance: createMaintenancePresenter,+};++export async function renderToolResult(args: {+ tool: AnyAgentTool;+ ctx: ServiceContext;+ input: unknown;+ output: unknown;+ notify: boolean;+}): Promise<string> {+ const custom = presenters[args.tool.name];+ if (custom) {+ return custom({+ input: args.input,+ output: args.output,+ ctx: args.ctx,+ notify: args.notify,+ });+ }+ return defaultPresenter({+ tool: args.tool,+ input: args.input,+ notify: args.notify,+ });+}diff --git a/apps/server/src/routes/slack/presenters/maintenance.ts b/apps/server/src/routes/slack/presenters/maintenance.tsnew file mode 100644index 000000000..8643cca4a--- /dev/null+++ b/apps/server/src/routes/slack/presenters/maintenance.ts@@ -0,0 +1,18 @@+import type {+ AgentToolInput,+ AgentToolOutput,+} from "@openstatus/services/agent-tools";++import { getPageUrl } from "../page-urls";+import type { Presenter } from "./types";++export const createMaintenancePresenter: Presenter = async ({+ input,+ output,+ notify,+}) => {+ const i = input as AgentToolInput<"create_maintenance">;+ const o = output as AgentToolOutput<"create_maintenance">;+ const url = o.pageId ? await getPageUrl(o.pageId) : null;+ return `:white_check_mark: Maintenance *${i.title}* scheduled${notify ? " and subscribers notified" : ""}.${url ? `\n<${url}|View status page>` : ""}`;+};diff --git a/apps/server/src/routes/slack/presenters/presenters.test.ts b/apps/server/src/routes/slack/presenters/presenters.test.tsnew file mode 100644index 000000000..e689be5be--- /dev/null+++ b/apps/server/src/routes/slack/presenters/presenters.test.ts@@ -0,0 +1,308 @@+import { describe, expect, mock, test } from "bun:test";+import type { ServiceContext } from "@openstatus/services";+import { agentTools } from "@openstatus/services/agent-tools";+import type { AnyAgentTool } from "@openstatus/services/agent-tools";+import { z } from "zod";++// page-urls.ts hits the db; stub before the presenters module loads.+mock.module("../page-urls", () => ({+ getPageUrl: (_pageId: number) =>+ Promise.resolve("https://example.openstatus.dev"),+ getReportUrl: (_pageId: number, reportId: number) =>+ Promise.resolve(`https://example.openstatus.dev/events/report/${reportId}`),+}));++const { defaultPresenter } = await import("./default");+const { renderToolResult } = await import("./index");++const fakeCtx = {+ workspace: { id: 1 },+ actor: { type: "slack", teamId: "T", slackUserId: "U" },+} as unknown as ServiceContext;++describe("defaultPresenter", () => {+ function fakeTool(verb?: string): AnyAgentTool {+ return {+ name: "create_widget",+ description: "x",+ scope: "write",+ destructive: true,+ inputSchema: z.object({ title: z.string() }),+ outputSchema: z.object({ ok: z.boolean() }),+ run: async () => ({ ok: true }),+ approval: {+ summarize: (input) => ({+ title: `New Widget: ${(input as { title: string }).title}`,+ lines: [],+ }),+ verb,+ },+ };+ }++ test("uses approval.verb when set", () => {+ const text = defaultPresenter({+ tool: fakeTool("emitted"),+ input: { title: "Foo" },+ notify: false,+ });+ expect(text).toBe(":white_check_mark: New Widget: Foo emitted.");+ });++ test("infers verb from create_ prefix when not set", () => {+ const text = defaultPresenter({+ tool: fakeTool(),+ input: { title: "Foo" },+ notify: false,+ });+ expect(text).toContain("created.");+ });++ test("appends 'Subscribers notified.' when notify is true", () => {+ const text = defaultPresenter({+ tool: fakeTool("created"),+ input: { title: "Foo" },+ notify: true,+ });+ expect(text).toContain("Subscribers notified.");+ });++ test("fallback for tools without approval", () => {+ const t: AnyAgentTool = {+ name: "z",+ description: "x",+ scope: "write",+ destructive: true,+ inputSchema: z.object({}),+ outputSchema: z.object({}),+ run: async () => ({}),+ };+ expect(defaultPresenter({ tool: t, input: {}, notify: false })).toBe(+ ":white_check_mark: Done.",+ );+ });++ test("verb inference matches each registry prefix", () => {+ const prefixes: Array<[string, string]> = [+ ["create_x", "created"],+ ["update_x", "updated"],+ ["resolve_x", "resolved"],+ ["add_x", "added"],+ ["weird_x", "done"], // unknown prefix+ ];+ for (const [name, verb] of prefixes) {+ const t: AnyAgentTool = {+ name,+ description: "x",+ scope: "write",+ destructive: true,+ inputSchema: z.object({}),+ outputSchema: z.object({}),+ run: async () => ({}),+ approval: {+ summarize: () => ({ title: "Thing", lines: [] }),+ },+ };+ const text = defaultPresenter({ tool: t, input: {}, notify: false });+ if (verb === "done") {+ expect(text).toBe(":white_check_mark: Thing done.");+ } else {+ expect(text).toBe(`:white_check_mark: Thing ${verb}.`);+ }+ }+ });+});++describe("renderToolResult (per-tool override)", () => {+ test("create_status_report uses its custom presenter with report URL", async () => {+ const tool = agentTools.create_status_report;+ const text = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: {+ title: "API Outage",+ status: "investigating",+ message: "We are investigating",+ pageId: 1,+ pageComponentIds: [],+ notify: true,+ },+ output: {+ statusReport: {+ id: 42,+ title: "API Outage",+ status: "investigating",+ pageId: 1,+ createdAt: null,+ },+ initialUpdateId: 100,+ notified: true,+ },+ notify: true,+ });+ expect(text).toContain("Status report *API Outage* created");+ expect(text).toContain("subscribers notified");+ expect(text).toContain("https://example.openstatus.dev/events/report/42");+ });++ test("add_status_report_update uses report title from output (no extra DB read)", async () => {+ const tool = agentTools.add_status_report_update;+ const text = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: {+ statusReportId: 7,+ status: "identified",+ message: "We found the root cause",+ notify: false,+ },+ output: {+ statusReportUpdateId: 99,+ notified: false,+ statusReport: {+ id: 7,+ title: "DB Slowness",+ status: "identified",+ pageId: 2,+ },+ },+ notify: false,+ });+ expect(text).toContain("Update added to *DB Slowness*");+ expect(text).toContain("(identified)");+ expect(text).not.toContain("subscribers notified");+ });++ test("resolve_status_report renders the resolution URL + message", async () => {+ const tool = agentTools.resolve_status_report;+ const text = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: {+ statusReportId: 7,+ message: "All systems healthy",+ notify: true,+ },+ output: {+ statusReportUpdateId: 101,+ notified: true,+ statusReport: { id: 7, title: "DB Slowness", pageId: 2 },+ },+ notify: true,+ });+ expect(text).toContain("*DB Slowness* resolved");+ expect(text).toContain("subscribers notified");+ expect(text).toContain("All systems healthy");+ expect(text).toContain("https://example.openstatus.dev/events/report/7");+ });++ test("create_maintenance includes the page URL", async () => {+ const tool = agentTools.create_maintenance;+ const text = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: {+ title: "DB Upgrade",+ message: "Reading replicas restart",+ from: "2026-06-01T00:00:00Z",+ to: "2026-06-01T01:00:00Z",+ pageId: 3,+ pageComponentIds: [],+ notify: false,+ },+ output: {+ id: 11,+ title: "DB Upgrade",+ from: "2026-06-01T00:00:00Z",+ to: "2026-06-01T01:00:00Z",+ pageId: 3,+ notified: false,+ },+ notify: false,+ });+ expect(text).toContain("Maintenance *DB Upgrade* scheduled");+ expect(text).not.toContain("subscribers notified");+ expect(text).toContain("https://example.openstatus.dev");+ });++ test("update_status_report uses input.title when provided, else output.title", async () => {+ const tool = agentTools.update_status_report;+ const withInputTitle = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: { statusReportId: 1, title: "Renamed" },+ output: { id: 1, title: "Persisted", status: "investigating" },+ notify: false,+ });+ expect(withInputTitle).toBe(+ ":white_check_mark: Status report *Renamed* updated.",+ );++ const withoutInputTitle = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: { statusReportId: 1 },+ output: { id: 1, title: "Persisted", status: "investigating" },+ notify: false,+ });+ expect(withoutInputTitle).toBe(+ ":white_check_mark: Status report *Persisted* updated.",+ );+ });++ test("create_status_report omits 'subscribers notified' when notify=false (e.g. dispatch failed)", async () => {+ const tool = agentTools.create_status_report;+ const text = await renderToolResult({+ tool,+ ctx: fakeCtx,+ input: {+ title: "API Outage",+ status: "investigating",+ message: "Investigating",+ pageId: 1,+ pageComponentIds: [],+ notify: true,+ },+ output: {+ statusReport: {+ id: 42,+ title: "API Outage",+ status: "investigating",+ pageId: 1,+ createdAt: null,+ },+ initialUpdateId: 100,+ // User clicked "Approve & Notify" but the dispatch failed —+ // the service caught it and set notified=false. Call site+ // (interactions.ts) passes notify=false through accordingly.+ notified: false,+ },+ notify: false,+ });+ expect(text).toContain("Status report *API Outage* created");+ expect(text).not.toContain("subscribers notified");+ });++ test("falls back to the default presenter when no override is registered", async () => {+ const t: AnyAgentTool = {+ name: "create_something_new",+ description: "x",+ scope: "write",+ destructive: true,+ inputSchema: z.object({}),+ outputSchema: z.object({}),+ run: async () => ({}),+ approval: {+ summarize: () => ({ title: "Something", lines: [] }),+ },+ };+ const text = await renderToolResult({+ tool: t,+ ctx: fakeCtx,+ input: {},+ output: {},+ notify: false,+ });+ expect(text).toBe(":white_check_mark: Something created.");+ });+});diff --git a/apps/server/src/routes/slack/presenters/status-report.ts b/apps/server/src/routes/slack/presenters/status-report.tsnew file mode 100644index 000000000..044a503a4--- /dev/null+++ b/apps/server/src/routes/slack/presenters/status-report.ts@@ -0,0 +1,52 @@+import type {+ AgentToolInput,+ AgentToolOutput,+} from "@openstatus/services/agent-tools";++import { getReportUrl } from "../page-urls";+import type { Presenter } from "./types";++export const createStatusReportPresenter: Presenter = async ({+ input,+ output,+ notify,+}) => {+ const i = input as AgentToolInput<"create_status_report">;+ const o = output as AgentToolOutput<"create_status_report">;+ const url = o.statusReport.pageId+ ? await getReportUrl(o.statusReport.pageId, o.statusReport.id)+ : null;+ return `:white_check_mark: Status report *${i.title}* created${notify ? " and subscribers notified" : ""}.${url ? `\n<${url}|View on status page>` : ""}`;+};++export const addStatusReportUpdatePresenter: Presenter = async ({+ input,+ output,+ notify,+}) => {+ const i = input as AgentToolInput<"add_status_report_update">;+ const o = output as AgentToolOutput<"add_status_report_update">;+ const url = o.statusReport.pageId+ ? await getReportUrl(o.statusReport.pageId, o.statusReport.id)+ : null;+ return `:white_check_mark: Update added to *${o.statusReport.title}* (${i.status})${notify ? " and subscribers notified" : ""}.\n>${i.message}${url ? `\n<${url}|View on status page>` : ""}`;+};++export const updateStatusReportPresenter: Presenter = ({ input, output }) => {+ const i = input as AgentToolInput<"update_status_report">;+ const o = output as AgentToolOutput<"update_status_report">;+ return `:white_check_mark: Status report *${i.title ?? o.title}* updated.`;+};++export const resolveStatusReportPresenter: Presenter = async ({+ input,+ output,+ notify,+}) => {+ const i = input as AgentToolInput<"resolve_status_report">;+ const o = output as AgentToolOutput<"resolve_status_report">;+ const url = o.statusReport.pageId+ ? await getReportUrl(o.statusReport.pageId, o.statusReport.id)+ : null;+ return `:white_check_mark: *${o.statusReport.title}* resolved${notify ? " and subscribers notified" : ""}.${i.message ? `\n>${i.message}` : ""}${url ? `\n<${url}|View on status page>` : ""}`;+};diff --git a/apps/server/src/routes/slack/presenters/types.ts b/apps/server/src/routes/slack/presenters/types.tsnew file mode 100644index 000000000..b41d0ed30--- /dev/null+++ b/apps/server/src/routes/slack/presenters/types.ts@@ -0,0 +1,15 @@+import type { ServiceContext } from "@openstatus/services";++/**+ * Per-tool presenter. The runner calls it after the registry tool's+ * `run` succeeds; the presenter returns the user-visible chat.update+ * text. Presenters can `await` for status-page URL lookups (the slack+ * route is server-only — `node:*` imports are fine here, unlike inside+ * `@openstatus/services`).+ */+export type Presenter = (args: {+ input: unknown;+ output: unknown;+ ctx: ServiceContext;+ notify: boolean;+}) => Promise<string> | string;diff --git a/apps/server/src/routes/slack/registry-runner.test.ts b/apps/server/src/routes/slack/registry-runner.test.tsnew file mode 100644index 000000000..f55efa569--- /dev/null+++ b/apps/server/src/routes/slack/registry-runner.test.ts@@ -0,0 +1,279 @@+import { describe, expect, test } from "bun:test";+import type { ServiceContext } from "@openstatus/services";+import { agentTools } from "@openstatus/services/agent-tools";+import type { AnyAgentTool } from "@openstatus/services/agent-tools";+import { z } from "zod";++import {+ buildSlackTools,+ deriveDraftSchema,+ executeRegistryAction,+ getRegistryTool,+ isSlackToolDraft,+} from "./registry-runner";++const fakeCtx = {+ workspace: { id: 1 },+ actor: { type: "slack", teamId: "T", slackUserId: "U" },+} as unknown as ServiceContext;++describe("isSlackToolDraft", () => {+ test("accepts a draft with needsConfirmation + toolName", () => {+ expect(+ isSlackToolDraft({+ needsConfirmation: true,+ toolName: "create_status_report",+ input: {},+ }),+ ).toBe(true);+ });++ test("rejects plain tool output", () => {+ expect(isSlackToolDraft({ items: [] })).toBe(false);+ });++ test("rejects null / non-object values", () => {+ expect(isSlackToolDraft(null)).toBe(false);+ expect(isSlackToolDraft("draft")).toBe(false);+ expect(isSlackToolDraft(undefined)).toBe(false);+ });++ test("rejects missing needsConfirmation", () => {+ expect(isSlackToolDraft({ toolName: "x", input: {} })).toBe(false);+ });++ test("rejects needsConfirmation === false", () => {+ expect(+ isSlackToolDraft({+ needsConfirmation: false,+ toolName: "x",+ }),+ ).toBe(false);+ });++ test("rejects non-string toolName", () => {+ expect(+ isSlackToolDraft({+ needsConfirmation: true,+ toolName: 42,+ input: {},+ }),+ ).toBe(false);+ });+});++describe("getRegistryTool", () => {+ test("returns a tool for a registered name", () => {+ const t = getRegistryTool("create_status_report");+ expect(t?.name).toBe("create_status_report");+ });++ test("returns undefined for an unknown name", () => {+ expect(getRegistryTool("not_a_tool")).toBeUndefined();+ });+});++describe("buildSlackTools", () => {+ const tools = buildSlackTools(fakeCtx);++ test("emits an entry for every registry tool", () => {+ for (const name of Object.keys(agentTools)) {+ expect(tools[name], `${name} missing`).toBeDefined();+ }+ });++ test("destructive tools omit extraFlag fields from the LLM-facing schema", () => {+ // Each destructive tool that declares `extraFlags: [{id:"notify"}]`+ // must reject `notify` from its LLM-facing schema, because the user+ // owns that value via Block Kit buttons.+ const t = tools.create_status_report as {+ inputSchema: z.ZodObject<z.ZodRawShape>;+ };+ const shape = t.inputSchema.shape;+ expect("notify" in shape).toBe(false);+ expect("title" in shape).toBe(true);+ expect("pageId" in shape).toBe(true);+ });++ test("destructive tools without extraFlags keep their full schema", () => {+ const t = tools.update_status_report as {+ inputSchema: z.ZodObject<z.ZodRawShape>;+ };+ const shape = t.inputSchema.shape;+ expect("statusReportId" in shape).toBe(true);+ // update_status_report has no notify field at all in the registry, so+ // we just check the schema is intact.+ expect("title" in shape).toBe(true);+ });++ test("deriveDraftSchema throws clearly when inputSchema isn't a ZodObject", () => {+ const badTool: AnyAgentTool = {+ name: "bad_tool",+ description: "x",+ scope: "write",+ destructive: true,+ // ZodUnion has no `.omit()`.+ inputSchema: z.union([+ z.object({ a: z.string() }),+ z.object({ b: z.string() }),+ ]),+ outputSchema: z.object({}),+ run: async () => ({}),+ approval: {+ extraFlags: [{ id: "notify", label: "Notify" }],+ applyFlags: (i, f) => ({ ...(i as object), notify: f.notify }),+ summarize: () => ({ title: "x", lines: [] }),+ },+ };+ expect(() => deriveDraftSchema(badTool)).toThrow(/not a ZodObject/);+ });++ test("deriveDraftSchema is a no-op for tools without extraFlags", () => {+ const t = agentTools.update_status_report;+ expect(deriveDraftSchema(t)).toBe(t.inputSchema);+ });++ test("read tools expose the full registry schema", () => {+ const t = tools.list_status_pages;+ // list_status_pages takes an empty object; the schema is unchanged.+ expect(t.inputSchema).toBe(agentTools.list_status_pages.inputSchema);+ });+});++describe("executeRegistryAction", () => {+ function fakeTool(+ opts: Partial<AnyAgentTool> & {+ run?: AnyAgentTool["run"];+ } = {},+ ): AnyAgentTool {+ return {+ name: "fake_tool",+ description: "fake",+ scope: "write",+ destructive: true,+ inputSchema: z.object({+ message: z.string(),+ notify: z.boolean(),+ }),+ outputSchema: z.object({ ok: z.boolean() }),+ run: async ({ input }) => ({ ok: (input as { notify: boolean }).notify }),+ approval: {+ extraFlags: [{ id: "notify", label: "Notify subscribers" }],+ applyFlags: (input, flags) => ({+ ...(input as object),+ notify: flags.notify ?? false,+ }),+ summarize: () => ({ title: "fake", lines: [] }),+ },+ ...opts,+ } as AnyAgentTool;+ }++ test("injects flag values via applyFlags", async () => {+ const t = fakeTool();+ const { input, output } = await executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { message: "hi" },+ flags: { notify: true },+ });+ expect((input as { notify: boolean }).notify).toBe(true);+ expect((output as { ok: boolean }).ok).toBe(true);+ });++ test("flag=false also flows through", async () => {+ const t = fakeTool();+ const { input } = await executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { message: "hi" },+ flags: { notify: false },+ });+ expect((input as { notify: boolean }).notify).toBe(false);+ });++ test("the full registry schema gates missing flag values", async () => {+ // If applyFlags is missing or returns input without the flag, the+ // registry's strict schema must reject — protecting against silent+ // omissions of `notify`.+ const t = fakeTool({+ approval: {+ // No-op applyFlags that drops `notify`.+ extraFlags: [{ id: "notify", label: "Notify" }],+ applyFlags: (input) => input,+ summarize: () => ({ title: "fake", lines: [] }),+ },+ });+ expect(+ executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { message: "hi" },+ flags: { notify: true },+ }),+ ).rejects.toThrow();+ });++ test("propagates errors from tool.run", async () => {+ const t = fakeTool({+ run: async () => {+ throw new Error("kaboom");+ },+ });+ expect(+ executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { message: "hi" },+ flags: { notify: false },+ }),+ ).rejects.toThrow("kaboom");+ });++ test("non-destructive tools run inline (no HITL gate)", async () => {+ const ran: unknown[] = [];+ const t: AnyAgentTool = {+ name: "no_op",+ description: "x",+ scope: "write",+ destructive: false,+ inputSchema: z.object({ value: z.number() }),+ outputSchema: z.object({ echo: z.number() }),+ run: async ({ input }) => {+ ran.push(input);+ return { echo: (input as { value: number }).value };+ },+ };+ // buildSlackTools spreads `agentTools`, so we test the per-tool+ // helper indirectly: a non-destructive tool's AI SDK execute() runs+ // inline and returns the registry output, not a draft.+ const out = await executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { value: 7 },+ flags: {},+ });+ expect(out.output).toEqual({ echo: 7 });+ expect(ran).toEqual([{ value: 7 }]);+ });++ test("tools without approval pass draftInput through unchanged", async () => {+ const t: AnyAgentTool = {+ name: "no_approval",+ description: "x",+ scope: "write",+ destructive: true,+ inputSchema: z.object({ value: z.number() }),+ outputSchema: z.object({ value: z.number() }),+ run: async ({ input }) => input as { value: number },+ };+ const { input, output } = await executeRegistryAction({+ tool: t,+ ctx: fakeCtx,+ draftInput: { value: 42 },+ flags: {},+ });+ expect(input).toEqual({ value: 42 });+ expect(output).toEqual({ value: 42 });+ });+});diff --git a/apps/server/src/routes/slack/registry-runner.ts b/apps/server/src/routes/slack/registry-runner.tsnew file mode 100644index 000000000..ee294b97f--- /dev/null+++ b/apps/server/src/routes/slack/registry-runner.ts@@ -0,0 +1,128 @@+import type { ServiceContext } from "@openstatus/services";+import {+ type AgentToolName,+ type AnyAgentTool,+ agentTools,+} from "@openstatus/services/agent-tools";+import { type Tool, tool } from "ai";+import { ZodObject, type ZodType, type z } from "zod";++/**+ * Marker shape returned by destructive tool wrappers. The agent handler+ * detects it and posts a Block Kit confirmation card; the user's button+ * click then drives `executeRegistryAction` (see interactions.ts).+ */+export type SlackToolDraft = {+ needsConfirmation: true;+ toolName: string;+ input: unknown;+};++export function isSlackToolDraft(value: unknown): value is SlackToolDraft {+ if (typeof value !== "object" || value === null) return false;+ const v = value as Record<string, unknown>;+ return v.needsConfirmation === true && typeof v.toolName === "string";+}++/**+ * Build the AI SDK tools dictionary backed by the registry. Read tools+ * execute server-side immediately; destructive tools return a draft for+ * the user to approve. The LLM-facing schema for HITL tools omits the+ * extraFlag fields (e.g. `notify`) so the model can't be expected to+ * answer them — the user supplies them via the Block Kit buttons.+ */+export function buildSlackTools(ctx: ServiceContext): Record<string, Tool> {+ const out: Record<string, Tool> = {};+ for (const name of Object.keys(agentTools) as AgentToolName[]) {+ out[name] = buildTool(agentTools[name] as AnyAgentTool, ctx);+ }+ return out;+}++function buildTool(t: AnyAgentTool, ctx: ServiceContext): Tool {+ // HITL is gated on `destructive`, not on scope: a non-destructive+ // write (none today, but conceivable — e.g. an idempotent reconcile)+ // should run inline like reads do.+ if (!t.destructive) {+ return tool({+ description: t.description,+ inputSchema: t.inputSchema,+ execute: async (input: unknown) => {+ const parsed = t.inputSchema.parse(input);+ return t.run({ ctx, input: parsed });+ },+ });+ }++ // Destructive: hide extraFlag fields from the LLM so it can't omit them+ // and so it can't pre-decide a value the user owns. The full schema+ // re-validates after applyFlags on button click.+ const draftSchema = deriveDraftSchema(t);+ return tool({+ description: t.description,+ inputSchema: draftSchema,+ execute: async (input: unknown) => {+ const parsed = draftSchema.parse(input);+ const draft: SlackToolDraft = {+ needsConfirmation: true,+ toolName: t.name,+ input: parsed,+ };+ return draft;+ },+ });+}++/**+ * Return a schema that omits every extraFlag field declared on the tool's+ * approval metadata. Used only for the Slack LLM-facing schema; the+ * registry's strict schema is the source of truth at execute time.+ *+ * Throws if `inputSchema` isn't a ZodObject — `.omit` only exists there,+ * and a union/intersection at the root would otherwise produce a+ * confusing runtime error several frames deep.+ */+export function deriveDraftSchema(t: AnyAgentTool): ZodType {+ const flagIds = t.approval?.extraFlags?.map((f) => f.id) ?? [];+ if (flagIds.length === 0) return t.inputSchema;+ if (!(t.inputSchema instanceof ZodObject)) {+ throw new Error(+ `slack registry: tool "${t.name}" declares extraFlags but inputSchema is not a ZodObject; .omit() is unavailable.`,+ );+ }+ const obj = t.inputSchema as unknown as ZodObject<z.ZodRawShape>;+ const mask: Record<string, true> = {};+ for (const id of flagIds) mask[id] = true;+ return obj.omit(mask) as unknown as ZodType;+}++/**+ * Look up a registry tool by name. Used by the Slack interaction handler+ * when resuming a pending action from the carrier.+ */+export function getRegistryTool(name: string): AnyAgentTool | undefined {+ return (agentTools as Record<string, AnyAgentTool>)[name];+}++/**+ * Drive a pending action through the registry: apply user-supplied flags,+ * parse against the strict registry schema, execute. Returns the parsed+ * input + raw output so the presenter can render. Throws whatever+ * `tool.run` throws — the caller maps it.+ */+export async function executeRegistryAction(args: {+ tool: AnyAgentTool;+ ctx: ServiceContext;+ draftInput: unknown;+ flags: Record<string, boolean>;+}): Promise<{ input: unknown; output: unknown }> {+ const { tool: t, ctx, draftInput, flags } = args;+ const finalInput = t.approval?.applyFlags+ ? t.approval.applyFlags(draftInput, flags)+ : draftInput;+ // Parse against the strict registry schema — this is the boundary+ // that gates `notify` (and any other extraFlag-injected fields).+ const parsed = t.inputSchema.parse(finalInput);+ const output = await t.run({ ctx, input: parsed });+ return { input: parsed, output };+}diff --git a/apps/server/src/routes/slack/service-adapter.ts b/apps/server/src/routes/slack/service-adapter.tsindex 65ae52a8f..003ddedb4 100644--- a/apps/server/src/routes/slack/service-adapter.ts+++ b/apps/server/src/routes/slack/service-adapter.ts@@ -39,24 +39,3 @@ export async function toServiceCtx(args: {requestId: args.requestId,};}--/**- * Convert a service (or unknown) error into a Slack-friendly message.- *- * **Always returns the same generic string: `"Something went wrong.- * Please try again."`** Slack users aren't developers — they don't need- * (and shouldn't see) the specific error detail. The constraint is- * codified by the `does not leak internal error details` test case and- * was the existing pre-services behaviour we need to preserve. Full- * error text still flows to logtape / Sentry via the catch site.- *- * Notable things this intentionally suppresses:- * - `NotFoundError` formats as `"<entity> <id> not found"` — internal- * row IDs have no meaning to Slack users.- * - `ConflictError` / `ValidationError` often carry SQL-ish phrasing- * or internal column names.- * - `ZodError` emits a raw JSON issue list.- */-export function toSlackMessage(_err: unknown): string {- return ":x: Something went wrong. Please try again.";-}diff --git a/apps/server/src/routes/slack/tools/add-status-report-update.ts b/apps/server/src/routes/slack/tools/add-status-report-update.tsdeleted file mode 100644index 631f708c4..000000000--- a/apps/server/src/routes/slack/tools/add-status-report-update.ts+++ /dev/null@@ -1,21 +0,0 @@-import { tool } from "ai";-import { z } from "zod";--export function createAddStatusReportUpdateTool() {- return tool({- description:- "Add a progress update to an existing status report. This creates a new update entry and changes the report's status. Use for progress updates and resolving incidents.",- inputSchema: z.object({- statusReportId: z.number().describe("ID of the status report to update"),- status: z- .enum(["investigating", "identified", "monitoring", "resolved"])- .describe("New status for the report"),- message: z- .string()- .describe("Professional update message for the public status page"),- }),- execute: async (input) => {- return { needsConfirmation: true as const, params: input };- },- });-}diff --git a/apps/server/src/routes/slack/tools/create-maintenance.ts b/apps/server/src/routes/slack/tools/create-maintenance.tsdeleted file mode 100644index bbc2091b9..000000000--- a/apps/server/src/routes/slack/tools/create-maintenance.ts+++ /dev/null@@ -1,35 +0,0 @@-import { tool } from "ai";-import { z } from "zod";--export function createCreateMaintenanceTool() {- return tool({- description:- "Schedule a maintenance window on a status page. IMPORTANT: You MUST call listStatusPages first to get the real pageId — never guess or make up a pageId. Parse natural language dates into ISO 8601 format (e.g. 'next Friday 2-3 PM' -> proper ISO strings). The maintenance will be shown to the user for confirmation before publishing.",- inputSchema: z.object({- title: z.string().describe("Short title for the maintenance window"),- message: z- .string()- .describe(- "Professional maintenance message for the public status page",- ),- from: z- .string()- .describe("Start time in ISO 8601 format (e.g. 2025-03-14T14:00:00Z)"),- to: z- .string()- .describe("End time in ISO 8601 format (e.g. 2025-03-14T15:00:00Z)"),- pageId: z- .number()- .describe(- "ID of the status page — MUST come from listStatusPages, never guess this value",- ),- pageComponentIds: z- .array(z.string())- .optional()- .describe("IDs of affected page components (optional)"),- }),- execute: async (input) => {- return { needsConfirmation: true as const, params: input };- },- });-}diff --git a/apps/server/src/routes/slack/tools/create-status-report.ts b/apps/server/src/routes/slack/tools/create-status-report.tsdeleted file mode 100644index bb277027d..000000000--- a/apps/server/src/routes/slack/tools/create-status-report.ts+++ /dev/null@@ -1,32 +0,0 @@-import { tool } from "ai";-import { z } from "zod";--export function createCreateStatusReportTool() {- return tool({- description:- "Create a new status report. IMPORTANT: You MUST call listStatusPages first to get the real pageId — never guess or make up a pageId. Draft the title and message based on the conversation. The report will be shown to the user for confirmation before publishing.",- inputSchema: z.object({- title: z.string().describe("Short title for the status report"),- status: z- .enum(["investigating", "identified", "monitoring", "resolved"])- .describe("Current status of the incident"),- message: z- .string()- .describe(- "Professional status update message for the public status page",- ),- pageId: z- .number()- .describe(- "ID of the status page — MUST come from listStatusPages, never guess this value",- ),- pageComponentIds: z- .array(z.string())- .optional()- .describe("IDs of affected page components (optional)"),- }),- execute: async (input) => {- return { needsConfirmation: true as const, params: input };- },- });-}diff --git a/apps/server/src/routes/slack/tools/index.ts b/apps/server/src/routes/slack/tools/index.tsdeleted file mode 100644index 91ff1c065..000000000--- a/apps/server/src/routes/slack/tools/index.ts+++ /dev/null@@ -1,22 +0,0 @@-import type { Workspace } from "@openstatus/db/src/schema/workspaces/validation";-import { createAddStatusReportUpdateTool } from "./add-status-report-update";-import { createCreateMaintenanceTool } from "./create-maintenance";-import { createCreateStatusReportTool } from "./create-status-report";-import { createListMaintenancesTool } from "./list-maintenances";-import { createListStatusPagesTool } from "./list-status-pages";-import { createListStatusReportsTool } from "./list-status-reports";-import { createResolveStatusReportTool } from "./resolve-status-report";-import { createUpdateStatusReportTool } from "./update-status-report";--export function createTools(workspace: Workspace) {- return {- listStatusPages: createListStatusPagesTool(workspace.id),- listStatusReports: createListStatusReportsTool(workspace.id),- createStatusReport: createCreateStatusReportTool(),- addStatusReportUpdate: createAddStatusReportUpdateTool(),- updateStatusReport: createUpdateStatusReportTool(),- resolveStatusReport: createResolveStatusReportTool(),- listMaintenances: createListMaintenancesTool(workspace.id),- createMaintenance: createCreateMaintenanceTool(),- };-}diff --git a/apps/server/src/routes/slack/tools/list-maintenances.ts b/apps/server/src/routes/slack/tools/list-maintenances.tsdeleted file mode 100644index 1208bcdb5..000000000--- a/apps/server/src/routes/slack/tools/list-maintenances.ts+++ /dev/null@@ -1,55 +0,0 @@-import { and, asc, db, desc, eq, gt } from "@openstatus/db";-import { maintenance } from "@openstatus/db/src/schema";-import { tool } from "ai";-import { z } from "zod";--export function createListMaintenancesTool(workspaceId: number) {- return tool({- description:- "List maintenance windows for this workspace. By default returns only upcoming maintenances. Use this to check existing scheduled maintenance.",- inputSchema: z.object({- filter: z- .enum(["upcoming", "all"])- .optional()- .describe(- "Filter: 'upcoming' for future maintenances (default), 'all' for everything",- ),- }),- execute: async ({ filter = "upcoming" }) => {- const conditions = [eq(maintenance.workspaceId, workspaceId)];- if (filter === "upcoming") {- conditions.push(gt(maintenance.from, new Date()));- }-- const records = await db- .select({- id: maintenance.id,- title: maintenance.title,- message: maintenance.message,- from: maintenance.from,- to: maintenance.to,- pageId: maintenance.pageId,- })- .from(maintenance)- .where(and(...conditions))- .orderBy(- filter === "upcoming"- ? asc(maintenance.from)- : desc(maintenance.from),- )- .limit(20)- .all();-- return {- maintenances: records.map((r) => ({- id: r.id,- title: r.title,- message: r.message,- from: r.from.toISOString(),- to: r.to.toISOString(),- pageId: r.pageId,- })),- };- },- });-}diff --git a/apps/server/src/routes/slack/tools/list-status-pages.ts b/apps/server/src/routes/slack/tools/list-status-pages.tsdeleted file mode 100644index be79277cd..000000000--- a/apps/server/src/routes/slack/tools/list-status-pages.ts+++ /dev/null@@ -1,48 +0,0 @@-import { db, eq } from "@openstatus/db";-import { page, pageComponent } from "@openstatus/db/src/schema";-import { tool } from "ai";-import { z } from "zod";--export function createListStatusPagesTool(workspaceId: number) {- return tool({- description:- "List all status pages for this workspace, including their components. Use this to find which page and components to use when creating a status report.",- inputSchema: z.object({}),- execute: async () => {- const pages = await db- .select({- id: page.id,- title: page.title,- slug: page.slug,- })- .from(page)- .where(eq(page.workspaceId, workspaceId))- .all();-- const result = await Promise.all(- pages.map(async (p) => {- const components = await db- .select({- id: pageComponent.id,- name: pageComponent.name,- })- .from(pageComponent)- .where(eq(pageComponent.pageId, p.id))- .all();-- return {- id: p.id,- title: p.title,- slug: p.slug,- components: components.map((c) => ({- id: String(c.id),- name: c.name,- })),- };- }),- );-- return { pages: result };- },- });-}diff --git a/apps/server/src/routes/slack/tools/list-status-reports.ts b/apps/server/src/routes/slack/tools/list-status-reports.tsdeleted file mode 100644index 97f1f6d2d..000000000--- a/apps/server/src/routes/slack/tools/list-status-reports.ts+++ /dev/null@@ -1,65 +0,0 @@-import { and, db, desc, eq, ne } from "@openstatus/db";-import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";-import { tool } from "ai";-import { z } from "zod";--export function createListStatusReportsTool(workspaceId: number) {- return tool({- description:- "List status reports for this workspace. By default returns only active (non-resolved) reports. Use this to find existing reports when adding updates or editing.",- inputSchema: z.object({- filter: z- .enum(["active", "all"])- .optional()- .describe(- "Filter: 'active' for non-resolved reports (default), 'all' for everything",- ),- }),- execute: async ({ filter = "active" }) => {- const conditions = [eq(statusReport.workspaceId, workspaceId)];- if (filter === "active") {- conditions.push(ne(statusReport.status, "resolved"));- }-- const reports = await db- .select()- .from(statusReport)- .where(and(...conditions))- .orderBy(desc(statusReport.updatedAt))- .limit(20)- .all();-- const result = await Promise.all(- reports.map(async (r) => {- const latestUpdate = await db- .select({- message: statusReportUpdate.message,- status: statusReportUpdate.status,- date: statusReportUpdate.date,- })- .from(statusReportUpdate)- .where(eq(statusReportUpdate.statusReportId, r.id))- .orderBy(desc(statusReportUpdate.date))- .limit(1)- .get();-- return {- id: r.id,- title: r.title,- status: r.status,- pageId: r.pageId,- latestUpdate: latestUpdate- ? {- message: latestUpdate.message,- status: latestUpdate.status,- date: latestUpdate.date?.toISOString() ?? null,- }- : null,- };- }),- );-- return { reports: result };- },- });-}diff --git a/apps/server/src/routes/slack/tools/resolve-status-report.ts b/apps/server/src/routes/slack/tools/resolve-status-report.tsdeleted file mode 100644index 81428c602..000000000--- a/apps/server/src/routes/slack/tools/resolve-status-report.ts+++ /dev/null@@ -1,20 +0,0 @@-import { tool } from "ai";-import { z } from "zod";--export function createResolveStatusReportTool() {- return tool({- description:- "Resolve an active status report. This marks the incident as resolved and adds a final update message to the public status page.",- inputSchema: z.object({- statusReportId: z.number().describe("ID of the status report to resolve"),- message: z- .string()- .describe(- "Resolution message explaining what was fixed, for the public status page",- ),- }),- execute: async (input) => {- return { needsConfirmation: true as const, params: input };- },- });-}diff --git a/apps/server/src/routes/slack/tools/tools.test.ts b/apps/server/src/routes/slack/tools/tools.test.tsdeleted file mode 100644index 5c4041d00..000000000--- a/apps/server/src/routes/slack/tools/tools.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import { describe, expect, test } from "bun:test";-import type { Workspace } from "@openstatus/db/src/schema/workspaces/validation";-import { createAddStatusReportUpdateTool } from "./add-status-report-update";-import { createCreateStatusReportTool } from "./create-status-report";-import { createTools } from "./index";-import { createUpdateStatusReportTool } from "./update-status-report";--const mockWorkspace = {- id: 1,- name: "Test",- slug: "test",- plan: "free",- limits: {},-} as Workspace;--describe("createTools", () => {- test("returns all expected tool keys", () => {- const tools = createTools(mockWorkspace);- expect(Object.keys(tools).sort()).toEqual([- "addStatusReportUpdate",- "createMaintenance",- "createStatusReport",- "listMaintenances",- "listStatusPages",- "listStatusReports",- "resolveStatusReport",- "updateStatusReport",- ]);- });-});--describe("createCreateStatusReportTool", () => {- const tool = createCreateStatusReportTool();-- test("returns needsConfirmation with params", async () => {- const input = {- title: "API Outage",- status: "investigating" as const,- message: "We are investigating the issue",- pageId: 1,- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result).toEqual({ needsConfirmation: true, params: input });- });-- test("includes optional pageComponentIds", async () => {- const input = {- title: "Outage",- status: "investigating" as const,- message: "msg",- pageId: 1,- pageComponentIds: ["comp-1", "comp-2"],- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result.params.pageComponentIds).toEqual(["comp-1", "comp-2"]);- });-});--describe("createAddStatusReportUpdateTool", () => {- const tool = createAddStatusReportUpdateTool();-- test("returns needsConfirmation with params", async () => {- const input = {- statusReportId: 42,- status: "identified" as const,- message: "Root cause identified",- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result).toEqual({ needsConfirmation: true, params: input });- });-- test("works with resolved status", async () => {- const input = {- statusReportId: 42,- status: "resolved" as const,- message: "Issue has been fixed",- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result.params.status).toBe("resolved");- });-});--describe("createUpdateStatusReportTool", () => {- const tool = createUpdateStatusReportTool();-- test("returns needsConfirmation with title update", async () => {- const input = {- statusReportId: 10,- title: "Updated Title",- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result).toEqual({ needsConfirmation: true, params: input });- });-- test("works with only pageComponentIds", async () => {- const input = {- statusReportId: 10,- pageComponentIds: ["comp-1"],- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result.params.pageComponentIds).toEqual(["comp-1"]);- });-- test("works with both title and components", async () => {- const input = {- statusReportId: 10,- title: "New Title",- pageComponentIds: ["comp-1", "comp-2"],- };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result.params.title).toBe("New Title");- expect(result.params.pageComponentIds).toEqual(["comp-1", "comp-2"]);- });-- test("works with only statusReportId", async () => {- const input = { statusReportId: 10 };- const result = await tool.execute(input, {- toolCallId: "test",- messages: [],- });- expect(result.params.statusReportId).toBe(10);- });-});diff --git a/apps/server/src/routes/slack/tools/update-status-report.ts b/apps/server/src/routes/slack/tools/update-status-report.tsdeleted file mode 100644index 6ce626360..000000000--- a/apps/server/src/routes/slack/tools/update-status-report.ts+++ /dev/null@@ -1,20 +0,0 @@-import { tool } from "ai";-import { z } from "zod";--export function createUpdateStatusReportTool() {- return tool({- description:- "Edit a status report's metadata (title, components). This does NOT add a new update message — use addStatusReportUpdate for that. No subscriber notifications are sent.",- inputSchema: z.object({- statusReportId: z.number().describe("ID of the status report to edit"),- title: z.string().optional().describe("New title for the report"),- pageComponentIds: z- .array(z.string())- .optional()- .describe("Updated list of affected component IDs"),- }),- execute: async (input) => {- return { needsConfirmation: true as const, params: input };- },- });-}diff --git a/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts b/packages/services/src/agent-tools/__tests__/shape-equivalence.test.tsindex 6936b6805..c6bfd1b3d 100644--- a/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts+++ b/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts@@ -4,6 +4,7 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import { loadSeededWorkspace, makeUserCtx } from "../../../test/helpers";import type { ServiceContext } from "../../context";import { agentTools } from "../index";+import type { AnyAgentTool } from "../types";let teamCtx: ServiceContext;@@ -118,3 +119,72 @@ describe("agent-tool shape equivalence", () => {// get_response_log requires a Tinybird row; covered by RPC handler tests.});++describe("approval metadata contract", () => {+ const destructiveTools = Object.values(agentTools).filter(+ (t): t is AnyAgentTool => t.destructive,+ );++ test("every destructive tool declares approval", () => {+ for (const t of destructiveTools) {+ expect(t.approval, `${t.name} missing approval`).toBeDefined();+ }+ });++ test("extraFlags is capped at one entry", () => {+ for (const t of destructiveTools) {+ const flags = t.approval?.extraFlags ?? [];+ expect(flags.length, `${t.name} extraFlags.length`).toBeLessThanOrEqual(+ 1,+ );+ }+ });++ test("extraFlags requires applyFlags", () => {+ for (const t of destructiveTools) {+ if (t.approval?.extraFlags?.length) {+ expect(+ t.approval.applyFlags,+ `${t.name} extraFlags but no applyFlags`,+ ).toBeDefined();+ }+ }+ });++ test("applyFlags injects the declared flag id", () => {+ for (const t of destructiveTools) {+ const flag = t.approval?.extraFlags?.[0];+ if (!flag || !t.approval?.applyFlags) continue;+ const draft = {} as Record<string, unknown>;+ const merged = t.approval.applyFlags(draft, {+ [flag.id]: true,+ }) as Record<string, unknown>;+ expect(merged[flag.id], `${t.name} applyFlags(true)`).toBe(true);+ const merged2 = t.approval.applyFlags(draft, {+ [flag.id]: false,+ }) as Record<string, unknown>;+ expect(merged2[flag.id], `${t.name} applyFlags(false)`).toBe(false);+ }+ });++ test("summarize returns a non-empty title", () => {+ for (const t of destructiveTools) {+ if (!t.approval) continue;+ // Smoke-call with a synthetic input so we just check shape.+ // Real inputs are tool-specific; we use minimal placeholders.+ const placeholder: Record<string, unknown> = {+ title: "t",+ message: "m",+ status: "investigating",+ pageId: 1,+ statusReportId: 1,+ from: new Date().toISOString(),+ to: new Date(Date.now() + 60000).toISOString(),+ pageComponentIds: [],+ };+ const summary = t.approval.summarize(placeholder);+ expect(summary.title.length, `${t.name} title empty`).toBeGreaterThan(0);+ expect(Array.isArray(summary.lines)).toBe(true);+ }+ });+});diff --git a/packages/services/src/agent-tools/index.ts b/packages/services/src/agent-tools/index.tsindex 013ed89e6..f223f37b7 100644--- a/packages/services/src/agent-tools/index.ts+++ b/packages/services/src/agent-tools/index.ts@@ -49,8 +49,11 @@ export type {AgentTool,AgentToolRegistry,AnyAgentTool,+ ApprovalMeta,+ ExtraFlag,InferAgentToolInput,InferAgentToolOutput,+ SummaryLine,} from "./types";export {type AgentSystemPromptOptions,@@ -88,6 +91,22 @@ export const agentTools = {get_audit_log: getAuditLogTool,} satisfies Record<string, AnyAgentTool>;+// Multi-flag confirmation UX should be a modal, not 2^N buttons. Fail+// loudly at module load if anything sneaks in past the tuple type.+for (const tool of Object.values(agentTools) as AnyAgentTool[]) {+ const flags = tool.approval?.extraFlags;+ if (flags && flags.length > 1) {+ throw new Error(+ `agent-tools: "${tool.name}" declares ${flags.length} extraFlags; cap is 1.`,+ );+ }+ if (flags?.length && !tool.approval?.applyFlags) {+ throw new Error(+ `agent-tools: "${tool.name}" declares extraFlags but no applyFlags.`,+ );+ }+}+/*** Iteration view used by adapters that don't care about the literal key.* Equivalent to `Object.values(agentTools)`.diff --git a/packages/services/src/agent-tools/maintenance.ts b/packages/services/src/agent-tools/maintenance.tsindex b6c630e50..5833e350d 100644--- a/packages/services/src/agent-tools/maintenance.ts+++ b/packages/services/src/agent-tools/maintenance.ts@@ -10,6 +10,20 @@ import type { AgentTool } from "./types";const PER_PAGE_DEFAULT = 50;const PER_PAGE_MAX = 200;+function formatMaintenanceDate(iso: string): string {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return iso;+ return d.toLocaleString("en-US", {+ weekday: "short",+ year: "numeric",+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ timeZoneName: "short",+ });+}+const ListMaintenancesInputShape = z.object({pageId: z.number()@@ -146,6 +160,29 @@ export const createMaintenanceTool: AgentTool<destructive: true,inputSchema: CreateMaintenanceInputShape,outputSchema: CreateMaintenanceOutput,+ approval: {+ extraFlags: [{ id: "notify", label: "Notify subscribers" }],+ applyFlags: (input, flags) => ({ ...input, notify: flags.notify ?? false }),+ summarize: (input) => ({+ title: `Schedule Maintenance: ${input.title}`,+ lines: [+ { label: "Title", value: input.title },+ { label: "Page ID", value: String(input.pageId) },+ { label: "From", value: formatMaintenanceDate(input.from) },+ { label: "To", value: formatMaintenanceDate(input.to) },+ ...(input.pageComponentIds?.length+ ? [+ {+ label: "Components",+ value: input.pageComponentIds.join(", "),+ },+ ]+ : []),+ { label: "Message", value: input.message },+ ],+ }),+ verb: "scheduled",+ },async run({ ctx, input }) {const record = await createMaintenance({ctx,diff --git a/packages/services/src/agent-tools/status-report.ts b/packages/services/src/agent-tools/status-report.tsindex 56645d7a4..94a3ac4ca 100644--- a/packages/services/src/agent-tools/status-report.ts+++ b/packages/services/src/agent-tools/status-report.ts@@ -183,6 +183,28 @@ export const createStatusReportTool: AgentTool<destructive: true,inputSchema: CreateStatusReportInputShape,outputSchema: CreateStatusReportOutput,+ approval: {+ extraFlags: [{ id: "notify", label: "Notify subscribers" }],+ applyFlags: (input, flags) => ({ ...input, notify: flags.notify ?? false }),+ summarize: (input) => ({+ title: `Create Status Report: ${input.title}`,+ lines: [+ { label: "Title", value: input.title },+ { label: "Status", value: input.status },+ { label: "Page ID", value: String(input.pageId) },+ ...(input.pageComponentIds?.length+ ? [+ {+ label: "Components",+ value: input.pageComponentIds.join(", "),+ },+ ]+ : []),+ { label: "Message", value: input.message },+ ],+ }),+ verb: "created",+ },async run({ ctx, input }) {const result = await createStatusReport({ctx,@@ -250,6 +272,12 @@ const AddStatusReportUpdateInputShape = z.object({const AddStatusReportUpdateOutput = z.object({statusReportUpdateId: z.number().int(),notified: z.boolean(),+ statusReport: z.object({+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+ pageId: z.number().int().nullable(),+ }),});export const addStatusReportUpdateTool: AgentTool<@@ -263,6 +291,19 @@ export const addStatusReportUpdateTool: AgentTool<destructive: true,inputSchema: AddStatusReportUpdateInputShape,outputSchema: AddStatusReportUpdateOutput,+ approval: {+ extraFlags: [{ id: "notify", label: "Notify subscribers" }],+ applyFlags: (input, flags) => ({ ...input, notify: flags.notify ?? false }),+ summarize: (input) => ({+ title: `Add Status Report Update (${input.status})`,+ lines: [+ { label: "Report ID", value: String(input.statusReportId) },+ { label: "New Status", value: input.status },+ { label: "Message", value: input.message },+ ],+ }),+ verb: "added",+ },async run({ ctx, input }) {const result = await addStatusReportUpdate({ctx,@@ -291,6 +332,12 @@ export const addStatusReportUpdateTool: AgentTool<return {statusReportUpdateId: result.statusReportUpdate.id,notified,+ statusReport: {+ id: result.statusReport.id,+ title: result.statusReport.title,+ status: result.statusReport.status,+ pageId: result.statusReport.pageId,+ },};},};@@ -335,6 +382,32 @@ export const updateStatusReportTool: AgentTool<destructive: true,inputSchema: UpdateStatusReportInputShape,outputSchema: UpdateStatusReportOutput,+ approval: {+ summarize: (input) => {+ const lines: { label: string; value: string }[] = [+ { label: "Report ID", value: String(input.statusReportId) },+ ];+ if (input.title) lines.push({ label: "New Title", value: input.title });+ if (input.status)+ lines.push({ label: "New Status", value: input.status });+ // Distinguish "don't touch components" (undefined) from+ // "clear all associations" ([]). The latter is destructive and+ // MUST be visible on the approval card.+ if (input.pageComponentIds !== undefined) {+ lines.push({+ label: "Components",+ value: input.pageComponentIds.length+ ? input.pageComponentIds.join(", ")+ : "(clear all)",+ });+ }+ return {+ title: `Update Status Report${input.title ? `: ${input.title}` : ""}`,+ lines,+ };+ },+ verb: "updated",+ },async run({ ctx, input }) {const report = await updateStatusReport({ctx,@@ -374,6 +447,11 @@ const ResolveStatusReportInputShape = z.object({const ResolveStatusReportOutput = z.object({statusReportUpdateId: z.number().int(),notified: z.boolean(),+ statusReport: z.object({+ id: z.number().int(),+ title: z.string(),+ pageId: z.number().int().nullable(),+ }),});export const resolveStatusReportTool: AgentTool<@@ -387,6 +465,18 @@ export const resolveStatusReportTool: AgentTool<destructive: true,inputSchema: ResolveStatusReportInputShape,outputSchema: ResolveStatusReportOutput,+ approval: {+ extraFlags: [{ id: "notify", label: "Notify subscribers" }],+ applyFlags: (input, flags) => ({ ...input, notify: flags.notify ?? false }),+ summarize: (input) => ({+ title: "Resolve Status Report",+ lines: [+ { label: "Report ID", value: String(input.statusReportId) },+ { label: "Message", value: input.message },+ ],+ }),+ verb: "resolved",+ },async run({ ctx, input }) {const result = await resolveStatusReport({ctx,@@ -414,6 +504,11 @@ export const resolveStatusReportTool: AgentTool<return {statusReportUpdateId: result.statusReportUpdate.id,notified,+ statusReport: {+ id: result.statusReport.id,+ title: result.statusReport.title,+ pageId: result.statusReport.pageId,+ },};},};diff --git a/packages/services/src/agent-tools/types.ts b/packages/services/src/agent-tools/types.tsindex cbc7c44e4..f9c615b6d 100644--- a/packages/services/src/agent-tools/types.ts+++ b/packages/services/src/agent-tools/types.ts@@ -4,7 +4,7 @@ import type { ZodType, z } from "zod";import type { ServiceContext } from "../context";/**- * Framework-agnostic tool descriptor shared by every adapter (MCP, AI SDK).+ * Framework-agnostic tool descriptor shared by every adapter (MCP, AI SDK, Slack).* `description` is factual; behavioral rubrics live in the system prompt* so per-surface prompts can vary the wording. `destructive` is mirrored* onto MCP `destructiveHint` and used by the AI SDK adapter to enable@@ -19,6 +19,54 @@ export type AgentTool<TInput = unknown, TOutput = unknown> = {inputSchema: ZodType<TInput>;outputSchema: ZodType<TOutput>;run(args: { ctx: ServiceContext; input: TInput }): Promise<TOutput>;++ /**+ * Optional HITL metadata consumed by surfaces that orchestrate approval+ * outside `run()` (today: Slack). MCP relies on `destructiveHint`; the+ * AI SDK uses `needsApproval: t.destructive`. When set, the surface+ * adapter stores the partial input, then re-injects the user's flag+ * choice via `applyFlags` before calling `run`.+ */+ approval?: ApprovalMeta<TInput>;+};++export type ExtraFlag = {+ /**+ * Schema field name injected back into input by `applyFlags`.+ *+ * Convention: when `id === "notify"`, the tool's `outputSchema` SHOULD+ * include `notified: boolean` reporting the actual dispatch outcome+ * (notify failures are typically swallowed, so the input flag and the+ * realized outcome can differ). Surfaces use that field to render+ * "subscribers notified" honestly.+ */+ id: string;+ /** Human-readable button label. */+ label: string;+ /** Default value when the user picks the non-flagged option. Defaults to false. */+ default?: boolean;+};++export type SummaryLine = { label: string; value: string };++export type ApprovalMeta<TInput> = {+ /**+ * Tuple — capped at one flag. Multi-flag UX deserves a modal, not 2^N+ * buttons. The registry validates the cap at module load.+ */+ extraFlags?: [ExtraFlag];+ /**+ * Required whenever `extraFlags` is declared. Returns a new input with+ * the flag value merged in — must not mutate the input.+ */+ applyFlags?: (input: TInput, flags: Record<string, boolean>) => TInput;+ /** Surface-rendered confirmation summary. */+ summarize: (input: TInput) => { title: string; lines: SummaryLine[] };+ /**+ * Past-tense verb for the default presenter ("created", "resolved").+ * Inferred from the tool name when omitted.+ */+ verb?: string;};export type InferAgentToolInput<T> = T extends AgentTool<infer I, unknown>