agents-framework 0.3.0__py3-none-any.whl

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 (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
@@ -0,0 +1,992 @@
1
+ """Slack-workspace source — read community workspaces we don't administer (issue #19).
2
+
3
+ Every Slack bot token this repo holds is scoped to a workspace we administer, so
4
+ there is no bot path into a community workspace, and getting an app installed
5
+ there needs admin approval we are unlikely to get. See issue #19 for the full
6
+ feasibility writeup.
7
+
8
+ ## Two transports
9
+
10
+ `transport:` selects the implementation; the config shape and the Source
11
+ interface are the same for both:
12
+
13
+ - `agentmail` (issue #19) — the workspace's own notification/digest
14
+ emails are forwarded to an AgentMail inbox; this plugin is a thin
15
+ composition wrapper over the existing `agentmail` source
16
+ (`framework/plugins/agentmail_source.py`). Zero new auth, unambiguously
17
+ within ToS, identical in shape to an already-deployed agent.
18
+ Coarse granularity: you get what Slack chooses to email, not full channel
19
+ history, and per-message links rather than threads.
20
+
21
+ - `session` (issue #45) — reads as the logged-in browser user through the
22
+ `xoxc` web token plus the `d` session cookie, the mechanism the
23
+ voitta-ai/skillz `slack-xoxc-session-client` skill documents. Full
24
+ channel history, a real lookback window, folded threads. Read-only
25
+ access as the logged-in user, per configured workspace, is the
26
+ authorization decision #45 records; posting stays unauthorized and the
27
+ client refuses it in code (see below).
28
+
29
+ ## Session transport: how the credentials are obtained
30
+
31
+ Nothing is configured and nothing is stored. Per run the plugin:
32
+
33
+ 1. decrypts the `d` (and `d-s`) cookie for `<subdomain>.slack.com` from the
34
+ local browser's cookie store with `pycookiecheat`. `d` is httpOnly, so
35
+ no in-page or extension path can read it; decrypting the store is the
36
+ only scriptable way. On macOS this touches the login keychain and may
37
+ prompt.
38
+ 2. GETs the workspace root with that cookie and scrapes the `xoxc-` token
39
+ out of the bootstrap payload (`"api_token":"xoxc-..."`).
40
+ 3. POSTs to `https://<subdomain>.slack.com/api/<method>` with the token as
41
+ form data and the cookies attached. The team host matters: the generic
42
+ `slack.com` host rejects session tokens.
43
+
44
+ Both secrets live in the client instance and die with the process. They are
45
+ never written, never logged and never appear in an error message. A call that
46
+ comes back `invalid_auth` re-extracts once (the session may have rotated
47
+ under us) and, if that still fails, raises naming the subdomain — the fix is
48
+ to log in again in the browser.
49
+
50
+ `pycookiecheat` is an optional dependency (`pip install '.[slack-session]'`)
51
+ and is imported inside `_build_session_transport`, not at module scope. The
52
+ #40 import isolation is per module: a module-level import would take the
53
+ agentmail transport down on a venv that lacks the package, which is exactly
54
+ the incident class #40 exists to prevent.
55
+
56
+ ## Session transport: writes are refused in code
57
+
58
+ `_SessionClient.call` checks the method against `_READ_METHODS` before it
59
+ touches the network. Anything not in that allowlist raises `RuntimeError`
60
+ naming the method. There is no config key, flag or subclass hook that widens
61
+ the list; extending it means editing this file. That is deliberate: the
62
+ allowlist is the whole guarantee the read-only authorization rests on, and
63
+ a guarantee that can be switched off in a config file is not one.
64
+
65
+ ## Session transport: what a run does
66
+
67
+ - `channels` entries are names or conversation ids. A name is resolved to
68
+ an id once per run through `conversations.list` (public and private,
69
+ archived excluded, paginated); an unknown name raises and lists what the
70
+ workspace does have, so a typo is a startup error and not an empty digest.
71
+ An entry shaped `^[CDG][A-Z0-9]{8,}$` is a conversation id and is used
72
+ directly. That is the only way to read a direct message: a DM has no name
73
+ and `conversations.list` does not carry it. An id gets one
74
+ `conversations.info` call for a `meta.channel` label — the channel's name,
75
+ or for a DM the other member's display name through `users.info`. A label
76
+ that cannot be read falls back to the id rather than failing the run.
77
+ - `from_users` (optional) keeps only messages posted by those ids. A
78
+ message's author is its `user`, or the `bot_profile.user_id` behind a bot
79
+ message; a `B...` id matches a message's `bot_id`, for integrations that
80
+ post with no user at all. This is what makes a bot's DM usable: the
81
+ conversation also holds your own replies, and without the filter they
82
+ would be scored as signals too. It applies to thread replies as well, so a
83
+ kept message folds in only the replies from a wanted author — otherwise
84
+ the text of a filtered signal would carry the very writing the filter
85
+ excludes. A parent whose replies are all filtered out folds nothing.
86
+ - `conversations.history` is read per channel with `oldest = now -
87
+ since_hours`, paginated by cursor. Only top-level messages become
88
+ Signals; thread replies that Slack surfaces in history (broadcasts) are
89
+ skipped there and picked up through their parent.
90
+ - With `include_threads`, every message carrying `reply_count` gets its
91
+ replies fetched through `conversations.replies` and folded into the
92
+ parent's text as indented `name: text` lines, so a scorer or a digest
93
+ sees the whole exchange as one item.
94
+ - One Signal per top-level message. `id` is `<channel_id>:<ts>`, which is
95
+ stable across runs and is what the SeenStore dedupes on. `url` is the
96
+ permalink from `chat.getPermalink`, or a constructed archive link where
97
+ that method is refused (see below). `meta` carries `workspace`,
98
+ `channel` (the name), `user` (display name), `reply_count`,
99
+ `permalink_source` (`"api"` or `"constructed"`), `posted` (ISO 8601,
100
+ UTC) and `transport: "session"`.
101
+ - A message's text is its `text` plus, when they say more, the text of
102
+ its header, section and context blocks: a bot post often carries its
103
+ content only in blocks and leaves `text` as a one-line fallback.
104
+ - `meta["job_url"]` is the message's first http(s) link, read out of
105
+ Slack's `<url|label>` markup (or, for a client that does not use it, out
106
+ of the prose), and `meta["apply_url"]` a later link whose
107
+ label says "apply" and whose URL differs from it (issue #76). Both keys
108
+ are absent when there is nothing to put in them — notably `apply_url` for
109
+ a lead bot whose "Apply Now" link *is* the job page; see `_link_meta`.
110
+ A destination that wants to render a link therefore reads
111
+ `job_url` and falls back to `url` (the permalink to the message itself).
112
+ - User ids are rendered to display names through `users.info`, cached for
113
+ the run.
114
+ - HTTP 429 (and the JSON-level `ratelimited` error) honour `Retry-After`
115
+ and retry that call. A run that still cannot complete raises; it never
116
+ returns the messages it managed to get as though that were everything,
117
+ because the SeenStore would then mark the window done.
118
+ - A page with `has_more: true` and no `next_cursor` raises. That is the
119
+ shape Slack returns when a free-tier workspace's history visibility cap
120
+ cuts the window short, and it is the common case for the community
121
+ workspaces this transport targets. Following it with time-based
122
+ pagination would not help (the older messages are not visible to this
123
+ user), and returning what came back would present a capped window as a
124
+ complete one.
125
+
126
+ ## Session transport on an Enterprise Grid org
127
+
128
+ Which methods a user session may call is a property of the *workspace*, not of
129
+ this config. An Enterprise Grid org refuses several of them outright with
130
+ `enterprise_is_restricted`, and a lead agent hit both of these live (issue
131
+ #69). Everything needed to actually read messages still works there:
132
+ `auth.test`, `conversations.info` (including a DM, by id),
133
+ `conversations.history`, `conversations.replies`, `users.info` and `team.info`.
134
+ Two things do not:
135
+
136
+ - **`chat.getPermalink` is refused.** A link is a convenience and the message
137
+ is the signal, so a refusal is not worth a failed run: the archive URL is
138
+ built instead, `https://<subdomain>.slack.com/archives/<channel_id>/p<ts
139
+ without its dot>`, which is the link the Slack client itself produces.
140
+ `meta["permalink_source"]` records `"constructed"` rather than `"api"`, and
141
+ the first fallback in a run prints one line on stderr, so nobody has to
142
+ guess whether a link was confirmed by Slack or assembled here.
143
+ - **`conversations.list` is refused, so channel *names* cannot be resolved
144
+ at all.** A config naming channels fails on such a workspace, and no
145
+ amount of retrying changes that; the run raises before anything else with
146
+ a message saying the org restricts listing and that channels must be given
147
+ as ids. A config of ids only never calls `conversations.list`, so it works
148
+ on a Grid org unchanged — which makes ids the portable way to write one.
149
+
150
+ Config keys (session transport):
151
+
152
+ workspace label for Signal.source / meta, required
153
+ subdomain the `<subdomain>` in `<subdomain>.slack.com`, required
154
+ browser pycookiecheat browser name (chrome, chromium, brave,
155
+ firefox, slack); default chrome
156
+ channels list of channel names or conversation ids (`C...`, `D...`,
157
+ `G...`), required and non-empty
158
+ from_users optional list of user ids; keeps only their messages
159
+ since_hours lookback window; default 24
160
+ include_threads fold thread replies into the parent; default true
161
+ timeout per-request HTTP timeout in seconds; default 30
162
+
163
+ The agentmail transport takes the agentmail source's own keys, including
164
+ `include_trash` (default false): that inbox's list endpoint hides messages
165
+ labelled `trash`, and a workspace's forwarded digests can end up there without
166
+ this repo doing anything. See agentmail_source.py.
167
+
168
+ ## Channel scoping is best-effort on the agentmail transport
169
+
170
+ AgentMail's message list carries no structured channel field (see
171
+ agentmail_source.py's docstring on the shape it hands back) — Slack's digest
172
+ emails are just subject/sender/body. So `channels:` there is a coarse text
173
+ filter over the combined subject+body, matching the "coarse granularity"
174
+ tradeoff issue #19 accepted. The session transport scopes by channel for
175
+ real.
176
+
177
+ Contract: see docs/PLUGIN-CONTRACT.md.
178
+ """
179
+
180
+ from __future__ import annotations
181
+
182
+ import html
183
+ import os
184
+ import re
185
+ import sys
186
+ import time
187
+ from datetime import datetime, timezone
188
+ from typing import Any, Callable
189
+
190
+ import requests
191
+
192
+ from framework.interfaces import Signal, Source
193
+ from framework.plugins.agentmail_source import AgentMailSource
194
+ from framework.registry import register_source
195
+
196
+
197
+ class _AgentmailTransport:
198
+ """Adapts an AgentMailSource into a workspace-scoped Source.
199
+
200
+ Composition, not subclassing: AgentMailSource already does the request,
201
+ the filtering, and the body hydration (and already never swallows a
202
+ failed fetch — `requests.raise_for_status()` propagates). This wrapper
203
+ only adds the workspace label and the coarse channel filter.
204
+ """
205
+
206
+ def __init__(self, agentmail: AgentMailSource, workspace: str, channels: list[str]):
207
+ self._agentmail = agentmail
208
+ self._workspace = workspace
209
+ self._channel_terms = [c.lstrip("#").lower() for c in channels]
210
+
211
+ def fetch(self) -> list[Signal]:
212
+ signals = self._agentmail.fetch()
213
+ if self._channel_terms:
214
+ signals = [
215
+ s
216
+ for s in signals
217
+ if any(term in s.text.lower() for term in self._channel_terms)
218
+ ]
219
+ for s in signals:
220
+ s.meta["workspace"] = self._workspace
221
+ s.meta["transport"] = "agentmail"
222
+ retval = signals
223
+ return retval
224
+
225
+
226
+ # The read-method allowlist for the session transport. This is the guarantee
227
+ # the read-only authorization (issue #45) rests on: `_SessionClient.call`
228
+ # refuses any method not listed here before any HTTP happens, and nothing in
229
+ # config can extend it. Widening it is a code change with a review.
230
+ _READ_METHODS: frozenset[str] = frozenset(
231
+ {
232
+ "auth.test",
233
+ "conversations.list",
234
+ "conversations.info",
235
+ "conversations.history",
236
+ "conversations.replies",
237
+ "chat.getPermalink",
238
+ "users.info",
239
+ "users.list",
240
+ }
241
+ )
242
+
243
+ # A `channels` entry in this shape is a Slack conversation id and is used as
244
+ # one: C public/private channel, D direct message, G legacy private group. A
245
+ # DM has no name to resolve, which is the case that made this necessary.
246
+ _CHANNEL_ID = re.compile(r"^[CDG][A-Z0-9]{8,}$")
247
+
248
+ # What an Enterprise Grid org answers a user session for the methods it does
249
+ # not allow it (issue #69). It is a property of the workspace, not of the call.
250
+ _RESTRICTED = "enterprise_is_restricted"
251
+
252
+ # Slack's own link markup, `<url>` or `<url|label>` (issue #76). Restricted to
253
+ # http(s) on purpose: the same syntax carries `<@U123>`, `<#C123|name>` and
254
+ # `<!here>`, which are mentions, not links. Slack escapes `&`, `<` and `>` in
255
+ # message text, so a captured URL is unescaped before it is handed on, or a
256
+ # query string would arrive with `&amp;` in it.
257
+ _SLACK_LINK = re.compile(r"<(https?://[^>|\s]+)(?:\|([^>]*))?>")
258
+ _BARE_URL = re.compile(r"(?<![<|])https?://[^\s<>|]+")
259
+ _APPLY_LABEL = re.compile(r"\bapply\b", re.I)
260
+
261
+ # Sentence punctuation that ends a URL in prose rather than belonging to it.
262
+ # A bracket is not here: a real URL can end in one, so brackets are trimmed
263
+ # only when they are unbalanced (see `_trim_url`).
264
+ _URL_TAIL = "".join((".", ",", ";", ":", "!", "?", "'", '"', "‘", "’", "“", "”"))
265
+ _URL_BRACKETS = (("(", ")"), ("[", "]"), ("{", "}"))
266
+
267
+ _USER_AGENT = "Mozilla/5.0"
268
+ _PAGE_LIMIT = 200
269
+ _MAX_RATE_LIMIT_RETRIES = 5
270
+
271
+
272
+ def _blocks_text(message: dict[str, Any]) -> str:
273
+ """The readable text a message carries in its Block Kit blocks.
274
+
275
+ A bot or app post often puts its whole content in `blocks` and leaves
276
+ `text` as the notification fallback: a weekly events announcement whose
277
+ `text` is one headline, "10 events this week", and whose ten events exist
278
+ only in section blocks. Reading `text` alone handed the digest that one
279
+ line, and the model reported the post as routine. Header, section (text and
280
+ fields) and context blocks are read. `rich_text` is not: it is what a human
281
+ message's composer writes, and it repeats `text`.
282
+ """
283
+ parts: list[str] = []
284
+ for block in message.get("blocks") or []:
285
+ kind = block.get("type")
286
+ if kind in ("header", "section"):
287
+ text = (block.get("text") or {}).get("text", "")
288
+ if text:
289
+ parts.append(text)
290
+ for field in block.get("fields") or []:
291
+ if field.get("text"):
292
+ parts.append(field["text"])
293
+ elif kind == "context":
294
+ for element in block.get("elements") or []:
295
+ if element.get("type") in ("mrkdwn", "plain_text") and element.get("text"):
296
+ parts.append(element["text"])
297
+ retval = "\n".join(parts)
298
+ return retval
299
+
300
+
301
+ def _message_text(message: dict[str, Any]) -> str:
302
+ """`text`, followed by its block text when the blocks say something more."""
303
+ text = message.get("text", "")
304
+ blocks = _blocks_text(message)
305
+ if blocks and blocks.strip() not in text:
306
+ retval = f"{text}\n{blocks}" if text else blocks
307
+ else:
308
+ retval = text
309
+ return retval
310
+
311
+
312
+ def _link_meta(text: str) -> dict[str, str]:
313
+ """`job_url` and, when there is a separate one, `apply_url` (issue #76).
314
+
315
+ A lead arrives as a bot message whose body is prose: the link a human
316
+ would click is in Slack's markup, not in a structured field, so it is read
317
+ back out of the text. `job_url` is the message's first http(s) link, which
318
+ for a notification bot is the thing being notified about (the job title is
319
+ a link). `apply_url` is a later link whose label says "apply" *and* points
320
+ somewhere else.
321
+
322
+ That last condition is what the measurement called for. In the live lead
323
+ DM this was written against, every one of the 654 "Apply Now" links across
324
+ 760 messages was byte-identical to that message's job link: the bot does
325
+ not publish an apply URL, and applying starts from a button on the job
326
+ page. The portal does have an application page of its own — a few
327
+ *post*-application follow-up messages link one directly — but its address
328
+ is never given out in a lead, and assembling one from the job id would put
329
+ a fabricated link in front of an operator. So the key is absent, and a
330
+ consumer falls back to `job_url`. A bot that does post a distinct apply
331
+ link gets both keys with no change here.
332
+
333
+ Markup and bare URLs mix in one message, so the two are searched per slot
334
+ rather than one falling back to the other wholesale: a markup job link and
335
+ a bare apply link in the same message yield both keys. For a bare URL there
336
+ is no label to read, so the line it sits on stands in for one.
337
+
338
+ Keys are absent rather than empty when nothing is found: a caller tests
339
+ membership and never has to tell "no link" from "a link that is nothing".
340
+ """
341
+ body = text or ""
342
+ marked = [(html.unescape(url), label or "") for url, label in _SLACK_LINK.findall(body)]
343
+ bare = _bare_links(body)
344
+
345
+ retval: dict[str, str] = {}
346
+ ordered = marked or bare
347
+ if not ordered:
348
+ return retval
349
+
350
+ job_url = ordered[0][0]
351
+ retval["job_url"] = job_url
352
+
353
+ apply_url = _first_apply(ordered[1:], job_url)
354
+ if not apply_url and marked:
355
+ # The job link was markup; an apply link in the same message may still
356
+ # be bare. Searched per slot, or a mixed message loses it entirely.
357
+ apply_url = _first_apply(bare, job_url)
358
+ if apply_url:
359
+ retval["apply_url"] = apply_url
360
+ return retval
361
+
362
+
363
+ def _first_apply(candidates: list[tuple[str, str]], job_url: str) -> str:
364
+ """First candidate whose describing text says "apply" and that is not the job.
365
+
366
+ The describing text is a markup link's label, or the line a bare URL sits
367
+ on. "apply" is matched as a whole word so an "Applicant tracking" link is
368
+ not mistaken for one.
369
+ """
370
+ retval = ""
371
+ for url, described_by in candidates:
372
+ if url != job_url and _APPLY_LABEL.search(described_by):
373
+ retval = url
374
+ break
375
+ return retval
376
+
377
+
378
+ def _bare_links(text: str) -> list[tuple[str, str]]:
379
+ """Unwrapped URLs in `text`, each with the line it appears on.
380
+
381
+ Not every client wraps its URLs in Slack's markup. A URL written in prose
382
+ runs into whatever punctuation follows it, so the match is trimmed: a
383
+ trailing full stop or comma cannot be part of the address, while a closing
384
+ bracket can, and is kept only when the URL opens one to match. Getting this
385
+ wrong is not cosmetic — an action built on `job_url` would navigate to the
386
+ 404 that a trailing `.` produces.
387
+ """
388
+ retval = []
389
+ for match in _BARE_URL.finditer(text):
390
+ url = _trim_url(html.unescape(match.group(0)))
391
+ if not url:
392
+ continue
393
+ line_start = text.rfind("\n", 0, match.start()) + 1
394
+ line_end = text.find("\n", match.end())
395
+ line = text[line_start:] if line_end == -1 else text[line_start:line_end]
396
+ retval.append((url, line))
397
+ return retval
398
+
399
+
400
+ def _trim_url(url: str) -> str:
401
+ """Drop sentence punctuation a URL picked up from the prose around it."""
402
+ retval = url
403
+ while retval:
404
+ last = retval[-1]
405
+ if last in _URL_TAIL:
406
+ retval = retval[:-1]
407
+ continue
408
+ unbalanced = any(
409
+ last == close and retval.count(close) > retval.count(opener)
410
+ for opener, close in _URL_BRACKETS
411
+ )
412
+ if not unbalanced:
413
+ break
414
+ retval = retval[:-1]
415
+ return retval
416
+
417
+
418
+ class SlackAPIError(RuntimeError):
419
+ """A Slack method answered `ok: false`; `code` is Slack's error string.
420
+
421
+ A `RuntimeError` like everything else this module raises, so callers that
422
+ only want a failed run need no change. `code` exists because two of these
423
+ are a property of the *workspace* rather than a bug: an Enterprise Grid org
424
+ refuses some methods to a user session with `enterprise_is_restricted`, and
425
+ the transport reacts differently depending on which method that was.
426
+ """
427
+
428
+ def __init__(self, message: str, code: str):
429
+ super().__init__(message)
430
+ self.code = code
431
+
432
+
433
+ class _SessionClient:
434
+ """Slack web-API client authenticated by a live browser session, read-only.
435
+
436
+ `cookie_reader` is `pycookiecheat.get_cookies` bound to a browser by the
437
+ builder; the client itself has no import of pycookiecheat so the
438
+ allowlist and the request path can be exercised without it. Secrets are
439
+ held on the instance only and are never logged, written or surfaced in
440
+ exceptions.
441
+ """
442
+
443
+ def __init__(
444
+ self,
445
+ subdomain: str,
446
+ cookie_reader: Callable[[str], dict[str, str]],
447
+ timeout: int = 30,
448
+ ):
449
+ self.subdomain = subdomain
450
+ # The team host, not slack.com: session tokens are rejected on the
451
+ # generic host.
452
+ self._base = f"https://{subdomain}.slack.com"
453
+ self._cookie_reader = cookie_reader
454
+ self._timeout = timeout
455
+ self._cookies: dict[str, str] | None = None
456
+ self._token: str | None = None
457
+
458
+ def _extract_cookies(self) -> dict[str, str]:
459
+ raw = self._cookie_reader(f"{self._base}/")
460
+ d = raw.get("d", "")
461
+ if not d.startswith("xoxd-"):
462
+ raise RuntimeError(
463
+ f"slack-workspace source (transport: session): no valid 'd' "
464
+ f"session cookie for {self.subdomain}.slack.com in the browser "
465
+ f"cookie store; log in to that workspace in the browser first"
466
+ )
467
+ # Some workspaces require d-s alongside d; send it when present.
468
+ retval = {"d": d, "d-s": raw.get("d-s", "")}
469
+ return retval
470
+
471
+ def _extract_token(self) -> str:
472
+ # No raise_for_status here: Slack answers a scripted GET of the
473
+ # workspace root with 403 while still serving the full authenticated
474
+ # HTML that carries the token, so the token's presence in the body is
475
+ # the real success test, not the HTTP status code.
476
+ resp = requests.get(
477
+ f"{self._base}/",
478
+ cookies=self._cookies,
479
+ headers={"User-Agent": _USER_AGENT},
480
+ timeout=self._timeout,
481
+ )
482
+ match = re.search(r'"api_token":"(xoxc-[^"]+)"', resp.text)
483
+ if match is None:
484
+ raise RuntimeError(
485
+ f"slack-workspace source (transport: session): no xoxc token "
486
+ f"in the {self.subdomain}.slack.com page; the browser session "
487
+ f"is probably expired, log in again"
488
+ )
489
+ retval = match.group(1)
490
+ return retval
491
+
492
+ def _ensure_auth(self) -> None:
493
+ if self._cookies is None:
494
+ self._cookies = self._extract_cookies()
495
+ if self._token is None:
496
+ self._token = self._extract_token()
497
+
498
+ def _reset_auth(self) -> None:
499
+ self._cookies = None
500
+ self._token = None
501
+
502
+ def _post(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
503
+ """One method call with 429 handling. Returns the parsed JSON body."""
504
+ attempts = 0
505
+ while True:
506
+ attempts += 1
507
+ resp = requests.post(
508
+ f"{self._base}/api/{method}",
509
+ data={"token": self._token, **params},
510
+ cookies=self._cookies,
511
+ headers={"User-Agent": _USER_AGENT},
512
+ timeout=self._timeout,
513
+ )
514
+ body: dict[str, Any] = {}
515
+ if resp.status_code != 429:
516
+ resp.raise_for_status()
517
+ body = resp.json()
518
+ limited = resp.status_code == 429 or body.get("error") == "ratelimited"
519
+ if not limited:
520
+ break
521
+ if attempts >= _MAX_RATE_LIMIT_RETRIES:
522
+ raise RuntimeError(
523
+ f"slack-workspace source (transport: session): {method} on "
524
+ f"{self.subdomain} still rate limited after {attempts} attempts; "
525
+ f"aborting the run rather than returning a partial window"
526
+ )
527
+ retry_after = resp.headers.get("Retry-After", "")
528
+ delay = int(retry_after) if retry_after.isdigit() else 1
529
+ time.sleep(max(delay, 1))
530
+ retval = body
531
+ return retval
532
+
533
+ def call(self, method: str, **params: Any) -> dict[str, Any]:
534
+ """Call a read method. Refuses anything outside `_READ_METHODS`.
535
+
536
+ The allowlist check runs before authentication and before any HTTP,
537
+ so a refused method never even extracts credentials.
538
+ """
539
+ if method not in _READ_METHODS:
540
+ raise RuntimeError(
541
+ f"slack-workspace source (transport: session): refusing Slack "
542
+ f"method {method!r}; this transport is read-only and writes are "
543
+ f"unauthorized (issue #45). Allowed: {', '.join(sorted(_READ_METHODS))}"
544
+ )
545
+ self._ensure_auth()
546
+ result = self._post(method, params)
547
+ if result.get("error") == "invalid_auth":
548
+ # The browser session may have rotated since extraction; take
549
+ # exactly one fresh look before giving up.
550
+ self._reset_auth()
551
+ self._ensure_auth()
552
+ result = self._post(method, params)
553
+ if result.get("error") == "invalid_auth":
554
+ raise RuntimeError(
555
+ f"slack-workspace source (transport: session): "
556
+ f"{self.subdomain}.slack.com rejected the session even after "
557
+ f"re-extracting it; log in to that workspace again in the browser"
558
+ )
559
+ if not result.get("ok"):
560
+ code = str(result.get("error") or "unknown error")
561
+ raise SlackAPIError(
562
+ f"slack-workspace source (transport: session): {method} on "
563
+ f"{self.subdomain} failed: {code}",
564
+ code=code,
565
+ )
566
+ retval = result
567
+ return retval
568
+
569
+ def archive_url(self, channel_id: str, ts: str) -> str:
570
+ """The archive link for a message, built rather than asked for.
571
+
572
+ Same shape the Slack client produces: the message timestamp with its
573
+ dot removed, prefixed `p`. Used when `chat.getPermalink` is refused.
574
+ """
575
+ retval = f"{self._base}/archives/{channel_id}/p{str(ts).replace('.', '')}"
576
+ return retval
577
+
578
+ def paginate(self, method: str, key: str, **params: Any) -> list[dict[str, Any]]:
579
+ """Follow `response_metadata.next_cursor` and concatenate `key`.
580
+
581
+ Raises when a page says `has_more` but gives no cursor to continue
582
+ with: Slack's history-visibility cap, where a partial result must not
583
+ pass for a complete one.
584
+ """
585
+ items: list[dict[str, Any]] = []
586
+ cursor = ""
587
+ while True:
588
+ page_params = dict(params, limit=_PAGE_LIMIT)
589
+ if cursor:
590
+ page_params["cursor"] = cursor
591
+ page = self.call(method, **page_params)
592
+ items.extend(page.get(key) or [])
593
+ cursor = (page.get("response_metadata") or {}).get("next_cursor") or ""
594
+ if not cursor:
595
+ if page.get("has_more"):
596
+ channel = params.get("channel")
597
+ where = f" for channel {channel}" if channel else ""
598
+ raise RuntimeError(
599
+ f"slack-workspace session: {method}{where} reported has_more "
600
+ "with no next_cursor after "
601
+ f"{len(items)} items: history is capped (Slack's free-tier "
602
+ "history visibility limit), so the rest of the window cannot "
603
+ "be read; refusing to return a partial result"
604
+ )
605
+ break
606
+ retval = items
607
+ return retval
608
+
609
+
610
+ class _SessionTransport:
611
+ """Reads named channels as the logged-in user and emits one Signal per message."""
612
+
613
+ def __init__(
614
+ self,
615
+ client: _SessionClient,
616
+ workspace: str,
617
+ channels: list[str],
618
+ since_hours: float,
619
+ include_threads: bool,
620
+ from_users: list[str] | None = None,
621
+ ):
622
+ self._client = client
623
+ self._workspace = workspace
624
+ self._channels = [c.strip() for c in channels]
625
+ self._since_hours = since_hours
626
+ self._include_threads = include_threads
627
+ self._from_users = set(from_users or [])
628
+ self._user_names: dict[str, str] = {}
629
+ self._permalink_warned = False
630
+
631
+ def _resolve_channels(self) -> list[tuple[str, str]]:
632
+ """Configured entries as (label, id) pairs, in configured order.
633
+
634
+ A name is resolved through `conversations.list` and an unknown one is a
635
+ hard error. An id is used as given: a DM has no name to look up, and
636
+ `conversations.list` would not carry it anyway.
637
+ """
638
+ names = [c.lstrip("#") for c in self._channels if not _CHANNEL_ID.match(c)]
639
+ by_name: dict[str, str] = {}
640
+ if names:
641
+ try:
642
+ listed = self._client.paginate(
643
+ "conversations.list",
644
+ "channels",
645
+ types="public_channel,private_channel",
646
+ exclude_archived="true",
647
+ )
648
+ except SlackAPIError as exc:
649
+ if exc.code != _RESTRICTED:
650
+ raise
651
+ raise RuntimeError(
652
+ f"slack-workspace source (transport: session): this workspace "
653
+ f"restricts channel listing for user sessions "
654
+ f"({_RESTRICTED}), so the name(s) {', '.join(names)} cannot be "
655
+ f"resolved. Give those channels as conversation ids instead: "
656
+ f"open the channel in Slack, 'Copy link', and take the id from "
657
+ f"the end of the URL (.../archives/<id>). Reading by id needs "
658
+ f"no listing and works on this workspace; a DM id starts with D."
659
+ ) from exc
660
+ by_name = {c["name"]: c["id"] for c in listed if c.get("name") and c.get("id")}
661
+ missing = [n for n in names if n not in by_name]
662
+ if missing:
663
+ raise RuntimeError(
664
+ f"slack-workspace source (transport: session): channel(s) "
665
+ f"{', '.join(missing)} not found in {self._workspace}; the "
666
+ f"workspace has: {', '.join(sorted(by_name))}"
667
+ )
668
+
669
+ resolved: list[tuple[str, str]] = []
670
+ for entry in self._channels:
671
+ if _CHANNEL_ID.match(entry):
672
+ resolved.append((self._label_for_id(entry), entry))
673
+ else:
674
+ name = entry.lstrip("#")
675
+ resolved.append((name, by_name[name]))
676
+ retval = resolved
677
+ return retval
678
+
679
+ def _label_for_id(self, channel_id: str) -> str:
680
+ """A human label for a conversation named by id, for `meta.channel`.
681
+
682
+ `conversations.info` names a channel. A DM has no name, so the label is
683
+ the other member's display name, which is what an operator reading the
684
+ digest recognises. Anything unreadable falls back to the id itself:
685
+ a label is not worth failing a run over.
686
+ """
687
+ info = self._client.call("conversations.info", channel=channel_id).get("channel") or {}
688
+ name = info.get("name") or info.get("name_normalized") or ""
689
+ if not name and info.get("is_im"):
690
+ other = info.get("user") or ""
691
+ name = f"dm:{self._display_name(other)}" if other else "dm"
692
+ retval = name or channel_id
693
+ return retval
694
+
695
+ def _display_name(self, user_id: str) -> str:
696
+ """Display name for a user id, cached for the run."""
697
+ if user_id not in self._user_names:
698
+ info = self._client.call("users.info", user=user_id).get("user") or {}
699
+ profile = info.get("profile") or {}
700
+ self._user_names[user_id] = (
701
+ profile.get("display_name")
702
+ or profile.get("real_name")
703
+ or info.get("real_name")
704
+ or info.get("name")
705
+ or user_id
706
+ )
707
+ retval = self._user_names[user_id]
708
+ return retval
709
+
710
+ @staticmethod
711
+ def _message_user_id(message: dict[str, Any]) -> str:
712
+ """The posting user id, including the bot user behind a bot message."""
713
+ retval = message.get("user") or (message.get("bot_profile") or {}).get("user_id") or ""
714
+ return retval
715
+
716
+ def _user_name(self, message: dict[str, Any]) -> str:
717
+ user_id = self._message_user_id(message)
718
+ if not user_id:
719
+ # Bot and integration posts carry no user; fall back to what the
720
+ # message itself says.
721
+ retval = message.get("username") or message.get("bot_id") or "unknown"
722
+ return retval
723
+ retval = self._display_name(user_id)
724
+ return retval
725
+
726
+ def _is_wanted_author(self, message: dict[str, Any]) -> bool:
727
+ """`from_users` membership. Empty config means every author.
728
+
729
+ Applied to thread replies as well as to top-level messages: a reply is
730
+ as much someone's writing as a post, and a filtered conversation that
731
+ folded the filtered-out author's replies into the text would hand the
732
+ scorer exactly what the filter was meant to keep out.
733
+ """
734
+ if not self._from_users:
735
+ retval = True
736
+ else:
737
+ user_id = self._message_user_id(message)
738
+ # A `B...` id may be configured instead, for an integration whose
739
+ # messages carry no user at all.
740
+ retval = (user_id in self._from_users) or (
741
+ message.get("bot_id") in self._from_users
742
+ )
743
+ return retval
744
+
745
+ @staticmethod
746
+ def _is_top_level(message: dict[str, Any]) -> bool:
747
+ thread_ts = message.get("thread_ts")
748
+ retval = thread_ts is None or thread_ts == message.get("ts")
749
+ return retval
750
+
751
+ def _replies_text(self, channel_id: str, parent_ts: str) -> list[str]:
752
+ replies = self._client.paginate(
753
+ "conversations.replies", "messages", channel=channel_id, ts=parent_ts
754
+ )
755
+ lines = []
756
+ for reply in replies:
757
+ if reply.get("ts") == parent_ts:
758
+ continue
759
+ if not self._is_wanted_author(reply):
760
+ continue
761
+ lines.append(f" {self._user_name(reply)}: {reply.get('text', '')}")
762
+ retval = lines
763
+ return retval
764
+
765
+ def _permalink(self, channel_id: str, ts: str) -> tuple[str, str]:
766
+ """The message's link, and where it came from.
767
+
768
+ `chat.getPermalink` is refused outright on an Enterprise Grid org
769
+ (issue #69), and the link is a convenience while the message is the
770
+ signal, so *that* refusal builds the archive URL instead of failing the
771
+ run. `meta["permalink_source"]` says which happened, and the first
772
+ fallback of a run says so once on stderr: constructed links are correct
773
+ but unverified, and an operator should not have to guess which they
774
+ have.
775
+
776
+ Only `enterprise_is_restricted` is treated that way. Any other Slack
777
+ error propagates, because a constructed link looks exactly the same
778
+ whether the org restricts the method or the call was wrong, and a run
779
+ that quietly builds links over a real fault would never be noticed.
780
+ """
781
+ link = ""
782
+ try:
783
+ link = self._client.call(
784
+ "chat.getPermalink", channel=channel_id, message_ts=ts
785
+ ).get("permalink", "")
786
+ except SlackAPIError as exc:
787
+ # Only the org-wide restriction is survivable. channel_not_found,
788
+ # message_not_found, missing_scope or a transient fatal_error say
789
+ # something is wrong with this call, and constructing a link would
790
+ # bury that under a URL indistinguishable from a healthy Grid run.
791
+ if exc.code != _RESTRICTED:
792
+ raise
793
+ if not self._permalink_warned:
794
+ self._permalink_warned = True
795
+ print(
796
+ f"slack-workspace source (transport: session): chat.getPermalink "
797
+ f"unavailable ({exc.code}); building archive links instead, see "
798
+ f"meta.permalink_source",
799
+ file=sys.stderr,
800
+ )
801
+ if link:
802
+ retval = (link, "api")
803
+ else:
804
+ retval = (self._client.archive_url(channel_id, ts), "constructed")
805
+ return retval
806
+
807
+ def _signal(self, channel_name: str, channel_id: str, message: dict[str, Any]) -> Signal:
808
+ ts = message["ts"]
809
+ reply_count = int(message.get("reply_count") or 0)
810
+ lines = [_message_text(message)]
811
+ if self._include_threads and reply_count > 0:
812
+ lines.extend(self._replies_text(channel_id, ts))
813
+ permalink, permalink_source = self._permalink(channel_id, ts)
814
+ retval = Signal(
815
+ id=f"{channel_id}:{ts}",
816
+ text="\n".join(lines),
817
+ url=permalink,
818
+ source=f"slack-workspace:{self._workspace}",
819
+ meta={
820
+ "workspace": self._workspace,
821
+ "channel": channel_name,
822
+ "user": self._user_name(message),
823
+ "reply_count": reply_count,
824
+ "permalink_source": permalink_source,
825
+ "transport": "session",
826
+ # When it was posted, so a reader can resolve "Wednesday,
827
+ # December 2" to a year (the digest's calendar card does).
828
+ "posted": datetime.fromtimestamp(float(ts), timezone.utc).isoformat(),
829
+ # From the parent message only: a reply's links belong to the
830
+ # reply, and folding them in would attach someone else's link
831
+ # to this signal.
832
+ **_link_meta(message.get("text", "")),
833
+ },
834
+ )
835
+ return retval
836
+
837
+ def fetch(self) -> list[Signal]:
838
+ self._user_names = {}
839
+ self._permalink_warned = False
840
+ oldest = time.time() - self._since_hours * 3600
841
+ signals: list[Signal] = []
842
+ for channel_name, channel_id in self._resolve_channels():
843
+ history = self._client.paginate(
844
+ "conversations.history",
845
+ "messages",
846
+ channel=channel_id,
847
+ oldest=f"{oldest:.6f}",
848
+ )
849
+ for message in history:
850
+ if not self._is_top_level(message):
851
+ continue
852
+ if not self._is_wanted_author(message):
853
+ continue
854
+ signals.append(self._signal(channel_name, channel_id, message))
855
+ if signals and not any("job_url" in s.meta for s in signals):
856
+ # Extraction reads a bot's prose, so a format change on the bot's
857
+ # side shows up here as a field that is simply always missing. Say
858
+ # it once, or the first anyone learns of it is a dead button.
859
+ print(
860
+ f"slack-workspace source (transport: session): no links found in any of "
861
+ f"{len(signals)} message(s); meta.job_url is unset for all of them",
862
+ file=sys.stderr,
863
+ )
864
+ retval = signals
865
+ return retval
866
+
867
+
868
+ def _build_agentmail_transport(cfg: dict) -> Source:
869
+ workspace = cfg.get("workspace")
870
+ if not workspace:
871
+ raise RuntimeError(
872
+ "slack-workspace source (transport: agentmail) needs 'workspace' "
873
+ "(a label for humans/meta — credentials are resolved per transport, "
874
+ "not from this field)"
875
+ )
876
+
877
+ inbox = cfg.get("inbox") or os.environ.get("AGENTMAIL_EMAIL")
878
+ if not inbox:
879
+ raise RuntimeError(
880
+ "slack-workspace source (transport: agentmail) needs 'inbox' in "
881
+ "config or AGENTMAIL_EMAIL in env"
882
+ )
883
+
884
+ key_env = cfg.get("api_key_env", "AGENTMAIL_API_KEY")
885
+ api_key = os.environ.get(key_env)
886
+ if not api_key:
887
+ raise RuntimeError(
888
+ f"slack-workspace source (transport: agentmail) needs the API key in ${key_env}"
889
+ )
890
+
891
+ agentmail = AgentMailSource(
892
+ inbox=inbox,
893
+ api_key=api_key,
894
+ limit=int(cfg.get("limit", 50)),
895
+ from_contains=cfg.get("from_contains"),
896
+ subject_contains=cfg.get("subject_contains"),
897
+ fetch_body=bool(cfg.get("fetch_body", True)),
898
+ include_trash=bool(cfg.get("include_trash", False)),
899
+ label=f"slack-workspace:{workspace}",
900
+ timeout=int(cfg.get("timeout", 30)),
901
+ )
902
+ retval = _AgentmailTransport(
903
+ agentmail=agentmail,
904
+ workspace=workspace,
905
+ channels=cfg.get("channels") or [],
906
+ )
907
+ return retval
908
+
909
+
910
+ def _build_session_transport(cfg: dict) -> Source:
911
+ workspace = cfg.get("workspace")
912
+ if not workspace:
913
+ raise RuntimeError(
914
+ "slack-workspace source (transport: session) needs 'workspace' "
915
+ "(a label for Signal.source/meta, not a credential)"
916
+ )
917
+ subdomain = cfg.get("subdomain")
918
+ if not subdomain:
919
+ raise RuntimeError(
920
+ "slack-workspace source (transport: session) needs 'subdomain' "
921
+ "(the <subdomain> in <subdomain>.slack.com)"
922
+ )
923
+ channels = cfg.get("channels") or []
924
+ if not channels:
925
+ raise RuntimeError(
926
+ "slack-workspace source (transport: session) needs a non-empty "
927
+ "'channels' list of channel names or conversation ids"
928
+ )
929
+ from_users = cfg.get("from_users") or []
930
+ if not isinstance(from_users, list):
931
+ raise RuntimeError(
932
+ "slack-workspace source (transport: session): 'from_users' must be a "
933
+ "list of user ids"
934
+ )
935
+
936
+ # Local import on purpose: pycookiecheat is optional, and the #40 import
937
+ # isolation is per module. Importing it at module scope would take the
938
+ # agentmail transport down on a venv without it.
939
+ try:
940
+ import pycookiecheat
941
+ except ImportError as exc:
942
+ raise RuntimeError(
943
+ "slack-workspace source (transport: session) needs the optional "
944
+ "dependency pycookiecheat: pip install '.[slack-session]'"
945
+ ) from exc
946
+
947
+ browser_name = str(cfg.get("browser", "chrome"))
948
+ try:
949
+ browser = pycookiecheat.BrowserType(browser_name)
950
+ except ValueError as exc:
951
+ known = ", ".join(b.value for b in pycookiecheat.BrowserType)
952
+ raise RuntimeError(
953
+ f"slack-workspace source (transport: session): unknown browser "
954
+ f"{browser_name!r}; pycookiecheat knows: {known}"
955
+ ) from exc
956
+
957
+ def _read_cookies(url: str) -> dict[str, str]:
958
+ retval = pycookiecheat.get_cookies(url, browser=browser)
959
+ return retval
960
+
961
+ client = _SessionClient(
962
+ subdomain=subdomain,
963
+ cookie_reader=_read_cookies,
964
+ timeout=int(cfg.get("timeout", 30)),
965
+ )
966
+ retval = _SessionTransport(
967
+ client=client,
968
+ workspace=workspace,
969
+ channels=list(channels),
970
+ since_hours=float(cfg.get("since_hours", 24)),
971
+ include_threads=bool(cfg.get("include_threads", True)),
972
+ from_users=[str(u) for u in from_users],
973
+ )
974
+ return retval
975
+
976
+ _TRANSPORTS: dict[str, Callable[[dict], Source]] = {
977
+ "agentmail": _build_agentmail_transport,
978
+ "session": _build_session_transport,
979
+ }
980
+
981
+
982
+ @register_source("slack-workspace")
983
+ def build(cfg: dict) -> Source:
984
+ transport_name = cfg.get("transport", "agentmail")
985
+ builder = _TRANSPORTS.get(transport_name)
986
+ if builder is None:
987
+ known = ", ".join(sorted(_TRANSPORTS))
988
+ raise RuntimeError(
989
+ f"slack-workspace source: unknown transport {transport_name!r}; known: {known}"
990
+ )
991
+ retval = builder(cfg)
992
+ return retval