@open-everywhere/provider-slack 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/agent/access/slack-attachment-fetch.ts +2 -1
  2. package/agent/app-manifest.ts +15 -1
  3. package/agent/channels/slack-agent-session.ts +249 -0
  4. package/agent/channels/slack-attachments.ts +20 -11
  5. package/agent/channels/slack-bot-ask.ts +101 -0
  6. package/agent/channels/slack-commands.ts +178 -17
  7. package/agent/channels/slack-context.ts +0 -5
  8. package/agent/channels/slack-events.ts +110 -33
  9. package/agent/channels/slack-follow-ups.ts +148 -0
  10. package/agent/channels/slack-friendly-names.ts +55 -0
  11. package/agent/channels/slack-front.ts +262 -27
  12. package/agent/channels/slack-home.ts +9 -3
  13. package/agent/channels/slack-identity.ts +9 -1
  14. package/agent/channels/slack-memory-canvas.ts +197 -54
  15. package/agent/channels/slack-origin-codec.ts +9 -0
  16. package/agent/channels/slack-post-arm.ts +68 -11
  17. package/agent/channels/slack-read.ts +27 -2
  18. package/agent/channels/slack-reply-blocks.ts +180 -0
  19. package/agent/channels/slack-reply-feedback.ts +75 -0
  20. package/agent/channels/slack-shortcut.ts +1 -1
  21. package/agent/channels/slack-voice-clips.ts +82 -0
  22. package/agent/channels/slack-wake-backscroll.ts +0 -5
  23. package/agent/channels/slack-web-api.ts +4 -2
  24. package/agent/channels/slack.ts +81 -19
  25. package/agent/docs-generated.ts +1282 -2
  26. package/agent/ops.ts +14 -21
  27. package/agent/register.ts +25 -0
  28. package/agent/setup/credentials.ts +17 -0
  29. package/agent/setup/page.ts +6 -3
  30. package/agent/surface-parity.ts +2 -0
  31. package/dist/agent/access/slack-attachment-fetch.d.ts.map +1 -1
  32. package/dist/agent/access/slack-attachment-fetch.js.map +1 -1
  33. package/dist/agent/app-manifest.d.ts.map +1 -1
  34. package/dist/agent/app-manifest.js +15 -1
  35. package/dist/agent/app-manifest.js.map +1 -1
  36. package/dist/agent/channels/slack-agent-session.d.ts +81 -0
  37. package/dist/agent/channels/slack-agent-session.d.ts.map +1 -0
  38. package/dist/agent/channels/slack-agent-session.js +198 -0
  39. package/dist/agent/channels/slack-agent-session.js.map +1 -0
  40. package/dist/agent/channels/slack-attachments.d.ts +11 -0
  41. package/dist/agent/channels/slack-attachments.d.ts.map +1 -1
  42. package/dist/agent/channels/slack-attachments.js +21 -14
  43. package/dist/agent/channels/slack-attachments.js.map +1 -1
  44. package/dist/agent/channels/slack-bot-ask.d.ts +30 -0
  45. package/dist/agent/channels/slack-bot-ask.d.ts.map +1 -0
  46. package/dist/agent/channels/slack-bot-ask.js +91 -0
  47. package/dist/agent/channels/slack-bot-ask.js.map +1 -0
  48. package/dist/agent/channels/slack-commands.d.ts +113 -10
  49. package/dist/agent/channels/slack-commands.d.ts.map +1 -1
  50. package/dist/agent/channels/slack-commands.js +151 -18
  51. package/dist/agent/channels/slack-commands.js.map +1 -1
  52. package/dist/agent/channels/slack-context.d.ts +1 -2
  53. package/dist/agent/channels/slack-context.d.ts.map +1 -1
  54. package/dist/agent/channels/slack-context.js +0 -4
  55. package/dist/agent/channels/slack-context.js.map +1 -1
  56. package/dist/agent/channels/slack-events.d.ts +47 -97
  57. package/dist/agent/channels/slack-events.d.ts.map +1 -1
  58. package/dist/agent/channels/slack-events.js +90 -22
  59. package/dist/agent/channels/slack-events.js.map +1 -1
  60. package/dist/agent/channels/slack-follow-ups.d.ts +44 -0
  61. package/dist/agent/channels/slack-follow-ups.d.ts.map +1 -0
  62. package/dist/agent/channels/slack-follow-ups.js +129 -0
  63. package/dist/agent/channels/slack-follow-ups.js.map +1 -0
  64. package/dist/agent/channels/slack-friendly-names.d.ts +10 -0
  65. package/dist/agent/channels/slack-friendly-names.d.ts.map +1 -0
  66. package/dist/agent/channels/slack-friendly-names.js +45 -0
  67. package/dist/agent/channels/slack-friendly-names.js.map +1 -0
  68. package/dist/agent/channels/slack-front.d.ts +38 -46
  69. package/dist/agent/channels/slack-front.d.ts.map +1 -1
  70. package/dist/agent/channels/slack-front.js +230 -23
  71. package/dist/agent/channels/slack-front.js.map +1 -1
  72. package/dist/agent/channels/slack-home.d.ts.map +1 -1
  73. package/dist/agent/channels/slack-home.js +10 -3
  74. package/dist/agent/channels/slack-home.js.map +1 -1
  75. package/dist/agent/channels/slack-identity.d.ts +7 -21
  76. package/dist/agent/channels/slack-identity.d.ts.map +1 -1
  77. package/dist/agent/channels/slack-identity.js +3 -1
  78. package/dist/agent/channels/slack-identity.js.map +1 -1
  79. package/dist/agent/channels/slack-memory-canvas.d.ts +21 -5
  80. package/dist/agent/channels/slack-memory-canvas.d.ts.map +1 -1
  81. package/dist/agent/channels/slack-memory-canvas.js +166 -55
  82. package/dist/agent/channels/slack-memory-canvas.js.map +1 -1
  83. package/dist/agent/channels/slack-origin-codec.d.ts.map +1 -1
  84. package/dist/agent/channels/slack-origin-codec.js +10 -0
  85. package/dist/agent/channels/slack-origin-codec.js.map +1 -1
  86. package/dist/agent/channels/slack-post-arm.d.ts +21 -1
  87. package/dist/agent/channels/slack-post-arm.d.ts.map +1 -1
  88. package/dist/agent/channels/slack-post-arm.js +57 -10
  89. package/dist/agent/channels/slack-post-arm.js.map +1 -1
  90. package/dist/agent/channels/slack-read.d.ts +11 -1
  91. package/dist/agent/channels/slack-read.d.ts.map +1 -1
  92. package/dist/agent/channels/slack-read.js +27 -3
  93. package/dist/agent/channels/slack-read.js.map +1 -1
  94. package/dist/agent/channels/slack-reply-blocks.d.ts +29 -0
  95. package/dist/agent/channels/slack-reply-blocks.d.ts.map +1 -0
  96. package/dist/agent/channels/slack-reply-blocks.js +172 -0
  97. package/dist/agent/channels/slack-reply-blocks.js.map +1 -0
  98. package/dist/agent/channels/slack-reply-feedback.d.ts +23 -0
  99. package/dist/agent/channels/slack-reply-feedback.d.ts.map +1 -0
  100. package/dist/agent/channels/slack-reply-feedback.js +63 -0
  101. package/dist/agent/channels/slack-reply-feedback.js.map +1 -0
  102. package/dist/agent/channels/slack-shortcut.d.ts +10 -0
  103. package/dist/agent/channels/slack-shortcut.d.ts.map +1 -1
  104. package/dist/agent/channels/slack-shortcut.js +1 -1
  105. package/dist/agent/channels/slack-shortcut.js.map +1 -1
  106. package/dist/agent/channels/slack-voice-clips.d.ts +16 -0
  107. package/dist/agent/channels/slack-voice-clips.d.ts.map +1 -0
  108. package/dist/agent/channels/slack-voice-clips.js +80 -0
  109. package/dist/agent/channels/slack-voice-clips.js.map +1 -0
  110. package/dist/agent/channels/slack-wake-backscroll.d.ts +0 -2
  111. package/dist/agent/channels/slack-wake-backscroll.d.ts.map +1 -1
  112. package/dist/agent/channels/slack-wake-backscroll.js +0 -4
  113. package/dist/agent/channels/slack-wake-backscroll.js.map +1 -1
  114. package/dist/agent/channels/slack-web-api.d.ts.map +1 -1
  115. package/dist/agent/channels/slack-web-api.js +4 -2
  116. package/dist/agent/channels/slack-web-api.js.map +1 -1
  117. package/dist/agent/channels/slack.d.ts +22 -1
  118. package/dist/agent/channels/slack.d.ts.map +1 -1
  119. package/dist/agent/channels/slack.js +70 -16
  120. package/dist/agent/channels/slack.js.map +1 -1
  121. package/dist/agent/docs-generated.d.ts.map +1 -1
  122. package/dist/agent/docs-generated.js +1282 -2
  123. package/dist/agent/docs-generated.js.map +1 -1
  124. package/dist/agent/ops.d.ts +1 -1
  125. package/dist/agent/ops.d.ts.map +1 -1
  126. package/dist/agent/ops.js +15 -21
  127. package/dist/agent/ops.js.map +1 -1
  128. package/dist/agent/register.d.ts.map +1 -1
  129. package/dist/agent/register.js +22 -1
  130. package/dist/agent/register.js.map +1 -1
  131. package/dist/agent/setup/credentials.d.ts +12 -0
  132. package/dist/agent/setup/credentials.d.ts.map +1 -1
  133. package/dist/agent/setup/credentials.js +17 -0
  134. package/dist/agent/setup/credentials.js.map +1 -1
  135. package/dist/agent/setup/page.d.ts.map +1 -1
  136. package/dist/agent/setup/page.js +6 -3
  137. package/dist/agent/setup/page.js.map +1 -1
  138. package/dist/agent/surface-parity.d.ts.map +1 -1
  139. package/dist/agent/surface-parity.js +2 -0
  140. package/dist/agent/surface-parity.js.map +1 -1
  141. package/package.json +40 -3
