:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(agent-platform): Slack agent reliability — form-encode API calls, dedupe events, workspace resolution (#64868)
Ben White8af049652df7
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.tsindex cec901b88d0e..44579981cd6e 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts@@ -38,6 +38,8 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {challenge?: stringevent?: SlackEventevent_id?: string+ // `message` events carry the workspace here, not on `event.team`.+ team_id?: string}if (body.type === 'url_verification') {res.json({ challenge: body.challenge })@@ -75,7 +77,8 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {ack_reaction?: string})const trusted = slackConfig.trusted_workspaces- const workspaceId = event.team ?? 'unknown'+ // message events lack event.team; fall back to the envelope team_id.+ const workspaceId = event.team ?? body.team_id ?? 'unknown'if (trusted !== '*' && (!Array.isArray(trusted) || !trusted.includes(workspaceId))) {// The rejected workspace id is otherwise only in the 403 body — surface// it (plus the configured allowlist) so "why is Slack getting a 403?"@@ -231,12 +234,9 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {application: resolved.application,revision: resolved.revision,externalKey,- // Slack retries the events callback up to 3 times if it doesn't see- // a 200 within 3s. `event_id` is Slack's per-event uuid — identical- // across retries, unique per real event — so it's the right- // idempotency key. Falls back to ts when an older payload shape- // doesn't carry event_id.- idempotencyKey: body.event_id ? `slack:event:${body.event_id}` : `slack:ts:${event.ts}`,+ // (channel, ts) = one message: collapses app_mention + message.* and+ // Slack retries (same ts, distinct event_ids) into a single turn.+ idempotencyKey: `slack:msg:${event.channel}:${event.ts}`,seed: { role: 'user', content: slackContext, timestamp: Date.now(), sender: slackPrincipal },principal: slackPrincipal,trigger: 'slack',diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.test.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.test.tsnew file mode 100644index 000000000000..3355d1961255--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.test.ts@@ -0,0 +1,185 @@+import { describe, expect, it } from 'vitest'++import { markdownToMrkdwn } from './slack-mrkdwn'++describe('markdownToMrkdwn', () => {+ describe('emphasis', () => {+ it.each([+ ['**bold**', '*bold*'],+ ['__bold__', '*bold*'],+ ['*italic*', '_italic_'],+ ['_italic_', '_italic_'],+ ['***bolditalic***', '*_bolditalic_*'],+ ['**a** **b**', '*a* *b*'],+ ['**a** and *b*', '*a* and _b_'],+ ['plain **bold** plain *italic* plain', 'plain *bold* plain _italic_ plain'],+ ['**bold _em_ inside**', '*bold _em_ inside*'],+ ['**a *b* c**', '*a _b_ c*'],+ ['**Status:** open', '*Status:* open'],+ ['ends with **bold**', 'ends with *bold*'],+ ['~~struck~~', '~struck~'],+ ['~~a~~ and ~~b~~', '~a~ and ~b~'],+ ['already ~strike~', 'already ~strike~'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })+ })++ describe('headings', () => {+ it.each([+ ['# H1', '*H1*'],+ ['## H2', '*H2*'],+ ['###### H6', '*H6*'],+ ['# extra spaces ', '*extra spaces*'],+ ['## With **bold** in it', '*With bold in it*'],+ ['## See [docs](https://x.io)', '*See <https://x.io|docs>*'],+ ['#nospace', '#nospace'],+ ['text # not a heading', 'text # not a heading'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })+ })++ describe('lists and tasks', () => {+ it.each([+ ['- a', '• a'],+ ['* a', '• a'],+ ['+ a', '• a'],+ ['- **bold** item', '• *bold* item'],+ [' - nested', ' • nested'],+ ['1. first', '1. first'],+ ['1. **bold**', '1. *bold*'],+ ['10. tenth', '10. tenth'],+ ['- [ ] todo', '• ☐ todo'],+ ['- [x] done', '• ☑ done'],+ ['- [X] done caps', '• ☑ done caps'],+ ['-nospace', '-nospace'],+ ['a - b', 'a - b'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })++ it('a multi-line list', () => {+ expect(markdownToMrkdwn('- one\n* two\n+ three')).toBe('• one\n• two\n• three')+ })+ })++ describe('links and images', () => {+ it.each([+ ['[t](https://x.io)', '<https://x.io|t>'],+ ['[t](https://x.io "title")', '<https://x.io|t>'],+ ['[t](https://x.io?a=1&b=2)', '<https://x.io?a=1&b=2|t>'],+ ['', '<https://img.png>'],+ ['', '<https://img.png>'],+ [' then [b](l.io)', '<i.png> then <l.io|b>'],+ ['[**bold link**](https://x.io)', '<https://x.io|*bold link*>'],+ ['**[t](https://x.io)**', '*<https://x.io|t>*'],+ ['bare https://x.io stays', 'bare https://x.io stays'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })+ })++ describe('code is shielded', () => {+ it.each([+ ['use `code` here', 'use `code` here'],+ ['`**not bold**`', '`**not bold**`'],+ ['`# not heading`', '`# not heading`'],+ ['`a` and `b`', '`a` and `b`'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })++ it('leaves fenced blocks (and their markdown) untouched', () => {+ expect(markdownToMrkdwn('```\n**x**\n- y\n# z\n```')).toBe('```\n**x**\n- y\n# z\n```')+ })++ it('leaves a language-tagged fence untouched', () => {+ expect(markdownToMrkdwn('```ts\nconst a = `**x**`\n```')).toBe('```ts\nconst a = `**x**`\n```')+ })++ it('converts around a fenced block but not inside', () => {+ expect(markdownToMrkdwn('**before**\n```\n**inside**\n```\n**after**')).toBe(+ '*before*\n```\n**inside**\n```\n*after*'+ )+ })+ })++ describe('blockquotes and rules', () => {+ it.each([+ ['> quote', '> quote'],+ ['> **important**', '> *important*'],+ ['---', '──────────'],+ ['***', '──────────'],+ ['___', '──────────'],+ ['----', '──────────'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })+ })++ describe('no false positives on literal punctuation', () => {+ it.each([+ ['snake_case_var', 'snake_case_var'],+ ['a_b_c_d', 'a_b_c_d'],+ ['2 * 3 = 6', '2 * 3 = 6'],+ ['plain text', 'plain text'],+ ['', ''],+ [' ', ' '],+ ['emoji 🎉 and :smile:', 'emoji 🎉 and :smile:'],+ ['**unclosed', '**unclosed'],+ ['a > b comparison', 'a > b comparison'],+ ])('%j -> %j', (input, expected) => {+ expect(markdownToMrkdwn(input)).toBe(expected)+ })+ })++ describe('realistic mixed messages', () => {+ it('a kudos-bot style digest', () => {+ const md = [+ '# Kudos — week of Jun 16',+ '',+ '- **Alice** → **Bob**: shipped the _migration_ early',+ '- **Carol** → **Dan**: caught a [regression](https://gh.io/pr/1)',+ '',+ '---',+ '',+ 'See `pinned-kudos.md` for the full list.',+ ].join('\n')+ const out = markdownToMrkdwn(md)+ expect(out).toContain('*Kudos — week of Jun 16*')+ expect(out).toContain('• *Alice* → *Bob*: shipped the _migration_ early')+ expect(out).toContain('caught a <https://gh.io/pr/1|regression>')+ expect(out).toContain('──────────')+ expect(out).toContain('`pinned-kudos.md`')+ expect(out).not.toContain('**')+ })++ it('an idea card like the screenshot', () => {+ const md =+ '**Self-Building Documentation Bot** (`self-building-documentation-bot`)\n\n' ++ '> A documentation bot that installs anywhere.\n\n' ++ '- **Status:** open\n- **Feasibility:** High\n\n---\n\nGot more ideas? 👀'+ const out = markdownToMrkdwn(md)+ expect(out).toContain('*Self-Building Documentation Bot* (`self-building-documentation-bot`)')+ expect(out).toContain('> A documentation bot that installs anywhere.')+ expect(out).toContain('• *Status:* open')+ expect(out).toContain('──────────')+ expect(out).not.toContain('**')+ expect(out).not.toContain('---')+ })+ })++ // Documented limitations — Slack has no equivalent / a real parser would be+ // needed. Asserted so the behaviour is pinned, not silently "correct".+ describe('known limitations', () => {+ it.each([+ ['bare * pairs read as italic: 2 * 3 * 4', 'math', '2 _ 3 _ 4'],+ ['spaced rule not detected: - - -', 'rule', '• - -'],+ ['tilde fence not a code block: ~~~', 'fence', '~~~'],+ ])('%s (%s)', (input, _kind, expected) => {+ const text = input.slice(input.indexOf(': ') + 2)+ expect(markdownToMrkdwn(text)).toBe(expected)+ })+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.tsnew file mode 100644index 000000000000..3b56a9153590--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-mrkdwn.ts@@ -0,0 +1,31 @@+/** Convert the Markdown an LLM emits into Slack mrkdwn: `*bold*` (not `**`),+ * `_italic_`, `<url|text>` links, `•` bullets, no headings/rules. Code spans+ * and `>` quotes are already Slack-compatible and left untouched. */+export function markdownToMrkdwn(input: string): string {+ // Shield code (already Slack-compatible) behind placeholder tokens so the+ // rewrites below can't mangle its contents; restored at the end.+ const fences: string[] = []+ const inline: string[] = []+ let text = input+ .replace(/```[\s\S]*?```/g, (m) => `@@CODEFENCE${fences.push(m) - 1}@@`)+ .replace(/`[^`\n]+`/g, (m) => `@@CODESPAN${inline.push(m) - 1}@@`)++ text = text+ .replace(/^[ \t]*#{1,6}[ \t]+(.+?)[ \t]*$/gm, (_m, h: string) => `@@BOLD@@${h.replace(/\*/g, '')}@@BOLD@@`) // headings -> bold (no nested emphasis)+ .replace(/^[ \t]*([-*_])\1{2,}[ \t]*$/gm, '──────────') // horizontal rules -> divider+ .replace(/^([ \t]*)[-*+] \[[ ]\][ \t]+/gm, '$1• ☐ ') // unchecked task -> bullet+ .replace(/^([ \t]*)[-*+] \[[xX]\][ \t]+/gm, '$1• ☑ ') // checked task -> bullet+ .replace(/^([ \t]*)[-*+][ \t]+/gm, '$1• ') // list markers -> bullets+ .replace(/!\[[^\]]*\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)/g, '<$1>') // images -> <url>+ .replace(/\[([^\]]+)\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)/g, '<$2|$1>') // [text](url "title") -> <url|text>+ .replace(/\*\*\*(.+?)\*\*\*/g, '@@BOLD@@_$1_@@BOLD@@') // bold+italic -> *_x_*+ .replace(/\*\*(.+?)\*\*/g, '@@BOLD@@$1@@BOLD@@') // bold ** -> token+ .replace(/__(.+?)__/g, '@@BOLD@@$1@@BOLD@@') // bold __ -> token+ .replace(/~~(.+?)~~/g, '~$1~') // strikethrough ~~x~~ -> ~x~+ .replace(/\*([^*\n]+)\*/g, '_$1_') // italic * -> _ (leave _italic_ as-is)+ .replace(/@@BOLD@@/g, '*') // tokens -> single * (after italics)++ return text+ .replace(/@@CODESPAN(\d+)@@/g, (_m, i) => inline[Number(i)])+ .replace(/@@CODEFENCE(\d+)@@/g, (_m, i) => fences[Number(i)])+}diff --git a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.tsindex 91587009c5cc..3e8ff132b175 100644--- a/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/slack-reply.ts@@ -11,6 +11,7 @@*/import { HttpFetcher } from './http-client'+import { markdownToMrkdwn } from './slack-mrkdwn'export interface SlackTriggerMetadata {type: 'slack'@@ -180,7 +181,8 @@ export class SlackStatusReporter {}export async function postSlackReply(http: HttpFetcher, opts: PostSlackReplyOpts): Promise<boolean> {- const text = opts.text.trim()+ // The model replies in Markdown; Slack speaks mrkdwn.+ const text = markdownToMrkdwn(opts.text).trim()if (!text) {return false}diff --git a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.test.ts b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.test.tsindex 388ecaff62dc..e33354781558 100644--- a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.test.ts@@ -132,4 +132,15 @@ describe('buildSlackManifest', () => {expect(manifest.display_information.description).toHaveLength(140)expect(manifest.features.bot_user.display_name).toHaveLength(35)})++ it('trims an over-long description at a word boundary, ending with an ellipsis', () => {+ const longDesc = `${'kudos '.repeat(40)}end`+ const { manifest } = build({ displayDescription: longDesc })+ const desc = manifest.display_information.description ?? ''+ expect(desc.length).toBeLessThanOrEqual(140)+ expect(desc.endsWith('…')).toBe(true)+ const kept = desc.slice(0, -1)+ expect(longDesc.startsWith(kept)).toBe(true) // a clean prefix, not mangled+ expect(longDesc[kept.length]).toBe(' ') // cut fell on a word boundary+ })})diff --git a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.tsindex 301165e2c623..7370d0166155 100644--- a/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts+++ b/products/agent_platform/services/agent-shared/src/spec/slack-manifest.ts@@ -62,8 +62,19 @@ export interface BuildSlackManifestResult {const EVENTS_URL_PLACEHOLDER = 'https://<set AGENT_INGRESS_PUBLIC_URL>/slack/events'const INTERACTIVITY_URL_PLACEHOLDER = 'https://<set AGENT_INGRESS_PUBLIC_URL>/slack/interactivity'-function truncate(value: string, max: number): string {- return value.length <= max ? value : value.slice(0, max)+// Cap to Slack's char limit. With `ellipsis`, cut at a word boundary + "…" so a+// long description ends cleanly, not mid-word (names/display_name can't — "…"+// isn't in their allowed charset).+function truncate(value: string, max: number, ellipsis = false): string {+ if (value.length <= max) {+ return value+ }+ if (!ellipsis) {+ return value.slice(0, max)+ }+ const slice = value.slice(0, max - 1)+ const lastSpace = slice.lastIndexOf(' ')+ return `${(lastSpace > 0 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`}/**@@ -140,7 +151,7 @@ export function buildSlackManifest(input: BuildSlackManifestInput): BuildSlackMaconst manifest: SlackAppManifest = {display_information: {name: truncate(input.displayName, 35),- ...(input.displayDescription ? { description: truncate(input.displayDescription, 140) } : {}),+ ...(input.displayDescription ? { description: truncate(input.displayDescription, 140, true) } : {}),},features: {bot_user: { display_name: truncate(input.displayName, 35), always_online: true },diff --git a/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts b/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.tsindex e945293d2991..3b7d1a71e431 100644--- a/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/example-kudos-bot.test.ts@@ -96,6 +96,22 @@ interface SlackCall {body: Record<string, unknown>}+/** Slack tools send form-encoded bodies; the reply relay sends JSON. Parse+ * either into a plain object so assertions can read the fields. */+function parseSlackBody(body: RequestInit['body']): Record<string, unknown> {+ if (typeof body !== 'string') {+ return {}+ }+ if (body.trimStart().startsWith('{')) {+ try {+ return JSON.parse(body) as Record<string, unknown>+ } catch {+ return {}+ }+ }+ return Object.fromEntries(new URLSearchParams(body))+}+/** A recording `HttpClient` stand-in. The native `@posthog/slack-*` tools* dispatch through `ctx.http.fetch` (NOT `global.fetch`), so the reliable* way to intercept + assert on the Slack calls is to pass this as the@@ -110,7 +126,7 @@ function buildSlackRecorder(): { http: { fetch: typeof fetch }; calls: SlackCallcalls.push({method: url.replace('https://slack.com/api/', ''),auth: headers.Authorization,- body: typeof init?.body === 'string' ? JSON.parse(init.body) : {},+ body: parseSlackBody(init?.body),})}return Promise.resolve({diff --git a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.tsindex 2e5ba6b9173b..cb80a4e95fc6 100644--- a/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/slack-trigger.test.ts@@ -49,15 +49,21 @@ function slackEvent(opts: {* distinct `ts` is treated as a separate event; tests simulating a retry* pass the same event_id twice with the same ts. */event_id?: string+ /** Event-level workspace (Slack sets it on app_mention, omits on message). */+ team?: string+ /** Envelope workspace id; message events rely on this. */+ team_id?: string}): Record<string, unknown> {const ts = opts.ts ?? '1.0'return {type: 'event_callback',event_id: opts.event_id ?? `Ev_test_${ts}`,+ team_id: opts.team_id,event: {type: opts.eventType ?? 'message',channel: opts.channel ?? 'C01',channel_type: opts.channel_type,+ team: opts.team,user: opts.user ?? 'U01',text: opts.text ?? 'hi',ts,@@ -200,6 +206,60 @@ describe('slack trigger: real e2e', () => {expect(assistantTexts).toHaveLength(1)})+ it('app_mention + message.channels for one mention dedupe to a single turn', async () => {+ // Slack fires both events for an @-mention: same ts, distinct event_id.+ c.setScript([fauxText('once')])+ await c.deployAgent({ slug: 'no-double', spec: {}, encrypted_env: SLACK_ENV })+ const ts = '1700000200.000100'+ const mention = await c.slackPost(+ 'no-double',+ 'events',+ slackEvent({ eventType: 'app_mention', ts, event_id: 'Ev_mention', text: '<@U-bot> hi' }),+ SLACK_SECRET+ )+ const message = await c.slackPost(+ 'no-double',+ 'events',+ slackEvent({ eventType: 'message', ts, event_id: 'Ev_message', text: '<@U-bot> hi' }),+ SLACK_SECRET+ )+ expect(mention.status).toBe(200)+ expect(message.status).toBe(200)+ expect(message.body.session_id).toBe(mention.body.session_id)++ await c.drain()+ const session = await c.queue.get(mention.body.session_id)+ expect(session!.conversation.filter((m) => m.role === 'user')).toHaveLength(1)+ expect(session!.pending_inputs).toHaveLength(0)+ expect(session!.conversation.filter((m) => m.role === 'assistant')).toHaveLength(1)+ })++ it('message event without event.team gates trust on the envelope team_id', async () => {+ c.setScript([fauxText('ok')])+ await c.deployAgent({+ slug: 'ws-fallback',+ spec: { triggers: [{ type: 'slack', config: { trusted_workspaces: ['T-TRUSTED'] } }] },+ encrypted_env: SLACK_ENV,+ })+ // message events omit event.team — the envelope team_id must still gate.+ const ok = await c.slackPost(+ 'ws-fallback',+ 'events',+ slackEvent({ eventType: 'message', ts: '1.0', team_id: 'T-TRUSTED', text: 'hello' }),+ SLACK_SECRET+ )+ expect(ok.status).toBe(200)+ expect(ok.body.session_id).toBeTruthy()+ // An untrusted envelope is still rejected.+ const rejected = await c.slackPost(+ 'ws-fallback',+ 'events',+ slackEvent({ eventType: 'message', ts: '2.0', team_id: 'T-OTHER', text: 'hello' }),+ SLACK_SECRET+ )+ expect(rejected.status).toBe(403)+ })+it('thread_ts falls back to ts when the mention is a top-level channel message', async () => {// Slack omits thread_ts for top-level messages. A reply still needs a// value (otherwise chat.postMessage would post to channel root, notdiff --git a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.tsindex c58ec6b5bd8b..7cfe59c2333b 100644--- a/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/http-request.v1.ts@@ -224,8 +224,6 @@ export const httpRequestV1 = defineNativeTool({'secrets declared in `spec.secrets` as `${NAME}` inside url, headers, or','body; the runner substitutes the plaintext value before the request goes',"out, so the token never appears in the model's tool-call history.",- 'For Slack specifically: POST to `https://slack.com/api/<method>` with',- '`Authorization: Bearer ${SLACK_BOT_TOKEN}` and a JSON body.',].join(' '),args: Type.Object({url: Type.String({@@ -255,7 +253,7 @@ export const httpRequestV1 = defineNativeTool({body: Type.Optional(Type.Union([Type.String(), Type.Record(Type.String(), Type.Unknown())], {description:- 'Request body. Strings are sent verbatim; objects are JSON-encoded and Content-Type defaults to application/json. `${NAME}` placeholders work inside either form.',+ 'Request body. Strings are sent verbatim; objects are JSON-encoded and Content-Type defaults to application/json. For form-encoded (or any non-JSON) APIs, pass a pre-encoded string body and set Content-Type yourself. `${NAME}` placeholders work inside either form.',})),timeout_ms: Type.Optional(diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.tsindex 2a0b3c37d50e..856f9839e2fc 100644--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.test.ts@@ -132,8 +132,8 @@ describe('slack.* tools', () => {expect(out.has_more).toBe(true)expect(out.next_cursor).toBe('cur-abc')const calls = fetchSpy.mock.calls as unknown as Array<[string, RequestInit]>- const body = JSON.parse(calls[0][1].body as string)- expect(body).toMatchObject({ channel: 'C01', limit: 50, oldest: '100.0' })+ const body = Object.fromEntries(new URLSearchParams(calls[0][1].body as string))+ expect(body).toMatchObject({ channel: 'C01', limit: '50', oldest: '100.0' })expect(body).not.toHaveProperty('latest')expect(body).not.toHaveProperty('cursor')})@@ -150,12 +150,12 @@ describe('slack.* tools', () => {const http: HttpFetcher = { fetch: fetchSpy }await slackReadChannelV1.run({ channel: 'C01', limit: 9999 }, ctxWithSlack(http))const calls = fetchSpy.mock.calls as unknown as Array<[string, RequestInit]>- const bodyHigh = JSON.parse(calls[0][1].body as string)- expect(bodyHigh.limit).toBe(200)+ const bodyHigh = Object.fromEntries(new URLSearchParams(calls[0][1].body as string))+ expect(bodyHigh.limit).toBe('200')await slackReadChannelV1.run({ channel: 'C01', limit: 0 }, ctxWithSlack(http))- const bodyLow = JSON.parse(calls[1][1].body as string)- expect(bodyLow.limit).toBe(1)+ const bodyLow = Object.fromEntries(new URLSearchParams(calls[1][1].body as string))+ expect(bodyLow.limit).toBe('1')})it('read_channel omits next_cursor when slack returns empty string', async () => {@@ -186,8 +186,26 @@ describe('slack.* tools', () => {expect(out.messages.map((m) => m.text)).toEqual(['parent', 'reply'])expect(out.has_more).toBe(false)const calls = fetchSpy.mock.calls as unknown as Array<[string, RequestInit]>- const body = JSON.parse(calls[0][1].body as string)- expect(body).toMatchObject({ channel: 'C01', ts: '111.222', limit: 50 })+ const body = Object.fromEntries(new URLSearchParams(calls[0][1].body as string))+ expect(body).toMatchObject({ channel: 'C01', ts: '111.222', limit: '50' })+ })++ it('sends form-encoded params — Slack read methods reject JSON', async () => {+ const fetchSpy = vi.fn(+ async () =>+ ({+ ok: true,+ status: 200,+ json: async () => ({ ok: true, messages: [], has_more: false }),+ }) as unknown as Response+ )+ const http: HttpFetcher = { fetch: fetchSpy }+ await slackReadThreadV1.run({ channel: 'C01', thread_ts: '9.9' }, ctxWithSlack(http))+ const calls = fetchSpy.mock.calls as unknown as Array<[string, RequestInit]>+ expect((calls[0][1].headers as Record<string, string>)['Content-Type']).toBe(+ 'application/x-www-form-urlencoded'+ )+ expect(calls[0][1].body).toBe('channel=C01&ts=9.9&limit=50')})it('propagates slack api errors', async () => {@@ -205,4 +223,25 @@ describe('slack.* tools', () => {/channel_not_found/)})++ it('surfaces slack warning + field detail so the agent can self-correct', async () => {+ const http: HttpFetcher = {+ fetch: vi.fn(+ async () =>+ ({+ ok: true,+ status: 200,+ json: async () => ({+ ok: false,+ error: 'invalid_arguments',+ warning: 'missing_charset',+ response_metadata: { messages: ['[ERROR] missing required field: ts'] },+ }),+ }) as unknown as Response+ ),+ }+ await expect(slackPostMessageV1.run({ channel: 'C01', text: 'hi' }, ctxWithSlack(http))).rejects.toThrow(+ /missing_charset.*missing required field: ts/+ )+ })})diff --git a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts b/products/agent_platform/services/agent-tools/src/tools/slack.v1.tsindex 92eef0ee4631..149d41323311 100644--- a/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/slack.v1.ts@@ -24,20 +24,41 @@ async function slackCall(method: string,body: Record<string, unknown>): Promise<unknown> {+ // Slack's read methods (conversations.*) reject JSON — they read+ // form-encoded params. Form works for every method, so use it throughout.+ const form = new URLSearchParams()+ for (const [k, v] of Object.entries(body)) {+ if (v !== undefined && v !== null) {+ form.append(k, String(v))+ }+ }const res = await http.fetch(`https://slack.com/api/${method}`, {method: 'POST',headers: {- 'Content-Type': 'application/json; charset=utf-8',+ 'Content-Type': 'application/x-www-form-urlencoded',Authorization: `Bearer ${token}`,},- body: JSON.stringify(body),+ body: form.toString(),})if (!res.ok) {throw new Error(`slack.${method} HTTP ${res.status}`)}- const j = (await res.json()) as { ok: boolean; error?: string }+ const j = (await res.json()) as {+ ok: boolean+ error?: string+ warning?: string+ response_metadata?: { messages?: string[] }+ }if (!j.ok) {- throw new Error(`slack.${method} error: ${j.error ?? 'unknown'}`)+ // Include Slack's warning + field messages so the agent can self-correct.+ const parts = [`slack.${method} error: ${j.error ?? 'unknown'}`]+ if (j.warning) {+ parts.push(`warning: ${j.warning}`)+ }+ if (j.response_metadata?.messages?.length) {+ parts.push(`detail: ${j.response_metadata.messages.join('; ')}`)+ }+ throw new Error(parts.join(' | '))}return j}