@stratusagent/channel-slack 0.11.0 → 0.11.1

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.
package/dist/index.js CHANGED
@@ -7,6 +7,35 @@ import { channelSessionKey, } from '@stratusagent/channels';
7
7
  const SLACK_MAX_MESSAGE_CHARS = 4000;
8
8
  const DEFAULT_EDIT_INTERVAL_MS = 1000;
9
9
  const DEDUPE_CAPACITY = 2000;
10
+ /**
11
+ * How many threads' addressees are remembered in receipt order. Past this
12
+ * the least recently addressed is dropped, which costs its next follow-up
13
+ * one session lookup — the durable answer, which is what a restart falls
14
+ * back to anyway.
15
+ */
16
+ const THREAD_ADDRESSEE_CAPACITY = 2000;
17
+ /**
18
+ * How many cold verdicts are remembered. Far smaller than the addressee
19
+ * map: one is wanted only while the agents sharing a thread resolve the
20
+ * same message, and the addressee record answers for every message after.
21
+ */
22
+ const COLD_VERDICT_CAPACITY = 256;
23
+ /**
24
+ * How many changes of hands one thread remembers.
25
+ *
26
+ * A message older than all of them asks the sessions instead, which answer
27
+ * for the thread as it stands rather than as it stood — so a reply that old
28
+ * can be resolved to the agent holding the thread now. That is the cost of
29
+ * bounding this, and something has to bound it: the alternative is a list
30
+ * that grows with a conversation for the life of the daemon.
31
+ *
32
+ * Eight is chosen to sit far past the case it covers. This only has to
33
+ * span the lag between two sockets, which is messages inside one delivery
34
+ * window; crossing it needs a single thread to change hands eight times —
35
+ * eight mentions, alternating between agents — while one socket stays
36
+ * behind for all of them.
37
+ */
38
+ const THREAD_HANDOVER_DEPTH = 8;
10
39
  /**
11
40
  * How many files an unrendered turn may queue for its outcome. Nothing
12
41
  * drains that queue until the outcome arrives, so a session whose outcome
@@ -438,9 +467,9 @@ const truncateForSlack = (text) => text.length <= SLACK_MAX_MESSAGE_CHARS
438
467
  * point of writing a span as ``code with a ` in it`` and a fence as ````
439
468
  * when the block itself contains ```.
440
469
  */