@@ -42,6 +42,7 @@ import {
42
42
  type EgressRefusalCause,
43
43
  } from "@open-everywhere/core/agent/adapter-api.js";
44
44
  import { slackBotToken } from "../setup/credentials.js";
45
+ import type { AuditDetail } from "@open-everywhere/core/agent/adapter-api.js";
45
46
 
46
47
  // THE CREDENTIAL'S IDENTITY, FOR THE AUDIT ROW (OPE-1547) — the ref NAME, never the value. This is
47
48
  // the one host-side seam that attaches a credential, so before this ticket it was the one place
@@ -140,7 +141,7 @@ export async function fetchSlackAttachment(ctx: BindableContext, ref: TrustedSla
140
141
  // referenced here; the row carries the ref name only, which is the identity an operator looks up.
141
142
  // `route` is the dispatch route — it was called `via` until OPE-1547, the same field name the
142
143
  // SANDBOX plane used for the stamping connection.
143
- const row = (outcome: "allowed" | "failed", extra: Record<string, unknown> = {}): Record<string, unknown> => ({
144
+ const row = (outcome: "allowed" | "failed", extra: AuditDetail = {}): AuditDetail => ({
144
145
  ...hostCallAuditFields({
145
146
  host: safe.url.hostname,
146
147
  verb: ATTACHMENT_VERB,
@@ -150,7 +150,7 @@ export function slackAppManifestTemplate(opts: SlackAppManifestOptions = {}): st
150
150
  description: `${appName} control-plane commands (stop, status, budget) — no model turn.`,
151
151
  // Every subcommand `parseOeCommandTokens` accepts (packages/core/agent/commands/core.ts).
152
152
  // scripts/slack-app-manifest-test.ts fails if one is missing here.
153
- usage_hint: "stop | status | budget [raise <usd> | clear] | rate <n> | optout [on | off] | help",
153
+ usage_hint: "stop | status | budget [raise <usd> | clear] | rate <n> | optout [on | off] | watch [more | less | none] | cover [on | off] | suggest [on | off] | help",
154
154
  should_escape: false,
155
155
  },
156
156
  ],
@@ -243,6 +243,17 @@ export function slackAppManifestTemplate(opts: SlackAppManifestOptions = {}): st
243
243
  // knows. Without it the canvas refresh fails with `missing_scope`, logged and audited
244
244
  // per channel, and memory itself is unaffected.
245
245
  "canvases:write",
246
+ // canvases.sections.lookup — find a memory canvas made before the `memory_canvas` row
247
+ // existed, by the marker line it carries (OPE-2587, core channels/slack-canvas-list.ts
248
+ // `memoryCanvasAmong`). Without it such a canvas held only as a channel tab is not found:
249
+ // its refresh and take-down record `failed` and `clear-failed`, and nothing is overwritten.
250
+ "canvases:read",
251
+ // slackLists.items.list / .create / .update — the agent's own List writes (OPE-2521,
252
+ // core tools/update_list.ts): it reads a List's rows to match one by name, then adds or
253
+ // changes rows on a person's approval. `canvases:write` above also covers the agent's own
254
+ // canvas writes (canvases.create, canvases.edit; core tools/write_canvas.ts).
255
+ "lists:read",
256
+ "lists:write",
246
257
  // The side panel (OPE-2457): Slack requires it for `app_context_changed`, the event whose
247
258
  // subscription makes Slack attach the viewed room to each side-panel `message.im`.
248
259
  "assistant:write",
@@ -271,6 +282,8 @@ export function slackAppManifestTemplate(opts: SlackAppManifestOptions = {}): st
271
282
  // channel_shared → channels:read, groups:read (re-run the memory canvas gate, OPE-2451)
272
283
  // user_change → users:read (automatic offboarding on a deactivated member, OPE-2423)
273
284
  // app_context_changed → assistant:write (the side panel's viewed room, OPE-2457)
285
+ // agent_session_stopped → chat:write (Slack's native Stop button on an agent session,
286
+ // OPE-2519; Slack shows the button only to an app subscribed to it)
274
287
  // scripts/slack-app-manifest-test.ts derives the handled set from the code and fails if
275
288
  // this list drops one (OPE-2223).
276
289
  bot_events: [
@@ -286,6 +299,7 @@ export function slackAppManifestTemplate(opts: SlackAppManifestOptions = {}): st
286
299
  "channel_shared",
287
300
  "user_change",
288
301
  "app_context_changed",
302
+ "agent_session_stopped",
289
303
  ],
290
304
  },
291
305
  // The INTERACTIVITY Request URL — the SAME public route Event Subscriptions uses. Every
@@ -0,0 +1,249 @@
1
+ // THE SLACK AGENT SESSION (OPE-2519) — Slack's native Stop, the session title, and the "needs you" state.
2
+ //
3
+ // Slack's agent experience shows each conversation with the app as an AGENT SESSION, keyed by the
4
+ // channel and the thread root (docs.slack.dev/ai/agent-sessions, re-read 2026-10-14). A session has a
5
+ // lifecycle status (`processing`, `active`, `suspended`, `closed`) and a title. This file owns the three
6
+ // things OE does with it:
7
+ //
8
+ // • STOP. While a session is `processing`, Slack shows a Stop button, but only to an app that
9
+ // subscribes to `agent_session_stopped`. A press arrives as that event. It takes the SAME cancel
10
+ // path as the ✋ reaction and `/oe stop` (`cancelAnchoredTurn`): no session is minted, no model is
11
+ // called, nothing is spent. Slack does not move the status itself, so the route sets `active`.
12
+ // • TITLE. A top-level message the person sends in their DM with the app opens a new conversation,
13
+ // and gets a short title from the words the person TYPED (`authoredText`). The lines of a
14
+ // forwarded or quoted message are another conversation's words, so they never title it. The host
15
+ // derives the title in code: no model writes it. Slack applies a `title` only when the call
16
+ // CREATES the session, so a title the person typed over ours is never overwritten. A thread reply,
17
+ // a shortcut and a group DM get no title.
18
+ // • STATE. Core's turn-anchor hook sets the session `processing` when a turn starts, and at the park
19
+ // `suspended` when the turn reported through `update_status` that it waits on a person
20
+ // (`needs_input` or `blocked`), else `active` (channels/surface-session-state.ts). This file
21
+ // registers the Slack setter: it names the session from the delivery's auth attributes. The
22
+ // person's next message sets `processing`, then parks `active` unless it reports again that it
23
+ // waits on the person. A job's result wake names no session, so its turn sets no state.
24
+ // • A FORWARDED JOB's WAIT (OPE-2536). A job the DM seat forwards to the work session can end waiting
25
+ // on the person: it asked a question in the room (`ask_room`), or it needs their own sign-in. The
26
+ // work session has no `update_status`, so the host sets the session `suspended` at the job's
27
+ // settlement (core channels/work-surface-wait.ts). This file registers the PIN for that: the
28
+ // session's id and the three attributes that name it again, kept on the job.
29
+ //
30
+ // WHICH SESSIONS. Only the person's 1:1 DM with the app (the Messages tab and the side panel), where
31
+ // Slack lists the person's agent sessions. The DM door stamps the session's thread root on the wake's
32
+ // auth (`agent_session_ts`): a top-level message opens its own session, keyed by its own `ts`, and a
33
+ // thread reply belongs to its thread's session. A channel thread gets no state from OE.
34
+ //
35
+ // Every call here is best-effort. A workspace without Slack's agent features answers an error, which
36
+ // is logged and changes nothing else.
37
+
38
+ import {
39
+ cancelAnchoredTurn,
40
+ resolvePartition,
41
+ turnAnchorKey,
42
+ turnChannelKey,
43
+ type AttachSessionForCancel,
44
+ type CancelResult,
45
+ type SurfaceSessionPinner,
46
+ type SurfaceSessionSetter,
47
+ } from "@open-everywhere/core/agent/adapter-api.js";
48
+ import { bindableForSlackIds, slackForm, type SlackEventEnvelope } from "./slack-events.js";
49
+
50
+ /** Slack's event for a press of the session's Stop button. */
51
+ export const AGENT_SESSION_STOPPED_EVENT = "agent_session_stopped";
52
+
53
+ /** The longest title OE sets. Slack accepts 200 characters; a session list shows far fewer. */
54
+ export const SLACK_SESSION_TITLE_MAX = 60;
55
+
56
+ /** The session states OE sets. */
57
+ export type SlackSessionStatus = "processing" | "active" | "suspended";
58
+
59
+ /** The auth attribute the DM door stamps with the session's thread root (slack-front.ts `scheduleDmWake`). */
60
+ const AGENT_SESSION_TS_ATTRIBUTE = "agent_session_ts";
61
+
62
+ /** The form-call seam: `slackForm` in production, a recorder in the tests. */
63
+ export type SlackFormCall = (method: string, body: string) => Promise<Record<string, unknown> | undefined>;
64
+
65
+ // --- the title ------------------------------------------------------------------------------------
66
+
67
+ /** Slack's three escaped characters, decoded. */
68
+ function decodeSlackEntities(text: string): string {
69
+ return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
70
+ }
71
+
72
+ /**
73
+ * The session title for a conversation that opens with `text`, or undefined when nothing readable is
74
+ * left. Pure. It keeps the first non-empty line, renders a link as its label, a channel as `#name`, and
75
+ * drops a member or group mention (no raw id reaches the title). It strips `*`, `~` and backticks, and
76
+ * keeps `_`, so an identifier such as `oe_config` stays intact. A long line is cut at a word and ends
77
+ * with `…`.
78
+ */
79
+ export function slackSessionTitle(text: string | undefined): string | undefined {
80
+ if (typeof text !== "string") return undefined;
81
+ const rendered = text
82
+ // A member mention, with or without a label: dropped.
83
+ .replace(/<@[A-Z0-9]+(?:\|[^>]*)?>/g, " ")
84
+ // A channel mention: its name when Slack sent one, else dropped.
85
+ .replace(/<#[A-Z0-9]+\|([^>]+)>/g, "#$1")
86
+ .replace(/<#[A-Z0-9]+>/g, " ")
87
+ // A special or group mention (`<!here>`, `<!subteam^S1|@team>`): dropped.
88
+ .replace(/<![^>]*>/g, " ")
89
+ // A link: its label, else the address.
90
+ .replace(/<[^>|]+\|([^>]+)>/g, "$1")
91
+ .replace(/<([^>]+)>/g, "$1");
92
+ const line = decodeSlackEntities(rendered)
93
+ .split(/\r?\n/)
94
+ .map((l) => l.replace(/[*~`]+/g, "").replace(/\s+/g, " ").trim())
95
+ .find((l) => l.length > 0);
96
+ if (line === undefined) return undefined;
97
+ if (line.length <= SLACK_SESSION_TITLE_MAX) return line;
98
+ const head = line.slice(0, SLACK_SESSION_TITLE_MAX - 1);
99
+ const cut = head.lastIndexOf(" ");
100
+ return `${(cut >= SLACK_SESSION_TITLE_MAX / 2 ? head.slice(0, cut) : head).trimEnd()}…`;
101
+ }
102
+
103
+ // --- the status call -------------------------------------------------------------------------------
104
+
105
+ /** One `agents.sessions.setStatus` call. */
106
+ export interface SlackSessionStatusCall {
107
+ readonly channelId: string;
108
+ /** The session's thread root. */
109
+ readonly threadTs: string;
110
+ readonly status: SlackSessionStatus;
111
+ /** Applied only when this call creates the session. */
112
+ readonly title?: string;
113
+ }
114
+
115
+ /** The form body of {@link SlackSessionStatusCall}. Pure. */
116
+ export function slackSessionStatusForm(call: SlackSessionStatusCall): string {
117
+ const body = new URLSearchParams({ channel_id: call.channelId, thread_ts: call.threadTs, status: call.status });
118
+ if (call.title !== undefined && call.title.length > 0) body.set("title", call.title);
119
+ return body.toString();
120
+ }
121
+
122
+ /** Set a session's status (and, on creation, its title). True when Slack answered `ok`. Never throws. */
123
+ export async function setSlackSessionStatus(call: SlackSessionStatusCall, form: SlackFormCall = slackForm): Promise<boolean> {
124
+ try {
125
+ const res = await form("agents.sessions.setStatus", slackSessionStatusForm(call));
126
+ if (res?.ok === true) return true;
127
+ console.warn(`[open-everywhere:slack-session] agents.sessions.setStatus ${call.status} was not applied (${call.channelId}/${call.threadTs}): ${String(res?.error ?? "no answer")}`);
128
+ return false;
129
+ } catch (err) {
130
+ console.warn(`[open-everywhere:slack-session] agents.sessions.setStatus ${call.status} failed (${call.channelId}/${call.threadTs}): ${String(err)}`);
131
+ return false;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The session a delivery's auth attributes name, or undefined for none. Only a delivery the DM door
137
+ * stamped (`agent_session_ts`) names one: a shortcut, a group DM and every channel carry no stamp, so
138
+ * they never set a session's state, even on a threaded message. Pure.
139
+ */
140
+ export function slackAgentSessionOf(attributes: Readonly<Record<string, unknown>>): { readonly channelId: string; readonly threadTs: string } | undefined {
141
+ if (attributes.channel_type !== "im") return undefined;
142
+ const channelId = attributes.channel_id;
143
+ const stamped = attributes[AGENT_SESSION_TS_ATTRIBUTE];
144
+ if (typeof channelId !== "string" || channelId.length === 0 || typeof stamped !== "string" || stamped.length === 0) return undefined;
145
+ return { channelId, threadTs: stamped };
146
+ }
147
+
148
+ /**
149
+ * The Slack pinner (OPE-2536): the session a delivery names, as the setter's own id and the three
150
+ * attributes that name it again. A forwarded job keeps this, so its settlement can set the session
151
+ * `suspended` long after the delivery's auth is gone. Ids only, never text. Pure.
152
+ */
153
+ export const slackSurfaceSessionPin: SurfaceSessionPinner = (attributes) => {
154
+ const session = slackAgentSessionOf(attributes);
155
+ if (!session) return undefined;
156
+ return {
157
+ id: `${session.channelId}:${session.threadTs}`,
158
+ attributes: { channel_id: session.channelId, channel_type: "im", [AGENT_SESSION_TS_ATTRIBUTE]: session.threadTs },
159
+ };
160
+ };
161
+
162
+ /** The Slack setter core's turn-anchor hook calls (registered in register.ts). */
163
+ export function slackSurfaceSessionSetter(form: SlackFormCall = slackForm): SurfaceSessionSetter {
164
+ return async (attributes, status) => {
165
+ const session = slackAgentSessionOf(attributes);
166
+ if (!session) return undefined;
167
+ await setSlackSessionStatus({ ...session, status }, form);
168
+ return `${session.channelId}:${session.threadTs}`;
169
+ };
170
+ }
171
+
172
+ // --- the Stop button -------------------------------------------------------------------------------
173
+
174
+ /** One press of the Stop button, as the route reads it. */
175
+ export interface ParsedSessionStop {
176
+ readonly channelId: string;
177
+ /** The session's thread root. */
178
+ readonly threadTs: string;
179
+ /** Who pressed Stop. */
180
+ readonly userId: string;
181
+ /** From the `event_callback` envelope: Slack does not put it in the event. */
182
+ readonly teamId?: string;
183
+ readonly eventTs?: string;
184
+ }
185
+
186
+ /** Parse an `agent_session_stopped` envelope, or null for anything else. Pure. */
187
+ export function parseAgentSessionStopped(envelope: SlackEventEnvelope): ParsedSessionStop | null {
188
+ if (envelope?.type !== "event_callback") return null;
189
+ const e = envelope.event as Record<string, unknown> | undefined;
190
+ if (!e || e.type !== AGENT_SESSION_STOPPED_EVENT) return null;
191
+ const channelId = typeof e.channel === "string" ? e.channel : "";
192
+ const threadTs = typeof e.thread_ts === "string" ? e.thread_ts : "";
193
+ const userId = typeof e.user === "string" ? e.user : "";
194
+ if (!channelId || !threadTs || !userId) return null;
195
+ const teamId = typeof envelope.team_id === "string" && envelope.team_id.length > 0 ? envelope.team_id : undefined;
196
+ return {
197
+ channelId,
198
+ threadTs,
199
+ userId,
200
+ ...(teamId ? { teamId } : {}),
201
+ ...(typeof e.event_ts === "string" ? { eventTs: e.event_ts } : {}),
202
+ };
203
+ }
204
+
205
+ /** A 1:1 DM channel id. Only there does the stop fall back to the channel's newest turn. */
206
+ function isDmChannel(channelId: string): boolean {
207
+ return channelId.startsWith("D");
208
+ }
209
+
210
+ /** What the Stop route needs. */
211
+ export interface SessionStopDeps {
212
+ /** eve's I/O-free cancel door, the same one the ✋ arm uses. */
213
+ readonly attachSession: AttachSessionForCancel;
214
+ /** The cancel path. Absent means the live `cancelAnchoredTurn`. */
215
+ readonly cancel?: typeof cancelAnchoredTurn;
216
+ /** The status call. Absent means the live {@link setSlackSessionStatus}. */
217
+ readonly setStatus?: (call: SlackSessionStatusCall) => Promise<boolean>;
218
+ }
219
+
220
+ /**
221
+ * Stop the turn a Stop press names, then set the session `active`.
222
+ *
223
+ * The turn is found by the session's thread first (the key the ✋ arm uses for a thread root). In the
224
+ * person's 1:1 DM it falls back to the DM's newest turn, because a top-level DM message keys its turn by
225
+ * the channel alone. In a shared channel it does not fall back: there the newest turn can belong to
226
+ * another thread, and cancelling nothing beats cancelling a guess. The status is set whatever the
227
+ * cancel answers, because a session left `processing` keeps its spinner for an hour. Never throws.
228
+ */
229
+ export async function routeAgentSessionStop(ev: ParsedSessionStop, deps: SessionStopDeps): Promise<CancelResult> {
230
+ const p = resolvePartition(bindableForSlackIds({ teamId: ev.teamId, channelId: ev.channelId, userId: ev.userId }));
231
+ const anchorKey = turnAnchorKey("slack", ev.channelId, ev.threadTs);
232
+ const channelKey = isDmChannel(ev.channelId) ? turnChannelKey("slack", ev.channelId) : undefined;
233
+ let result: CancelResult;
234
+ try {
235
+ result = await (deps.cancel ?? cancelAnchoredTurn)({
236
+ org: p.org,
237
+ platform: "slack",
238
+ workspace: p.workspace,
239
+ requestedBy: ev.userId,
240
+ via: "stop-button",
241
+ query: { ...(anchorKey ? { anchorKey } : {}), ...(channelKey ? { channelKey } : {}) },
242
+ attachSession: deps.attachSession,
243
+ });
244
+ } catch (err) {
245
+ result = { outcome: "error", message: `stop failed: ${String(err)}` };
246
+ }
247
+ await (deps.setStatus ?? setSlackSessionStatus)({ channelId: ev.channelId, threadTs: ev.threadTs, status: "active" }).catch(() => false);
248
+ return result;
249
+ }
@@ -33,6 +33,7 @@ import {
33
33
  registerAttachmentResolver,
34
34
  AttachmentOversizeError,
35
35
  type SlackAttachmentRow,
36
+ type BindableContext,
36
37
  } from "@open-everywhere/core/agent/adapter-api.js";
37
38
  import { fetchSlackAttachment } from "../access/slack-attachment-fetch.js";
38
39
 
@@ -135,6 +136,24 @@ export async function resolveSlackAttachmentDurable(fileId: string, org?: string
135
136
  }
136
137
  }
137
138
 
139
+ /**
140
+ * The size-guarded byte pull over a TRUSTED `url_private`: the bot-token, host-pinned fetch, then the Content-Length
141
+ * pre-check (rejects with {@link AttachmentOversizeError} phase "declared" BEFORE the body is read), then the post-read
142
+ * cap (phase "actual"). Two callers: the guarded resolver below, and the voice-clip loader (slack-voice-clips.ts),
143
+ * which reads a clip off the event that woke the agent. Both pass an event-supplied URL, never a model string.
144
+ */
145
+ export async function pullSlackAttachmentBytes(ctx: BindableContext, ref: { readonly urlPrivate: string; readonly id?: string }, maxBytes: number): Promise<Uint8Array> {
146
+ const res = await fetchSlackAttachment(ctx, ref);
147
+ if (!res.ok) throw new Error(`fetching the upload failed (HTTP ${res.status})`);
148
+ // Content-Length pre-check off the declared length — reject before reading the body.
149
+ const declared = Number.parseInt(res.headers.get("content-length") ?? "", 10);
150
+ if (Number.isFinite(declared) && declared > maxBytes) throw new AttachmentOversizeError(declared, "declared", maxBytes);
151
+ const bytes = new Uint8Array(await res.arrayBuffer());
152
+ // Post-read cap — a chunked response can exceed the (possibly-absent) Content-Length.
153
+ if (bytes.byteLength > maxBytes) throw new AttachmentOversizeError(bytes.byteLength, "actual", maxBytes);
154
+ return bytes;
155
+ }
156
+
138
157
  /**
139
158
  * Register Slack as an attachment-plane resolver (channels/attachments.ts) — the neutral seam
140
159
  * describe_image consults so its contract carries no per-platform union arm. The resolver wraps the
@@ -169,17 +188,7 @@ export function registerSlackAttachmentResolver(): void {
169
188
  ref: `slack-file:${attachmentId}`,
170
189
  mimeType: rec.mimeType,
171
190
  name: rec.name,
172
- async pull({ maxBytes }) {
173
- const res = await fetchSlackAttachment(ctx, { urlPrivate: rec.urlPrivate, id: attachmentId });
174
- if (!res.ok) throw new Error(`fetching the upload failed (HTTP ${res.status})`);
175
- // Content-Length pre-check off the declared length — reject before reading the body.
176
- const declared = Number.parseInt(res.headers.get("content-length") ?? "", 10);
177
- if (Number.isFinite(declared) && declared > maxBytes) throw new AttachmentOversizeError(declared, "declared", maxBytes);
178
- const bytes = new Uint8Array(await res.arrayBuffer());
179
- // Post-read cap — a chunked response can exceed the (possibly-absent) Content-Length.
180
- if (bytes.byteLength > maxBytes) throw new AttachmentOversizeError(bytes.byteLength, "actual", maxBytes);
181
- return bytes;
182
- },
191
+ pull: ({ maxBytes }) => pullSlackAttachmentBytes(ctx, { urlPrivate: rec.urlPrivate, id: attachmentId }, maxBytes),
183
192
  };
184
193
  },
185
194
  });
@@ -0,0 +1,101 @@
1
+ // SLACK'S ARM OF CHIEF-OF-STAFF DELEGATION (OPE-2426) — the probe that proves an ask to another bot, and
2
+ // the facts the front route hands core for an inbound bot message. Core holds the policy
3
+ // (core/agent/channels/bot-ask.ts); this file only reads Slack.
4
+ //
5
+ // THE PROBE reads three facts with the BOT token, never a model string:
6
+ // 1. the ask message itself (`conversations.replies` on its ts). The bot token reads it only when this
7
+ // app is in the channel, and the app must be in the channel to receive the other bot's reply at all.
8
+ // So an unreadable message is a refusal that says "invite the agent";
9
+ // 2. its author is the person who asks, and its own text @mentions the named bot;
10
+ // 3. the named account is a bot (`users.info` `is_bot`), and not this app itself (`auth.test`). An
11
+ // unknown own identity refuses: it cannot prove "not this app".
12
+ // Any failed call refuses (`unreadable`). The probe never throws.
13
+
14
+ import type { BotAskProbe, BotAskProbeAnswer, BotReplyFacts } from "@open-everywhere/core/agent/adapter-api.js";
15
+ import { encodeSlackForm } from "./slack-web-api.js";
16
+ import type { ParsedMessageEvent } from "./slack-events.js";
17
+
18
+ /** The Slack calls the probe makes (injectable for the unit test). */
19
+ export interface SlackBotAskDeps {
20
+ /** One Web API call with the bot token; resolves the parsed body, or undefined on a transport failure. */
21
+ readonly call: (method: string, body: Record<string, string>) => Promise<Record<string, unknown> | undefined>;
22
+ /** This app's own bot user id and bot id (`auth.test`), best-effort. */
23
+ readonly self: () => Promise<{ readonly userId?: string; readonly botId?: string }>;
24
+ }
25
+
26
+ type SlackMessage = { readonly ts?: unknown; readonly thread_ts?: unknown; readonly user?: unknown; readonly text?: unknown };
27
+
28
+ /** Does the text @mention this user id (`<@U123>` or `<@U123|name>`)? PURE. */
29
+ export function mentionsUser(text: string, userId: string): boolean {
30
+ return text.includes(`<@${userId}>`) || text.includes(`<@${userId}|`);
31
+ }
32
+
33
+ /** Build Slack's probe. */
34
+ export function slackBotAskProbe(deps: SlackBotAskDeps): BotAskProbe {
35
+ return async (q): Promise<BotAskProbeAnswer> => {
36
+ try {
37
+ const [platform, teamId] = q.workspaceKey.split("/");
38
+ if (platform !== "slack" || !teamId) return { ok: false, reason: "unreadable" };
39
+ const replies = await deps.call("conversations.replies", { channel: q.channel, ts: q.messageTs, limit: "1", inclusive: "true" });
40
+ const messages = replies?.ok === true && Array.isArray(replies.messages) ? (replies.messages as SlackMessage[]) : [];
41
+ const msg = messages.find((m) => m.ts === q.messageTs);
42
+ if (!msg) return { ok: false, reason: "unreadable" };
43
+ if (msg.user !== q.personId) return { ok: false, reason: "not-yours" };
44
+ const text = typeof msg.text === "string" ? msg.text : "";
45
+ if (!mentionsUser(text, q.bot)) return { ok: false, reason: "bot-not-named" };
46
+ const self = await deps.self().catch(() => ({}) as { userId?: string; botId?: string });
47
+ // FAIL-CLOSED: without this app's own user id, a mention of this app cannot be told from another bot's.
48
+ if (self.userId === undefined) return { ok: false, reason: "unreadable" };
49
+ if (self.userId === q.bot) return { ok: false, reason: "self" };
50
+ const info = await deps.call("users.info", { user: q.bot });
51
+ const user = info?.ok === true && info.user && typeof info.user === "object" ? (info.user as Record<string, unknown>) : undefined;
52
+ if (!user) return { ok: false, reason: "unreadable" };
53
+ if (user.is_bot !== true) return { ok: false, reason: "not-a-bot" };
54
+ const profile = user.profile && typeof user.profile === "object" ? (user.profile as Record<string, unknown>) : {};
55
+ const botId = typeof profile.bot_id === "string" && profile.bot_id.length > 0 ? profile.bot_id : undefined;
56
+ if (botId !== undefined && self.botId !== undefined && botId === self.botId) return { ok: false, reason: "self" };
57
+ const label = [user.real_name, profile.display_name, user.name].find((v) => typeof v === "string" && v.trim().length > 0) as string | undefined;
58
+ return {
59
+ ok: true,
60
+ threadTs: typeof msg.thread_ts === "string" && msg.thread_ts.length > 0 ? msg.thread_ts : q.messageTs,
61
+ botUserId: q.bot,
62
+ ...(botId === undefined ? {} : { botId }),
63
+ ...(label === undefined ? {} : { botLabel: label }),
64
+ askText: text,
65
+ };
66
+ } catch {
67
+ return { ok: false, reason: "unreadable" };
68
+ }
69
+ };
70
+ }
71
+
72
+ /** The live deps: `slackForm` with the bot token, and the front route's cached `auth.test`. */
73
+ export function liveSlackBotAskDeps(
74
+ form: (method: string, body: string) => Promise<Record<string, unknown> | undefined>,
75
+ self: () => Promise<{ readonly userId?: string; readonly botId?: string }>,
76
+ ): SlackBotAskDeps {
77
+ return { call: (method, body) => form(method, encodeSlackForm(body)), self };
78
+ }
79
+
80
+ /** Is this parsed message a candidate for the asked-thread exception at all? A cheap, pure pre-filter, so a
81
+ * human message never pays a store read. PURE. */
82
+ export function botReplyCandidate(ev: ParsedMessageEvent): boolean {
83
+ return (Boolean(ev.botId) || ev.subtype === "bot_message") && ev.threadTs !== undefined && ev.threadTs !== ev.ts;
84
+ }
85
+
86
+ /** Core's facts for one parsed Slack message. PURE. */
87
+ export function slackBotReplyFacts(ev: ParsedMessageEvent, org: string, self: { readonly userId?: string; readonly botId?: string }): BotReplyFacts {
88
+ return {
89
+ org,
90
+ platform: "slack",
91
+ workspace: ev.teamId,
92
+ channel: ev.channelId,
93
+ threadTs: ev.threadTs,
94
+ messageTs: ev.ts,
95
+ authorUserId: ev.userId,
96
+ authorBotId: ev.botId,
97
+ subtype: ev.subtype,
98
+ ...(self.userId === undefined ? {} : { selfUserId: self.userId }),
99
+ ...(self.botId === undefined ? {} : { selfBotId: self.botId }),
100
+ };
101
+ }