441
- const closingBacktickRun = (text, from, length) => {
470
+ const closingBacktickRun = (text, from, length, limit) => {
442
471
  const run = '`'.repeat(length);
443
- for (let at = text.indexOf(run, from); at !== -1; at = text.indexOf(run, at + 1)) {
472
+ for (let at = text.indexOf(run, from); at !== -1 && at + length <= limit; at = text.indexOf(run, at + 1)) {
444
473
  if (text[at - 1] !== '`' && text[at + length] !== '`') {
445
474
  return at;
446
475
  }
@@ -456,12 +485,22 @@ const closingBacktickRun = (text, from, length) => {
456
485
  * the same rule for a span and for a fence and is why a longer delimiter
457
486
  * can carry a shorter one inside it.
458
487
  *
488
+ * A span may close on a later line, and is protected the whole way. That
489
+ * looks wasteful — two stray backticks paragraphs apart become one long
490
+ * "span" whose contents are left unconverted — and it was briefly changed
491
+ * to end a span at its line for exactly that reason. That was wrong, and
492
+ * the reason is the rule this whole file answers to: what Slack does with
493
+ * the message decides, not what Markdown says. Slack pairs those backticks
494
+ * too, so the text between them is what it renders as code, and rewriting
495
+ * a `**bold**` in there would alter the contents of somebody's snippet.
496
+ * Leaving prose unconverted is a cosmetic loss; changing what a reader is
497
+ * told is code is not, so the doubt resolves toward protecting more.
498
+ *
459
499
  * A fence with no closer runs to the end on purpose: a model that forgets
460
500
  * to close one, and every partially streamed block on its way to being
461
501
  * closed, would otherwise have its contents rewritten as prose. One or two
462
- * unmatched backticks are the opposite case — literal text, as they are in
463
- * Markdown, since "use the ` character" must not swallow the rest of the
464
- * message.
502
+ * unmatched backticks are the opposite case — literal text, since "use the
503
+ * ` character" must not swallow what follows.
465
504
  */
466
505
  const proseAndCode = (text) => {
467
506
  const segments = [];
@@ -476,7 +515,7 @@ const proseAndCode = (text) => {
476
515
  while (text[open + length] === '`') {
477
516
  length += 1;
478
517
  }
479
- const close = closingBacktickRun(text, open + length, length);
518
+ const close = closingBacktickRun(text, open + length, length, text.length);
480
519
  if (close === -1) {
481
520
  if (length < 3) {
482
521
  cursor = open + length;
@@ -522,26 +561,131 @@ const MRKDWN_REWRITES = [
522
561
  * The optional closing hashes have to be spaced off the text, as Markdown
523
562
  * requires: without that, `# C#` is a heading whose name loses its last
524
563
  * character.
564
+ *
565
+ * What they and any trailing spaces cover is captured rather than dropped,
566
+ * because dropping is only right when they are the heading's own syntax. A
567
+ * heading that opens a code span reaches its end inside one, and there the
568
+ * same characters are the snippet: `` # show `value # `` has a hash that
569
+ * belongs to whoever wrote the code.
525
570
  */
526
- const MARKDOWN_HEADING = /^ {0,3}#{1,6}[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*$/gm;
527
- /** One emphasis run and nothing else — `*Title*`, not `Some *word* here`. */
528
- const WHOLLY_BOLD = /^\*[^*]+\*$/;
529
- const convertProse = (segment) => {
571
+ const MARKDOWN_HEADING = /^ {0,3}#{1,6}[ \t]+(.+?)((?:[ \t]+#+)?[ \t]*)$/gm;
572
+ const convertInline = (segment) => {
530
573
  let converted = segment;
531
574
  for (const [pattern, replacement] of MRKDWN_REWRITES) {
532
575
  converted = converted.replace(pattern, replacement);
533
576
  }
534
- // Last, so the heading's own text is already converted. A heading a model
535
- // wrote as `## **Title**` is bold by then, and wrapping it again would
536
- // print the asterisks rather than render them. Nothing is stripped to get
537
- // there: an asterisk in a heading may be the text itself (`# glob *.ts`),
538
- // and a reply that reads oddly beats a reply that says something else.
539
- return converted.replace(MARKDOWN_HEADING, (line, body) => {
540
- const text = body.trim();
541
- if (text.length === 0) {
577
+ return converted;
578
+ };
579
+ /**
580
+ * Headings, found on the text's own lines rather than inside each prose
581
+ * fragment.
582
+ *
583
+ * A fragment is not a line: inline code cuts one in two, and the halves
584
+ * begin wherever the code ended. Matched per fragment, `^` then lied in
585
+ * both directions — the tail of `` `status` # not a heading `` looked like a
586
+ * line of its own and lost its hash, and ``## Run `npm test` now`` was only
587
+ * ever half a line, so only the half before the code was wrapped.
588
+ *
589
+ * So the whole text is matched instead, with the code spans it now contains
590
+ * passed in: a `#` whose line begins inside one is a comment in somebody's
591
+ * snippet, not a heading. A heading that merely *contains* code is a
592
+ * heading, and its code goes along untouched.
593
+ *
594
+ * Emphasis inside is already converted by here, so the line is only wrapped
595
+ * when nothing in it can pair with the wrapper. Slack has one bold
596
+ * delimiter and no way to nest it: wrapping `*Run* the thing` again yields
597
+ * `**Run* the thing*`, which it renders as literal asterisks rather than as
598
+ * anything bold. A heading that already carries emphasis therefore keeps
599
+ * exactly the emphasis it has — `## **Title**` is bold by now and needs
600
+ * nothing more, and `# glob *.ts` keeps an asterisk that was never a marker
601
+ * at all. An unbolded heading reads fine; a heading full of stray asterisks
602
+ * does not, and one with characters removed to make room is worse than both.
603
+ *
604
+ * An asterisk inside a code span is not one of those: Slack does not read
605
+ * markup there, so it cannot pair with anything, and ``## Match `*.ts` files``
606
+ * is bolded like any other heading.
607
+ *
608
+ * Both walks are cursors rather than searches: `replace` reports matches in
609
+ * increasing offset, and the spans were collected in that order too, so
610
+ * neither has to be looked at twice. The same work as a scan per heading,
611
+ * without its quadratic on a reply that is mostly headings and snippets.
612
+ */
613
+ /** What could pair with a heading's wrapper, or with something out of sight. */
614
+ const PAIRABLE_MARKER = /[*`]/g;
615
+ const convertHeadings = (text, code) => {
616
+ let span = 0;
617
+ const startsInside = (position, from) => position >= (code[from]?.[0] ?? Number.POSITIVE_INFINITY);
618
+ return text.replace(MARKDOWN_HEADING, (line, body, tail, offset) => {
619
+ while (span < code.length && (code[span]?.[1] ?? 0) <= offset) {
620
+ span += 1;
621
+ }
622
+ // A `#` whose line begins inside a span is a comment in somebody's code.
623
+ if (startsInside(offset, span)) {
624
+ return line;
625
+ }
626
+ const heading = body.trim();
627
+ if (heading.length === 0) {
542
628
  return line;
543
629
  }
544
- return WHOLLY_BOLD.test(text) ? text : `*${text}*`;
630
+ // Where everything this would drop from the line's end begins: the
631
+ // closing hashes and spaces the pattern captured, and whatever else
632
+ // `trimEnd` would take with them. The two are not the same set — the
633
+ // pattern knows only spaces and tabs, while trimming also takes a
634
+ // no-break space, an ideographic space, and the rest of what
635
+ // ECMAScript counts as whitespace — and the difference is exactly
636
+ // where a character goes missing.
637
+ //
638
+ // Dropping any of it is the heading's own syntax being removed, but
639
+ // only while it is the heading's: a line that opens a span reaches its
640
+ // end inside one, and there the same characters are somebody's
641
+ // snippet. Nothing on this line is safe to strip then, so it is left
642
+ // exactly as written. (The front needs no such care: the body starts
643
+ // where the hashes stop, which this line has already been shown to
644
+ // reach in prose.)
645
+ const dropped = tail.length + (body.length - body.trimEnd().length);
646
+ if (dropped > 0) {
647
+ const droppedAt = offset + line.length - dropped;
648
+ let over = span;
649
+ while (over < code.length && (code[over]?.[1] ?? 0) <= droppedAt) {
650
+ over += 1;
651
+ }
652
+ if (startsInside(droppedAt, over)) {
653
+ return line;
654
+ }
655
+ }
656
+ // Anything left on the line that a delimiter could pair with, walked
657
+ // from where the heading cursor already stands rather than from the
658
+ // beginning. An asterisk is the obvious one — it would pair with the
659
+ // wrapper. A backtick counts too: one this side found no partner for is
660
+ // a literal character here, but Slack parses the message itself and may
661
+ // pair it with a backtick further down, and the wrapper's closing `*`
662
+ // would then be written inside what Slack reads as code, where it is
663
+ // ignored — leaving the opening one with nothing to close it. Both are
664
+ // spent characters inside a span, which is why the ranges are consulted
665
+ // rather than the text alone.
666
+ let within = span;
667
+ for (const marker of line.matchAll(PAIRABLE_MARKER)) {
668
+ const position = offset + (marker.index ?? 0);
669
+ while (within < code.length && (code[within]?.[1] ?? 0) <= position) {
670
+ within += 1;
671
+ }
672
+ if (!startsInside(position, within)) {
673
+ return heading;
674
+ }
675
+ }
676
+ // Both markers have to land in prose, not just the opening one. A fence
677
+ // opened on this line — by a model mid-answer, or by a block still being
678
+ // streamed — runs past its end, so the closing `*` would be written
679
+ // inside the code and ignored there, leaving the opening one unpaired.
680
+ // The line began in prose or this never ran, so it is the end that is
681
+ // in question: where the marker would go, one past the line's last
682
+ // character, and not that character itself — a span that closes exactly
683
+ // at the line's end leaves the marker just outside it, which is fine.
684
+ const closer = offset + line.length;
685
+ while (within < code.length && (code[within]?.[1] ?? 0) <= closer) {
686
+ within += 1;
687
+ }
688
+ return startsInside(closer, within) ? heading : `*${heading}*`;
545
689
  });
546
690
  };
547
691
  /**
@@ -558,9 +702,30 @@ const convertProse = (segment) => {
558
702
  * already mean in mrkdwn what they mean in Markdown; rewriting them would
559
703
  * add ways to be wrong and fix nothing.
560
704
  */
561
- const toSlackMrkdwn = (text) => proseAndCode(text)
562
- .map((segment, index) => (index % 2 === 1 ? segment : convertProse(segment)))
563
- .join('');
705
+ const toSlackMrkdwn = (text) => {
706
+ // Where each code span ends up in the converted text, which is not where
707
+ // it started: the prose before it changes length as it is rewritten.
708
+ const code = [];
709
+ const segments = proseAndCode(text);
710
+ let converted = '';
711
+ segments.forEach((segment, index) => {
712
+ if (index % 2 === 1) {
713
+ // A code segment that ends the text is the unterminated fence: every
714
+ // closed run is followed by a prose slice, even an empty one. It has
715
+ // no end to be past, so nothing may be appended after it either —
716
+ // recording the end as it looks would say a marker placed at the
717
+ // text's end was safely outside.
718
+ const ends = index === segments.length - 1
719
+ ? Number.POSITIVE_INFINITY
720
+ : converted.length + segment.length;
721
+ code.push([converted.length, ends]);
722
+ converted += segment;
723
+ return;
724
+ }
725
+ converted += convertInline(segment);
726
+ });
727
+ return convertHeadings(converted, code);
728
+ };
564
729
  const splitForSlack = (text) => {
565
730
  if (text.length <= SLACK_MAX_MESSAGE_CHARS) {
566
731
  return [text];
@@ -638,6 +803,45 @@ const OUTCOME_TEXT = {
638
803
  const APPROVAL_INPUT_LIMIT = 1400;
639
804
  /** One line in a notification; the blocks carry the readable version. */
640
805
  const APPROVAL_SUMMARY_LIMIT = 160;
806
+ /**
807
+ * Subtypes that are still a person saying something, rather than Slack
808
+ * narrating the channel. Everything else a `subtype` marks — an edit, a
809
+ * deletion, a join, a pinned file — is bookkeeping, and an agent following
810
+ * a thread must not answer bookkeeping.
811
+ *
812
+ * These three are here because each is an ordinary thing a person does:
813
+ * `file_share` is a message that happens to carry an attachment (asking a
814
+ * question with the log attached is the normal way to ask it),
815
+ * `thread_broadcast` is a thread reply the author also sent to the channel,
816
+ * and `me_message` is what `/me` produces — typed by a person, in their own
817
+ * words, and marked only by how it is rendered.
818
+ */
819
+ const HUMAN_MESSAGE_SUBTYPES = new Set(['file_share', 'me_message', 'thread_broadcast']);
820
+ const isPersonSpeaking = (event) => event.subtype === undefined || HUMAN_MESSAGE_SUBTYPES.has(event.subtype);
821
+ /** At most this many attachment names are listed; the rest are counted. */
822
+ const MAX_LISTED_ATTACHMENTS = 5;
823
+ /**
824
+ * What a message's attachments are called, for a turn that cannot open
825
+ * them. Without this the agent is handed "here's the log" and no log, and
826
+ * answers as though it had read something — the note is what lets it say
827
+ * the true thing instead.
828
+ */
829
+ const attachmentNote = (files) => {
830
+ if (!files || files.length === 0) {
831
+ return '';
832
+ }
833
+ const names = files.slice(0, MAX_LISTED_ATTACHMENTS).map((file) => file.name ?? file.title ?? 'an unnamed file');
834
+ const rest = files.length - names.length;
835
+ const listed = rest > 0 ? `${names.join(', ')}, and ${rest} more` : names.join(', ');
836
+ return `\n[Attached: ${listed}. Attachment contents cannot be read here — say so rather than guessing at them.]`;
837
+ };
838
+ /**
839
+ * Whether `text` addresses a bot user by name. Slack writes a mention as
840
+ * `<@U123>` markup whoever typed it, so this is the same question for an
841
+ * `app_mention` event and for a plain channel message the app now also
842
+ * sees.
843
+ */
844
+ const mentions = (text, botUserId) => botUserId.length > 0 && text.includes(`<@${botUserId}>`);
641
845
  /**
642
846
  * Slack's three markup characters. Tool input is written by a model, so it
643
847
  * reaches this message as untrusted text: unescaped, `<@U123>` becomes a
@@ -743,6 +947,14 @@ const approvalBlocks = (agentName, toolName, risk, requestId, input, origin, one
743
947
  * (DMs: the DM channel id alone), so threads are resumable conversations
744
948
  * and two agents sharing a thread keep fully separate sessions. Replies
745
949
  * stream via placeholder-then-edit, throttled for chat.update limits.
950
+ *
951
+ * A mention starts a thread conversation; inside one, the agent keeps
952
+ * listening without being tagged again — see `couldBeFollowUp` and
953
+ * `answersFollowUp` for exactly whose reply an untagged message is. That
954
+ * needs the app to be subscribed to `message.channels` / `message.groups`
955
+ * / `message.mpim` (the shipped manifest is); an app installed before
956
+ * those were in it receives only `app_mention` and behaves as it always
957
+ * did, which makes the workspace's own grant the switch.
746
958
  */
747
959
  export const createSlackChannelAdapter = (options) => {
748
960
  const log = options.log ?? (() => { });
@@ -776,6 +988,75 @@ export const createSlackChannelAdapter = (options) => {
776
988
  // Socket Mode redelivers on missed acks; a slow turn must not run twice.
777
989
  const seenEvents = new Set();
778
990
  const seenOrder = [];
991
+ /**
992
+ * Who each thread was last handed to, in SLACK RECEIPT ORDER — written
993
+ * the moment a message is accepted for an agent, before any of the work
994
+ * that message causes.
995
+ *
996
+ * The durable answer (`answersFollowUp`) is the agents' own sessions,
997
+ * and it lags: a session row is written when its turn starts, which is a
998
+ * display-name lookup and a placeholder post after the message that
999
+ * asked for it. Inside that window the persisted order still names the
1000
+ * agent that spoke *before* the handover, so a mention of Bea followed
1001
+ * straight away by an untagged addendum would send the addendum to Ava —
1002
+ * and a follow-up typed on the heels of the mention that opened the
1003
+ * thread would find no session at all and be dropped for good.
1004
+ *
1005
+ * Keyed by thread rather than by (agent, thread): one agent has it at a
1006
+ * time, so there is nothing to reconcile. The value is that thread's
1007
+ * HANDOVERS in order, not just its latest one, because the question an
1008
+ * untagged message asks is not "who holds this thread now" but "who held
1009
+ * it when I was sent". Those differ whenever a socket runs behind
1010
+ * another: Bea's connection can reject a pre-handover reply, then take
1011
+ * the mention that moves the thread to her, and Ava's connection reach
1012
+ * that same earlier reply afterwards — which the latest holder alone
1013
+ * would reject for a second time, dropping a message that was plainly
1014
+ * Ava's when it was written.
1015
+ *
1016
+ * Keeping the handovers also makes out-of-order writes ordinary rather
1017
+ * than dangerous. A connection several messages behind, or a redelivered
1018
+ * envelope carrying an old mention, inserts into the past where it
1019
+ * belongs instead of overwriting the present.
1020
+ *
1021
+ * Bounded and lossy on purpose — evicting an entry costs one lookup,
1022
+ * since the sessions still hold the answer for every thread this map has
1023
+ * forgotten, and for every thread a restart forgot.
1024
+ *
1025
+ * One thing they cannot reconstruct: a handover made in the seconds
1026
+ * before the daemon went down. The mention that moved the thread is
1027
+ * recorded only here, and the newly named agent has not replied yet, so
1028
+ * after a restart the sessions still name the previous speaker and the
1029
+ * next untagged reply goes to them. Surviving that needs durable
1030
+ * adapter-owned state, which the channel contract deliberately does not
1031
+ * have — an adapter reads routing and translates events, and inventing a
1032
+ * private store here is the wrong place to answer it. The next mention
1033
+ * corrects it.
1034
+ */
1035
+ const threadAddressee = new Map();
1036
+ /**
1037
+ * One cold verdict per message — see `followUpWinner`. Bounded, because
1038
+ * an entry outlives its own resolution on purpose; an entry that has not
1039
+ * yet resolved is never the one evicted, since the agent still waiting on
1040
+ * it would otherwise start a second one.
1041
+ */
1042
+ const coldVerdicts = new Map();
1043
+ /**
1044
+ * `agentId` → bot user id, for every app whose token this adapter has
1045
+ * authenticated — whether or not its socket then came up, and kept for as
1046
+ * long as the adapter runs.
1047
+ *
1048
+ * Separate from `connections` because recognizing that somebody was named
1049
+ * and being able to answer are different questions. An agent whose app is
1050
+ * down cannot answer anything; a message that names it is still not the
1051
+ * other agent's to take, and treating it as untagged would have the wrong
1052
+ * agent answer a question a person deliberately handed elsewhere. Silence
1053
+ * is the correct outcome there, and it is also the visible one — the same
1054
+ * thing a mention has always done when an app is down.
1055
+ *
1056
+ * Insertion order is `options.agents` order, which is what makes
1057
+ * `agentNamedIn` deterministic across every connection.
1058
+ */
1059
+ const botIdentities = new Map();
779
1060
  // Rendered approval requests, keyed by the gateway's request id — the
780
1061
  // same id the buttons carry back.
781
1062
  const approvalPosts = new Map();
@@ -1348,47 +1629,432 @@ export const createSlackChannelAdapter = (options) => {
1348
1629
  warn(`slack: could not send an ephemeral notice: ${error instanceof Error ? error.message : String(error)}`);
1349
1630
  }
1350
1631
  };
1351
- const handleInbound = async (connection, args) => {
1352
- // Ack immediately: Slack redelivers unacked envelopes, and a turn can
1353
- // outlive the ack window many times over.
1354
- await args.ack();
1632
+ /** One thread, whichever agent is talking in it. */
1633
+ const threadKeyFor = (parts) => `${parts.team}:${parts.conversation}:${parts.thread}`;
1634
+ /**
1635
+ * Records that `agentId` holds the thread from the message at `ts`
1636
+ * onwards, wherever in the thread's history that message falls.
1637
+ *
1638
+ * Only actual handovers are kept: a write naming the agent that already
1639
+ * held the thread at that point adds nothing, so the list stays as short
1640
+ * as the conversation's changes of hands rather than growing per message.
1641
+ * The oldest handovers are dropped past `THREAD_HANDOVER_DEPTH`, and the
1642
+ * least recently written thread past `THREAD_ADDRESSEE_CAPACITY`; both
1643
+ * losses cost a lookup, never an answer, since the sessions still hold
1644
+ * the durable version.
1645
+ *
1646
+ * Slack timestamps compare as strings: `seconds.microseconds`, both
1647
+ * parts fixed width, so lexicographic order is chronological order.
1648
+ */
1649
+ const rememberAddressee = (key, agentId, ts) => {
1650
+ const handovers = threadAddressee.get(key) ?? [];
1651
+ let at = handovers.length;
1652
+ while (at > 0 && handovers[at - 1].ts > ts) {
1653
+ at -= 1;
1654
+ }
1655
+ const before = handovers[at - 1];
1656
+ if (before && before.agentId === agentId) {
1657
+ // Already this agent's from earlier in the thread; the same message
1658
+ // reaching a second connection lands here too.
1659
+ return;
1660
+ }
1661
+ handovers.splice(at, 0, { agentId, ts });
1662
+ // Re-inserted rather than mutated in place: a Map iterates in insertion
1663
+ // order, which is what makes the first key the one to evict.
1664
+ threadAddressee.delete(key);
1665
+ threadAddressee.set(key, handovers.slice(-THREAD_HANDOVER_DEPTH));
1666
+ if (threadAddressee.size > THREAD_ADDRESSEE_CAPACITY) {
1667
+ const oldest = threadAddressee.keys().next();
1668
+ if (!oldest.done) {
1669
+ threadAddressee.delete(oldest.value);
1670
+ }
1671
+ }
1672
+ };
1673
+ /**
1674
+ * Who held the thread when the message at `ts` was sent — the last
1675
+ * handover at or before it. Undefined when this process has no handover
1676
+ * that old, which sends the question to the sessions.
1677
+ */
1678
+ const holderAt = (key, ts) => {
1679
+ const handovers = threadAddressee.get(key);
1680
+ if (!handovers) {
1681
+ return undefined;
1682
+ }
1683
+ for (let index = handovers.length - 1; index >= 0; index -= 1) {
1684
+ const handover = handovers[index];
1685
+ if (handover && handover.ts <= ts) {
1686
+ return handover.agentId;
1687
+ }
1688
+ }
1689
+ return undefined;
1690
+ };
1691
+ /**
1692
+ * Which of this process's agents a message names, or undefined if it
1693
+ * names none of them.
1694
+ *
1695
+ * When it names several, the first that is actually serving — and any
1696
+ * of them otherwise. That determinism is the point: every connection sees every message and runs
1697
+ * this over the same text and the same array, so all of them agree on who
1698
+ * a message handed the thread to — including the connections that will go
1699
+ * on to ignore it. Which is what makes the handover record converge
1700
+ * without the sockets having to agree on anything, since each agent is
1701
+ * its own Socket Mode connection and one can run minutes behind another.
1702
+ *
1703
+ * Scoped to the message's own workspace, because a bot user id is only
1704
+ * unique within one — the same reason the display-name cache is keyed by
1705
+ * team. Two agents in two workspaces can hold the same id, and resolving
1706
+ * a mention to the wrong one would hand the thread to an agent that
1707
+ * cannot see it, leaving the agent that was actually named refusing every
1708
+ * reply after.
1709
+ *
1710
+ * Only agents this adapter has authenticated can be recognized at all.
1711
+ * One served by another daemon is invisible here, and both would answer;
1712
+ * so is one whose `auth.test` itself failed, since its bot id was never
1713
+ * learned.
1714
+ */
1715
+ const agentNamedIn = (text, team) => {
1716
+ let offline;
1717
+ for (const [agentId, identity] of botIdentities) {
1718
+ if (identity.teamId !== team || !mentions(text, identity.botUserId)) {
1719
+ continue;
1720
+ }
1721
+ if (connections.some((live) => live.config.agentId === agentId)) {
1722
+ return agentId;
1723
+ }
1724
+ // Named, recognized, and not serving. Remembered only as the answer
1725
+ // of last resort: a message that names an agent whose app is down and
1726
+ // nobody else still gets silence, which is the deliberate behavior —
1727
+ // but a message that also names one that IS serving must leave the
1728
+ // thread with the agent that can actually answer it, or the reply it
1729
+ // just posted would be the last anyone gets.
1730
+ offline ??= agentId;
1731
+ }
1732
+ return offline;
1733
+ };
1734
+ /**
1735
+ * Who an untagged reply belongs to, asked of the SESSIONS — the durable
1736
+ * answer, for a thread this process has no record of: one it has not seen
1737
+ * a message in since it started, or one evicted from `threadAddressee`.
1738
+ * Everything else is settled synchronously in `admit`, before this is
1739
+ * ever reached.
1740
+ *
1741
+ * Being in the thread is the first half: a session under a thread's key
1742
+ * exists only because someone mentioned that agent here, so an agent
1743
+ * follows up only in conversations it was invited into, and stops when
1744
+ * the thread is gone. `sessionRouting` is the durable record of that — a
1745
+ * restart forgets nothing.
1746
+ *
1747
+ * Whose turn it is, is the second. In a thread with several agents an
1748
+ * unaddressed reply belongs to **whoever spoke last**, the way it does
1749
+ * between people: answer the voice that just answered you, and tag
1750
+ * someone by name to change that. `lastSpokeAt` orders them — when each
1751
+ * agent last *replied*, not when its session last changed, because a turn
1752
+ * saves on tool results and approval checkpoints without having said
1753
+ * anything, and a recovery resuming after a restart lands in exactly this
1754
+ * window.
1755
+ *
1756
+ * Nobody is the answer only when the agents cannot be *ordered* — nothing
1757
+ * in the thread has spoken (a host whose routing carries no `lastSpokeAt`
1758
+ * at all reads this way, and so does a thread where every agent is still
1759
+ * on its first turn), or the newest two tie — because guessing there
1760
+ * would put two answers under one message. An agent that simply has not
1761
+ * spoken is a different thing and is skipped rather than fatal: it cannot
1762
+ * have spoken last, and letting it silence the agent that did would leave
1763
+ * a reply nobody answers. The agent alone in its thread, which is nearly
1764
+ * every thread, is answered without the question arising.
1765
+ */
1766
+ const resolveFollowUpWinner = async (parts) => {
1355
1767
  const gateway = gatewayRef;
1768
+ if (!gateway?.sessionRouting || !parts.thread) {
1769
+ return undefined;
1770
+ }
1771
+ const engaged = [];
1772
+ // Live connections in this message's OWN workspace. Live, because an
1773
+ // agent whose app failed to connect cannot answer anything, and leaving
1774
+ // a thread silent because its last speaker is offline is the bug this
1775
+ // whole change exists to remove. In-workspace, because a session key
1776
+ // carries a team: an agent whose app has moved workspaces still has its
1777
+ // old sessions there, and letting those contend for a thread it can no
1778
+ // longer receive a message in would leave nobody to answer.
1779
+ for (const candidate of connections) {
1780
+ if (candidate.teamId !== parts.team) {
1781
+ continue;
1782
+ }
1783
+ const routing = await gateway.sessionRouting(channelSessionKey({
1784
+ channel: 'slack',
1785
+ agentId: candidate.config.agentId,
1786
+ team: parts.team,
1787
+ conversation: parts.conversation,
1788
+ thread: parts.thread,
1789
+ }));
1790
+ if (!routing) {
1791
+ continue;
1792
+ }
1793
+ engaged.push({
1794
+ agentId: candidate.config.agentId,
1795
+ ...(routing.lastSpokeAt !== undefined ? { lastSpokeAt: routing.lastSpokeAt } : {}),
1796
+ });
1797
+ }
1798
+ const first = engaged[0];
1799
+ if (!first) {
1800
+ return undefined;
1801
+ }
1802
+ if (engaged.length === 1) {
1803
+ return first.agentId;
1804
+ }
1805
+ let latest;
1806
+ let tied = false;
1807
+ for (const entry of engaged) {
1808
+ if (entry.lastSpokeAt === undefined) {
1809
+ // In the thread, but has never said anything in it — mentioned and
1810
+ // still on its first turn, or a turn that produced no text. It
1811
+ // cannot be the one who spoke last, and it must not stop the agent
1812
+ // that did from answering.
1813
+ continue;
1814
+ }
1815
+ if (!latest || entry.lastSpokeAt > latest.lastSpokeAt) {
1816
+ latest = { agentId: entry.agentId, lastSpokeAt: entry.lastSpokeAt };
1817
+ tied = false;
1818
+ }
1819
+ else if (entry.lastSpokeAt === latest.lastSpokeAt) {
1820
+ tied = true;
1821
+ }
1822
+ }
1823
+ return tied ? undefined : latest?.agentId;
1824
+ };
1825
+ /**
1826
+ * `resolveFollowUpWinner`, resolved ONCE PER MESSAGE and shared by every
1827
+ * agent asking about that message.
1828
+ *
1829
+ * The sharing is the point. Each agent's own copy of the question is
1830
+ * several independent session reads, and turns finishing in between can
1831
+ * make two agents' reads disagree: both concluding they are the most
1832
+ * recent speaker, so one message is answered twice, or both concluding
1833
+ * they are not, so it is answered by nobody. One resolution cannot
1834
+ * disagree with itself, which is a stronger guarantee than arbitrating
1835
+ * between two that already have.
1836
+ *
1837
+ * Keyed on the message, so a later reply in the same thread asks again.
1838
+ * Bounded, and deliberately not deleted when it settles: an entry has to
1839
+ * outlive its own resolution, because an agent it beats may only reach
1840
+ * this after the winner has finished, and recomputing for that agent is
1841
+ * precisely the disagreement the memo exists to prevent.
1842
+ */
1843
+ const followUpWinner = (parts, ts) => {
1844
+ const key = `${threadKeyFor(parts)}:${ts}`;
1845
+ const existing = coldVerdicts.get(key);
1846
+ if (existing) {
1847
+ return existing.verdict;
1848
+ }
1849
+ const entry = { verdict: resolveFollowUpWinner(parts), settled: false };
1850
+ coldVerdicts.set(key, entry);
1851
+ void entry.verdict.then(() => {
1852
+ entry.settled = true;
1853
+ }, () => {
1854
+ entry.settled = true;
1855
+ });
1856
+ if (coldVerdicts.size > COLD_VERDICT_CAPACITY) {
1857
+ // The oldest SETTLED entry, never simply the oldest. Evicting one
1858
+ // still resolving is the one eviction that costs an answer rather
1859
+ // than a lookup: the agent it has not reached yet would start its own
1860
+ // resolution, which is the disagreement this memo exists to prevent.
1861
+ // With none settled there is nothing safe to drop, and the map runs
1862
+ // over its cap by however many resolutions are genuinely in flight.
1863
+ for (const [candidate, held] of coldVerdicts) {
1864
+ if (held.settled) {
1865
+ coldVerdicts.delete(candidate);
1866
+ break;
1867
+ }
1868
+ }
1869
+ }
1870
+ return entry.verdict;
1871
+ };
1872
+ /**
1873
+ * Everything about who a message is for that can be decided WITHOUT
1874
+ * AWAITING, run straight off the socket's own event emission — so for the
1875
+ * whole of it, this process is exactly as far through the conversation as
1876
+ * Slack is.
1877
+ *
1878
+ * That is the point of it being one synchronous block. The Socket Mode
1879
+ * client emits envelopes in order, but `ack()` resolves from a WebSocket
1880
+ * send callback, so two handlers that ack before deciding anything can
1881
+ * come back in either order: a follow-up could then overtake the mention
1882
+ * that opened its thread, find neither a record nor a session, and be
1883
+ * dropped for good. Nothing here awaits, so nothing can be overtaken —
1884
+ * the dedupe and the handover record included, which are the two pieces a
1885
+ * later message reads.
1886
+ *
1887
+ * `undefined` means the message is not this agent's. `settled: false`
1888
+ * means only the sessions can still decide it, which is the one case that
1889
+ * has to wait — and it is the cold case, where by definition no message
1890
+ * of this thread has been seen in this process.
1891
+ */
1892
+ const admit = (connection, args) => {
1356
1893
  const event = args.event;
1357
- if (!gateway || !event || !event.user || event.bot_id || event.subtype) {
1358
- return;
1894
+ if (!gatewayRef || !event || !event.user || event.bot_id || !isPersonSpeaking(event)) {
1895
+ return undefined;
1359
1896
  }
1360
- const isDm = event.channel_type === 'im';
1361
- if (event.type !== 'app_mention' && !(event.type === 'message' && isDm)) {
1362
- // Mention-only outside DMs.
1363
- return;
1897
+ if (event.type !== 'app_mention' && event.type !== 'message') {
1898
+ return undefined;
1364
1899
  }
1365
1900
  if (event.user === connection.botUserId) {
1366
- return;
1367
- }
1368
- const eventKey = `${connection.config.agentId}:${args.body?.event_id ?? args.envelope_id ?? `${event.channel}:${event.ts}`}`;
1369
- if (alreadySeen(eventKey)) {
1370
- return;
1901
+ return undefined;
1371
1902
  }
1903
+ const isDm = event.channel_type === 'im';
1372
1904
  const team = args.body?.team_id ?? connection.teamId;
1373
- const userId = event.user;
1374
1905
  // A top-level mention has no thread_ts; its own ts roots the reply
1375
1906
  // thread that becomes the conversation. DMs are one conversation per
1376
1907
  // peer, unkeyed by thread.
1377
1908
  const thread = isDm ? undefined : event.thread_ts ?? event.ts;
1378
- const sessionId = channelSessionKey({
1379
- channel: 'slack',
1380
- agentId: connection.config.agentId,
1909
+ // Threads only: a DM has one agent by construction.
1910
+ const threadKey = thread !== undefined && !isDm
1911
+ ? threadKeyFor({ team, conversation: event.channel, thread })
1912
+ : undefined;
1913
+ const text = event.text ?? '';
1914
+ const addressed = isDm || mentions(text, connection.botUserId);
1915
+ // Who this message hands the thread to — worked out by EVERY connection
1916
+ // that sees it, not only by the one being named, and recorded before any
1917
+ // of the rejections below. Each agent is its own Socket Mode connection,
1918
+ // so the message naming Bea reaches Ava's socket and Bea's socket
1919
+ // independently and in no fixed order; if only Bea recorded the
1920
+ // handover, Ava could take the next untagged reply while Bea's socket
1921
+ // was still behind, and answer a question that had just been handed
1922
+ // away. The message Ava must record is exactly the one Ava ignores.
1923
+ const named = agentNamedIn(text, team);
1924
+ if (threadKey && named) {
1925
+ rememberAddressee(threadKey, named, event.ts);
1926
+ }
1927
+ if (!addressed) {
1928
+ if (event.thread_ts === undefined) {
1929
+ // The room is not a conversation: a message that starts a thread,
1930
+ // or stands alone, is a follow-up to nothing.
1931
+ return undefined;
1932
+ }
1933
+ if (named) {
1934
+ // Somebody else was asked. Tagging an agent hands it the question,
1935
+ // and the agent that had it is no longer being asked — two answers
1936
+ // to one message is what a thread with a roster in it must never
1937
+ // produce.
1938
+ return undefined;
1939
+ }
1940
+ }
1941
+ // One Slack MESSAGE, not one delivery. An app subscribed to both
1942
+ // `app_mention` and `message.channels` is told about a mention twice —
1943
+ // two envelopes carrying two event ids — so keying this on the event
1944
+ // id would run the turn twice the moment thread follow-through was
1945
+ // switched on. `(channel, ts)` names the message itself, and a
1946
+ // redelivery (what the event id was here for) repeats both.
1947
+ //
1948
+ // After the handover record and not before it: a redelivery re-records
1949
+ // the same agent, which costs nothing, while deduping first would drop
1950
+ // the record whenever the other copy of a doubly-delivered mention is
1951
+ // the one a connection sees second.
1952
+ const eventKey = `${connection.config.agentId}:${event.channel}:${event.ts}`;
1953
+ if (alreadySeen(eventKey)) {
1954
+ return undefined;
1955
+ }
1956
+ const admission = {
1957
+ event,
1958
+ isDm,
1381
1959
  team,
1382
- conversation: event.channel,
1960
+ userId: event.user,
1961
+ sessionId: channelSessionKey({
1962
+ channel: 'slack',
1963
+ agentId: connection.config.agentId,
1964
+ team,
1965
+ conversation: event.channel,
1966
+ ...(thread ? { thread } : {}),
1967
+ }),
1383
1968
  ...(thread ? { thread } : {}),
1969
+ ...(threadKey ? { threadKey } : {}),
1970
+ settled: true,
1971
+ };
1972
+ if (addressed) {
1973
+ // A message that named this agent and others is recorded above under
1974
+ // whichever of them comes first in connection order — every agent
1975
+ // named answers it, and the thread it leaves behind has one holder
1976
+ // that all the sockets agree on, which is the only self-consistent
1977
+ // reading of a message that asked several.
1978
+ return admission;
1979
+ }
1980
+ // An untagged reply. The record is what this process has actually seen,
1981
+ // in the order it saw it — right even inside the window before a
1982
+ // handover reaches the store.
1983
+ const holder = threadKey === undefined ? undefined : holderAt(threadKey, event.ts);
1984
+ if (holder !== undefined && threadKey !== undefined) {
1985
+ if (holder !== connection.config.agentId) {
1986
+ // Standing down for the holder, whether or not the holder can still
1987
+ // hear it. An app removed from this channel stops receiving the
1988
+ // thread, and its untagged replies then reach nobody until somebody
1989
+ // names an agent — which is the same answer this adapter gives
1990
+ // whenever the agent being addressed cannot answer, and one mention
1991
+ // reopens the conversation. Doing better means per-channel
1992
+ // membership the adapter does not track, and would have to be
1993
+ // tracked in the durable path too, since a removed app is still a
1994
+ // live connection with the newest session there.
1995
+ return undefined;
1996
+ }
1997
+ rememberAddressee(threadKey, connection.config.agentId, event.ts);
1998
+ return admission;
1999
+ }
2000
+ // Nothing seen for this thread since startup: only the sessions can
2001
+ // answer, and that answer has to be awaited.
2002
+ return { ...admission, settled: false };
2003
+ };
2004
+ const handleInbound = async (connection, args) => {
2005
+ // Decided before the ack, never after it — see `admit`. That block is
2006
+ // map and string work measured in microseconds, against an ack window
2007
+ // Slack measures in seconds, and the envelope is acked below whatever
2008
+ // the decision was.
2009
+ const admitted = admit(connection, args);
2010
+ // Acked without awaiting it. The ack still leaves as promptly as it ever
2011
+ // did — Slack redelivers unacked envelopes, and a turn outlives the ack
2012
+ // window many times over — but nothing here needs its send callback, and
2013
+ // awaiting one was the single await between receiving a message and
2014
+ // taking its place in the queue below. Two handlers waiting on their
2015
+ // acks can come back in either order; two handlers that never wait
2016
+ // cannot. A failed ack costs a redelivery, which the dedupe absorbs.
2017
+ void Promise.resolve(args.ack()).catch((error) => {
2018
+ warn(`slack: could not ack an envelope: ${error instanceof Error ? error.message : String(error)}`);
1384
2019
  });
2020
+ if (!admitted) {
2021
+ return;
2022
+ }
2023
+ // Re-read rather than carried through the admission: `stop()` can clear
2024
+ // it while the ack above is in flight, and a dispatch into a gateway
2025
+ // this adapter has let go of is not one to start.
2026
+ const gateway = gatewayRef;
2027
+ if (!gateway) {
2028
+ return;
2029
+ }
2030
+ const { event, isDm, team, userId, thread, sessionId, threadKey } = admitted;
1385
2031
  // Everything up to (and including) the dispatch call is serialized per
1386
2032
  // session in Slack receipt order: the user lookups and placeholder
1387
2033
  // post below await network I/O, and without this chain a later message
1388
2034
  // could reach gateway.dispatch first — processing the conversation in
1389
- // reverse order in durable history.
2035
+ // reverse order in durable history. The chain is claimed here,
2036
+ // synchronously, so a message's place in it is fixed by when Slack
2037
+ // delivered it and not by how long anything it does takes.
1390
2038
  const previousIntake = intakeChains.get(sessionId) ?? Promise.resolve();
1391
2039
  const intake = previousIntake.then(async () => {
2040
+ // The durable half of addressing runs INSIDE the chain, for the same
2041
+ // reason: it awaits, and a message that had to ask the sessions must
2042
+ // not lose its place to one that did not. A message that turns out
2043
+ // not to be this agent's leaves an empty link behind, which is all it
2044
+ // should cost.
2045
+ if (!admitted.settled) {
2046
+ // One verdict for this message, shared with whichever other agents
2047
+ // are asking about it — see `followUpWinner`.
2048
+ const winner = await followUpWinner({ team, conversation: event.channel, thread: event.thread_ts ?? '' }, event.ts);
2049
+ if (winner !== connection.config.agentId) {
2050
+ return undefined;
2051
+ }
2052
+ // Answered from the store rather than from memory: hold it, so the
2053
+ // rest of the thread is ordered by receipt like any other.
2054
+ if (threadKey) {
2055
+ rememberAddressee(threadKey, connection.config.agentId, event.ts);
2056
+ }
2057
+ }
1392
2058
  const cleaned = await humanizeMentions(connection, event.text ?? '');
1393
2059
  if (cleaned.length === 0) {
1394
2060
  return undefined;
@@ -1396,7 +2062,8 @@ export const createSlackChannelAdapter = (options) => {
1396
2062
  const author = await displayNameFor(connection, userId);
1397
2063
  // In shared channels the model should know who is speaking; a DM is
1398
2064
  // unambiguous.
1399
- const userMessage = isDm ? cleaned : `${author}: ${cleaned}`;
2065
+ const spoken = isDm ? cleaned : `${author}: ${cleaned}`;
2066
+ const userMessage = `${spoken}${attachmentNote(event.files)}`;
1400
2067
  const renderer = new ReplyRenderer(connection.web, event.channel, thread, editIntervalMs, warn);
1401
2068
  try {
1402
2069
  await renderer.open();
@@ -1569,6 +2236,14 @@ export const createSlackChannelAdapter = (options) => {
1569
2236
  }
1570
2237
  });
1571
2238
  const known = new Set(gateway.agents().map((agent) => agent.id));
2239
+ // Two passes, because who a message names has to be answerable from
2240
+ // the first event onwards. Identities are learned for every app
2241
+ // FIRST; only then does any socket start delivering. One pass would
2242
+ // leave the agents at the front of the roster taking messages while
2243
+ // the ones behind them were still authenticating, and a mention of an
2244
+ // agent not yet known reads as an untagged reply — which the agent
2245
+ // holding that thread would then answer.
2246
+ const authenticated = [];
1572
2247
  for (const config of options.agents) {
1573
2248
  if (!known.has(config.agentId)) {
1574
2249
  warn(`slack: no roster agent with id ${config.agentId}; skipping its Slack app`);
@@ -1577,14 +2252,27 @@ export const createSlackChannelAdapter = (options) => {
1577
2252
  try {
1578
2253
  const web = createWeb(config.botToken);
1579
2254
  const auth = await web.auth.test();
1580
- const socket = createSocket(config.appToken);
1581
- const connection = {
2255
+ const botUserId = auth.user_id ?? '';
2256
+ const teamId = auth.team_id ?? '';
2257
+ // Recorded before the socket is even built: an app that never
2258
+ // comes up must still be recognizable when somebody names it.
2259
+ botIdentities.set(config.agentId, { botUserId, teamId });
2260
+ authenticated.push({
1582
2261
  config,
1583
2262
  web,
1584
- socket,
1585
- botUserId: auth.user_id ?? '',
1586
- teamId: auth.team_id ?? '',
1587
- };
2263
+ socket: createSocket(config.appToken),
2264
+ botUserId,
2265
+ teamId,
2266
+ });
2267
+ }
2268
+ catch (error) {
2269
+ // One broken app must not take the rest of the fleet down.
2270
+ warn(`slack: could not connect ${config.agentId}: ${error instanceof Error ? error.message : String(error)}`);
2271
+ }
2272
+ }
2273
+ for (const connection of authenticated) {
2274
+ const { config, socket } = connection;
2275
+ try {
1588
2276
  const onEvent = (args) => {
1589
2277
  const handled = handleInbound(connection, args).catch((error) => {
1590
2278
  warn(`slack event handling failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -1604,7 +2292,8 @@ export const createSlackChannelAdapter = (options) => {
1604
2292
  log(`slack: ${config.agentId} connected (bot ${connection.botUserId} in team ${connection.teamId})`);
1605
2293
  }
1606
2294
  catch (error) {
1607
- // One broken app must not take the rest of the fleet down.
2295
+ // Authenticated but not serving: it answers nothing, and stays
2296
+ // recognizable so nobody answers in its place.
1608
2297
  warn(`slack: could not connect ${config.agentId}: ${error instanceof Error ? error.message : String(error)}`);
1609
2298
  }
1610
2299
  }
@@ -1636,6 +2325,9 @@ export const createSlackChannelAdapter = (options) => {
1636
2325
  gatewayRef = undefined;
1637
2326
  connections.length = 0;
1638
2327
  approvalPosts.clear();
2328
+ threadAddressee.clear();
2329
+ coldVerdicts.clear();
2330
+ botIdentities.clear();
1639
2331
  rendering.clear();
1640
2332
  resolvedWhileRendering.clear();
1641
2333
  },