@kana-ai/edgar-ext-slack 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -6,15 +6,17 @@ The full guide, with the app setup, each setting, each tool and its examples, is
6
6
 
7
7
  ## Parts
8
8
 
9
- | Part | What it does |
10
- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
- | The service | Keeps one Socket Mode connection to Slack while `edgar start` runs. A DM or a mention that names a card (`EDG-2422`, or its tracker link) goes on that card and binds its thread to it; any other is a chat (`ctx.runs.chat`), which the built-in `chat` workflow answers in the thread, or opens a card for when it asks for work. A reply answers the newest question that waits; with no question, a reply in the thread of a card, or of the card that the thread is bound to, goes on the card as that person's comment with the thread as its place (`ctx.cards.reply`), with the thread's messages since EDGAR's last one and each Slack thread that it links from the same channel or a public one (a private one is left out, and the person is told). EDGAR says so, and says once when it is still on an earlier reply. The stop button cancels the card's runs. Approve, Deny and answer buttons move the run. |
12
- | The hook `progress` | Takes the run events of every run. A run that a person's words in Slack started (`relayed` on its `run_created`) posts a stage's answer `text`, or the card that a chat opened, in that thread once, ends its status, and says a failed answer in one plain line. Each card has one thread. A card that came from Slack uses the thread of its message. Any other card gets a thread in `channel`, or in the DM of the first `dm` entry when `channel` is not set: its first message links the card, and each run of the card, a rerun too, replies in it. Each run keeps one progress message in the thread from the moment its first stage starts, and its approvals go there; a stage that ends `done` with a `question` in its output, such as a proposal that went on with the option it recommends, posts the question once there, greets the assignee, and says that a reply with the number of another option changes the work, with the metadata `edgar_question` and the run and the stage; a run that ends with no stage, such as a run that a card's event started and that had nothing to do, posts none. A card from Slack also gets the session status (`processing` at the run's start and at each stage's start, `suspended` for an approval, `active` or `closed` at the end). When a run ends, the end note goes in the card's thread, and in the card's thread in the DM of each `dm` entry. A run with no card, such as a scheduled watch, gets no thread and no progress message, and gets an end note only when it does not end `done`. |
13
- | The tool `post_summary` | Posts a run's summary as a person writes it: one sentence with the card and what was done, plain paragraphs, then what to check. Side effect, undone by `delete_message`, found by `find_message`. |
14
- | The tool `dm` | Sends a DM to a person, by Slack user id or by email. Side effect, undone by `delete_message`, found by `find_message`. |
15
- | The tool `ask` | Posts a question with answer buttons, or asks for a reply, and returns `waiting` until a person answers. Side effect with no undo: a person may already have read the question. |
16
- | The tool `delete_message` | Deletes a message that EDGAR posted. A message that is already gone is `done` with `deleted: false`. |
17
- | The tool `find_message` | Finds the message of a `post_summary` or `dm` call by the operation id in its metadata. `skipped` when there is none. |
9
+ | Part | What it does |
10
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
+ | The service | Keeps one Socket Mode connection to Slack while `edgar start` runs. A DM or a mention that names a card (`ENG-42`, or its tracker link) goes on that card and binds its thread to it; any other is a chat (`ctx.runs.chat`), which the built-in `chat` workflow answers in the thread, or opens a card for when it asks for work. A reply answers the newest question that waits; with no question, a reply in the thread of a card, or of the card that the thread is bound to, goes on the card as that person's comment with the thread as its place (`ctx.cards.reply`), with the thread's messages since EDGAR's last one and each Slack thread that it links from the same channel or a public one (a private one is left out, and the person is told). EDGAR says so, and says once when it is still on an earlier reply. The stop button cancels the card's runs. Approve, Deny and answer buttons move the run. |
12
+ | The hook `progress` | Takes the run events of every run. A run that a person's words in Slack started (`relayed` on its `run_created`) posts a stage's answer `text`, or the card that a chat opened, in that thread once, ends its status, and says a failed answer in one plain line. Each card has one thread. A card that came from Slack uses the thread of its message. Any other card gets a thread in `channel`, or in the DM of the first `dm` entry when `channel` is not set: its first message links the card, and each run of the card, a rerun too, replies in it. Each run keeps one progress message in the thread from the moment it waits in a queue or its first stage starts, and its approvals go there; a stage that ends `done` with a `question` in its output, such as a proposal that went on with the option it recommends, posts the question once there, greets the assignee, and says that a reply with the number of another option changes the work, with the metadata `edgar_question` and the run and the stage; a run that ends with no stage, such as a run that a card's event started and that had nothing to do, posts none. A card from Slack also gets the session status (`processing` at the run's start and at each stage's start, `suspended` for an approval, `active` or `closed` at the end). When a run ends, the end note goes in the card's thread, and in the card's thread in the DM of each `dm` entry. A run with no card, such as a scheduled watch, gets no thread and no progress message, and gets an end note only when it does not end `done`. |
13
+ | The tool `post_summary` | Posts a run's summary as a person writes it: one sentence with the card and what was done, plain paragraphs, then what to check. Side effect, undone by `delete_message`, found by `find_message`. |
14
+ | The tool `dm` | Sends a DM to a person, by Slack user id or by email. Side effect, undone by `delete_message`, found by `find_message`. |
15
+ | The tool `ask` | Posts a question with answer buttons, or asks for a reply, and returns `waiting` until a person answers. Side effect with no undo: a person may already have read the question. |
16
+ | The tool `delete_message` | Deletes a message that EDGAR posted. A message that is already gone is `done` with `deleted: false`. |
17
+ | The tool `find_message` | Finds the message of a `post_summary` or `dm` call by the operation id in its metadata. `skipped` when there is none. |
18
+ | The link reader | Reads a Slack thread that a card or its comments link (`read_link`, for `*.slack.com`) into the run's inbox, as `/tmp/inbox/links.md`: its newest 50 messages, oldest first, quoted as the service quotes a linked thread. Only a thread in `channel` or in a public channel is read, because everyone who reads the run may see it; a thread in a private channel, a DM or a group DM is a `forbidden` failure, which the inbox shows in one line. A Slack link that is not a message's permalink, such as a file, is not read. |
19
+ | Chat files | A file that a person shares in a chat, such as a screenshot or a log, goes with the chat (`chatFiles`, for `files.slack.com`). The engine fetches it into the run's inbox, as it fetches a card's attachments: with the same byte caps, with secrets masked in a text file, and with `SLACK_BOT_TOKEN` as its bearer token, sent only to `files.slack.com`. A chat reads text and log files, JSON, XML, YAML, PDFs, and PNG, JPEG, GIF or WebP pictures; for any other file, or one Slack gives no download link for, the person gets one short reply that names it. Reading a file needs the `files:read` scope of `slack-app.json`. |
18
20
 
19
21
  The text of `post_summary` (`did`, `paragraphs`, `check`), of `dm`, of an `ask` question and of an answer shown back comes from a model, which often copies it from a card or a log. The extension makes `&`, `<` and `>` plain in that text, so it cannot notify a channel (`<!channel>`, `<@U…>`) or show a link whose label hides its address. A plain address still becomes a link in Slack. Known limit: a tool cannot post a link with a label of its own; the card link of `post_summary` is built by the extension. A question that passes the 3,000 characters of a Slack section once its markup is plain is cut on a whole character and ends with `…`. In the other direction, the text of a message from Slack is read back as the person wrote it before it reaches a card or an answer: no mention, a link as its address, and `&amp;`, `&lt;`, `&gt;` as their characters.
20
22
 
@@ -27,14 +29,13 @@ open_card_on = ["dm", "mention"] # the default: a DM and a mention both open a c
27
29
  card_column = "intake" # the default: the engine state of a new card
28
30
  context_messages = 20 # the default: the thread's newest messages copied onto the card, 0 to 100
29
31
  allow = { domains = ["example.com"], guests = false } # optional: who may open a card
30
- operators = { U0123ABCD = "ada" } # the default is empty: the Slack users who may answer, approve, deny and stop
31
32
  channel = "C0123ABCD" # optional: where post_summary posts when the call names no channel, where a run whose card did not come from Slack opens its thread, and where the note of a run that opened a pull request is shown
32
33
  dm = [
33
34
  "U0123ABCD",
34
35
  "ada@example.com",
35
36
  ] # the default is empty: who gets the end note of each run in a DM, by Slack user id or email
36
37
  close_on_done = false # the default: true sets the session closed after a run that is done
37
- console_url = "https://edgar.example.com" # no default: when set, the end note links the run's page, <console_url>/runs/<id>
38
+ console_url = "https://edgar.example.com" # no default: when set, the progress message, an approval question and the end note link the console, such as the run's page, <console_url>/runs/<id>
38
39
 
39
40
  [extensions.slack.people] # the default is empty: who the end note and an approval question mention, and who gets a decision note in a DM, by the assignee's name as the tracker gives it
40
41
  "Pat Doe" = "U0123ABCD"
@@ -44,7 +45,7 @@ console_url = "https://edgar.example.com" # no default: when set, the end note l
44
45
  fix = "is reading the code"
45
46
  ```
46
47
 
47
- A `dm` email is found with `users.lookupByEmail`, which needs the `users:read.email` scope of `slack-app.json`, once per process. An email that no person of the workspace has makes the end of each run a permanent `invalid` that names the email, and the engine raises an alert. A `dm` entry that is neither a user id nor an email fails the config schema, which `edgar check` prints. `edgar check` runs no extension code, so it cannot find an unknown email or a channel that does not exist; Slack answers those at the first run, as `invalid` and `not_found`.
48
+ A `dm` email is found with `users.lookupByEmail`, which needs the `users:read.email` scope of `slack-app.json`, once per process. An email that no person of the workspace has makes the end of each run a permanent `invalid` that names the email, and the engine raises an alert. A `dm` entry that is neither a user id nor an email fails the config schema, which `edgar check` prints. `edgar check` runs no extension code, so it cannot find an unknown email or a channel that does not exist. An unknown email is found at the first run, as `invalid`. The channel is checked when the service starts, as [Start check](#start-check) says.
48
49
 
49
50
  ## The thread of a card and the end note
50
51
 
@@ -52,8 +53,8 @@ The first message about a card opens its thread. The message is the card's title
52
53
 
53
54
  The end note is one message with blocks and the same words as plain text, which a notification and a screen reader show:
54
55
 
55
- 1. The headline: one emoji, the status in words, and the card. When the run names the card's id, the id is the link, and the service and the title follow: "EDG-1 · api: Search fails". With no id, the title is the link. A run with no card names its workflow, or the run.
56
- 2. One or two sentences. They greet the assignee ("Hey <assignee>,") when the card is assigned: a Slack mention, `<@U0123ABCD>`, when the extension finds their Slack user, else the name as the tracker gives it. The extension uses the first of these: the `people` entry whose key is the assignee's name, the `operators` entry whose name is the assignee's name, and the assignee itself when it is an email address. An email is found with `users.lookupByEmail`, once per process. When an email finds no user, the lookup fails, or the answer is not a Slack user id, the greeting has the plain name, the note is still posted, and the log has one line that names the assignee, the email and the reason. Then what happened:
56
+ 1. The headline: one emoji, the status in words, and the card. When the run names the card's id, the id is the link, and the service and the title follow: "ENG-1 · api: Search fails". With no id, the title is the link. A run with no card names its workflow, or the run.
57
+ 2. One or two sentences. They greet the assignee ("Hey <assignee>,") when the card is assigned: a Slack mention, `<@U0123ABCD>`, when the extension finds their Slack user, and no greeting otherwise, so a tracker name with no Slack user is never written. The extension uses the first of these: the `people` entry whose key is the assignee's name, the `operators` entry whose name is the assignee's name, and the assignee itself when it is an email address. An email is found with `users.lookupByEmail`, once per process. When an email finds no user, the lookup fails, or the answer is not a Slack user id, the note has no greeting, it is still posted, and the log has one line that names the assignee, the email and the reason. Then what happened:
57
58
  - "I've opened a pull request for <card>." or "I've opened <n> pull requests for <card>.", then the proposal's summary and, for a risk above low, the merge risk and its reason. A run of the built-in `remediate` says this at the moment its review wait (`wait_review`) starts, with no summary: see "The note that a pull request is ready".
58
59
  - "The pull request for <card> is merged.", then "<logins> approved it." and "The merge commit is `<7 characters>`." when the run read them. The note has no "Your move" and no word of the proposal, which was written before the pull request.
59
60
  - "The pull request for <card> is approved, and it isn't merged yet.", "A reviewer asked for changes on the pull request for <card>." or "The pull request for <card> was closed with no merge.", when the run ended with that decision of its reviewers.
@@ -83,7 +84,7 @@ An event whose `outcome` `endNote` cannot read still ends the progress message a
83
84
 
84
85
  ## The progress message
85
86
 
86
- Each run with a card keeps one message in the card's thread, with the metadata `edgar_plan`, and the hook changes it in place. The hook posts it at the run's first `attempt_started` event, not at `run_created`, so a run that ends before any stage starts leaves no line in the thread, and, when it ends `done`, no note either. The `run_created` event only lists the run on the card's first message and, for a card from Slack, sets the session status `processing` with the card's title. Its first line is the status and the card, in a `context` block, so that Slack shows its text and its emoji small; the plain text of the message keeps the same line. Then it has one line for each stage that started, in the order of the starts: the emoji of its state and its label. A stage is added at its `attempt_started` event, so a stage that the run skips or never reaches is never shown, and an outcome `skipped` removes its line. A stage of the built-in workflows has a label in `words.ts`; another stage reads as its name in words. A stage that waits reads "Waiting for CI", "Waiting for a review" or "Waiting for you"; another wait reads "Waiting:" and the label. More than three done steps fold into one line, "<n> steps done". A done stage whose output has the `state` and the `review_state` of a pull request says what people decided in place of its label, on a line of its own beside the folded steps: "The pull request is approved", "The pull request is approved and merged", "The pull request is merged", "A reviewer asked for changes" or "The pull request was closed with no merge". The last line links the run's page, when `console_url` is set, and each pull request that a stage answered with `url` and `number`. In Slack the steps are a `plan` block, and the stage that runs also sets the moving status line of the thread with `assistant.threads.setStatus`: the stage's phrase from `status`, else "is on it:" and its label. Slack removes that line at the app's next message in the thread, or after 2 minutes.
87
+ Each run with a card keeps one message in the card's thread, with the metadata `edgar_plan`, and the hook changes it in place. The hook posts it at the run's first `attempt_started` event, not at `run_created`, so a run that ends before any stage starts leaves no line in the thread, and, when it ends `done`, no note either. A run that waits in a queue posts it earlier, at its `waiting_for_slot` event: the first line reads "Queued" with the still hourglass, and the next line says what the run waits on, such as "1 run for ENG-12 is going, which is my limit. I'll start when one ends." for a workflow's `concurrency`, "3 triage runs are going, which is my limit." when the run's input has no value at the key, so it counts with every other such run of its workflow, or "I'm already running 4 steps at once, which is my limit." for the project's `[concurrency]`. The first stage that starts turns the same message into the plan. The `run_created` event only lists the run on the card's first message and, for a card from Slack, sets the session status `processing` with the card's title. Its first line is the status and the card, in a `context` block, so that Slack shows its text and its emoji small; the plain text of the message keeps the same line. Then it has one line for each stage that started, in the order of the starts: the emoji of its state and its label. A stage is added at its `attempt_started` event, so a stage that the run skips or never reaches is never shown, and an outcome `skipped` removes its line. A stage of the built-in workflows has a label in `words.ts`; another stage reads as its name in words. A stage that waits reads "Waiting for CI", "Waiting for a review" or "Waiting for you"; another wait reads "Waiting:" and the label. More than three done steps fold into one line, "<n> steps done". A done stage whose output has the `state` and the `review_state` of a pull request says what people decided in place of its label, on a line of its own beside the folded steps: "The pull request is approved", "The pull request is approved and merged", "The pull request is merged", "A reviewer asked for changes" or "The pull request was closed with no merge". The last line links the run's page, when `console_url` is set, and each pull request that a stage answered with `url` and `number`. In Slack the steps are a `plan` block, and the stage that runs also sets the moving status line of the thread with `assistant.threads.setStatus`: the stage's phrase from `status`, else "is on it:" and its label. Slack removes that line at the app's next message in the thread, or after 2 minutes.
87
88
 
88
89
  The hook's process ends after some minutes with no work, so the hook keeps nothing that it cannot read again: the progress message holds its own state in its metadata, and the card and the trigger of a run that the process did not see start are read from the run's first event with `runs.read`, which the hook holds the capability `runs:read` for. A run that does not read is one line in the log, and its messages name no card.
89
90
 
@@ -97,15 +98,35 @@ An approval question greets the assignee as the end note does. The hook reads th
97
98
 
98
99
  An approval question shows the input of the call as JSON in a code block, and the approval runs that input and no other. The block holds at most 2,400 characters. When the input is longer, the question says that the block is only its start and names the console page **Needs a person**, as a link when `console_url` is set. For the full text of the question, see [the Slack page](/docs/reference/slack.md#approve-and-deny).
99
100
 
100
- Each value in `operators` must also be a name in `[roles] operator`, because the engine checks the person on each move. A person who is not an operator and answers, presses a button or stops work is told so, only to them. While `operators` is empty, that message gives their Slack user id and the line to add, so a new project's first press shows how to set it up.
101
+ When a done stage's output names a channel in `post_in`, as `classify` does when a person asks for the result in a channel ("post it in #team-backend when it's done"), the hook says once in the card's thread "I'll post the result in #team-backend when the work is done.", with the metadata `edgar_post_to`. At the end of a later run of the card that is done, it posts that run's end note in the channel, as a message of the channel and not in a thread, and changes the promise to "I posted the result in #team-backend." (`edgar_post_done`), so the result goes there once. A channel link (`<#C123|name>`) is posted to by its id, and a name by its name. When the app is not in the channel or Slack can't find it, the promise says so and how to invite the app; the run that heard the ask, and a run that did not end done, post nothing there.
102
+
103
+ When a run ends, the hook closes each question of that run in the card's thread that no answer can reach any more, so nobody spends time on it: each `ask` question and approval question of the run, because the engine no longer waits on their keys, and, when the card was closed or a person stopped the work, the question a done stage left open. It adds to each one "This isn't needed any more" and why, removes its buttons, and marks it `edgar_closed`, so a reply in the thread goes past it. An `ask` question that the agent posted in another thread stays up until a reply there finds it closed.
104
+
105
+ EDGAR decides who may answer, approve, deny and stop, from the project's `[people]` and `[roles] operator`; the extension keeps no list of its own. Before each of these, it asks the engine with `ctx.moves.allowed` for the person's Slack user id, and sends the move with that id, which EDGAR signs as `<name>@slack` when `[people.<name>] ids = { slack = "<id>" }` holds it. With no `[roles] operator`, only a person of `[people]` with a Slack id may. A person who may not is told so, only to them, with their Slack user id and the lines to add.
106
+
107
+ The card a message opens and each reply the extension puts on a card carry the trust of the person who wrote the message, as `users.info` says: a member of the workspace the app is installed in, or of its organization on Enterprise Grid, is on the team. A guest, a bot, and a person of another workspace in a shared channel are outside, and so is a person Slack does not answer for. EDGAR starts triage and answers for words from outside the team, and no work that changes code. `allow` still decides who may open a card or put a reply on one, on top of that.
108
+
109
+ The `operators` table (`{ U0123ABCD = "ada" }`, a Slack user to a name in `[roles] operator`) is deprecated and is removed in a later release. While it has an entry, it still decides as before, even with no `[roles] operator`, and `edgar check` warns with `C050` and names what to write instead.
110
+
111
+ ## Start check
112
+
113
+ Each time the service starts, before it opens the Socket Mode connection, it checks the set-up with the bot token. It posts nothing.
114
+
115
+ - `auth.test` proves that `SLACK_BOT_TOKEN` works. When Slack refuses the token (`invalid_auth`, `not_authed`, `account_inactive`, `token_revoked`, `token_expired`), the service ends with a permanent `unauthenticated` that says how to fix the token. The engine writes an alert and opens the service's breaker, as it does for a refused app token, and keeps running.
116
+ - `conversations.info` reads `channel`, when it is set. A channel that Slack does not find, that the bot is not a member of, or that is archived writes one warning to the log that names the channel and the fix, such as `Invite the bot with /invite @edgar in #ops.` The service then starts.
117
+ - When Slack does not answer, answers 5xx, or limits the rate, the check writes a warning and the service starts. Slack being down never blocks the engine.
118
+
119
+ `dm` entries are not checked: a DM needs no membership. A `channel` that a `post_summary` call names is checked by Slack when the call posts.
101
120
 
102
121
  ## Secrets
103
122
 
104
- - `SLACK_BOT_TOKEN`: the bot token (`xoxb-`) of the installed app. Every Web API call sends it. It reaches `slack.com` and `*.slack.com`, such as `files.slack.com`.
123
+ - `SLACK_BOT_TOKEN`: the bot token (`xoxb-`) of the installed app. Every Web API call sends it. It reaches `slack.com` and `*.slack.com`, such as `files.slack.com`. The engine also sends it to `files.slack.com`, and nowhere else, when it fetches a file that a person shared in a chat.
105
124
  - `SLACK_APP_TOKEN`: an app-level token (`xapp-`) with `connections:write`. Only the service sends it, to open the Socket Mode connection. It reaches `slack.com` and `*.slack.com`.
106
125
 
107
126
  Both secrets list `*.slack.com`, because the engine gives a service only the `network:` hosts its secrets list, and the Socket Mode address is `wss-primary.slack.com`. A project that approved an earlier manifest runs `edgar extensions approve slack` again. A connection that closes within 5 seconds of opening is written to the log with its close code, and the next one waits 1 s, then 2 s, up to a minute.
108
127
 
128
+ Each Socket Mode event is stored in EDGAR's inbox before the service tells Slack it arrived, keyed by Slack's `event_id` (or the envelope id for a button press), without the legacy verification token. So a stop after the event is stored loses nothing: at its next start, before it opens a connection, the service handles what the inbox still holds. A redelivery of the same event is acknowledged and not handled again. Each message the service writes in answer to an event carries the event's id in its metadata, so an event handled again at start, because a stop came between its answer and its `handled` mark, finds that answer in its thread and is not answered twice: no second reply on the card, note, or rewritten question. Only a short status or a message that only the person sees can come again. An event the inbox cannot take is not acknowledged, and Slack sends it again. `edgar inbox list --extension slack` shows them under the route `service`, and `edgar inbox replay <id>` hands one back at the service's next start.
129
+
109
130
  Create the app from `slack-app.json` in this folder. The [Slack page](/docs/reference/slack.md#create-the-slack-app) gives each step.
110
131
 
111
132
  ## Errors
@@ -0,0 +1,5 @@
1
+ import { type Failure, type Result } from "@kana-ai/edgar-sdk";
2
+ import { type SlackCtx } from "#api/client";
3
+ import type { Config } from "#schemas/config";
4
+ /** The start check of the service: `auth.test` proves the bot token, then `conversations.info` shows whether the bot can post to `channel`. A refused token is a permanent `unauthenticated`; anything else, Slack down or rate limited too, is a warning line, so the engine never waits on Slack. */
5
+ export declare function checkSetup(ctx: SlackCtx, settings: Config): Promise<Result<readonly string[], Failure>>;
@@ -0,0 +1,40 @@
1
+ import { err, ok, permanentFailure } from "@kana-ai/edgar-sdk";
2
+ import { BOT, slack } from "#api/client";
3
+ import { channelInfo, identity } from "#schemas/slack";
4
+ const KEY = "the `[extensions.slack] channel`";
5
+ /** Reads the configured `channel` with `conversations.info`, never posting, and says what stops the bot from posting there. */
6
+ async function channelWarning(ctx, id, bot) {
7
+ const info = await slack(ctx, "conversations.info", { channel: id }, channelInfo);
8
+ if (!info.ok) {
9
+ const { kind, message, cause = message } = info.error;
10
+ if (kind === "not_found")
11
+ return `Slack: ${KEY} ${id} is not found (${cause}). Check the id, or, for a private channel, invite the bot with /invite @${bot} in it.`;
12
+ if (kind === "forbidden")
13
+ return `Slack: the bot may not read ${KEY} ${id} (${cause}). Invite the bot with /invite @${bot} in it, or add the scope the cause names to the app and install it again.`;
14
+ return `Slack: could not check ${id}: ${message} (${cause}). EDGAR starts, and Slack answers at the first post.`;
15
+ }
16
+ const { name, is_member, is_archived } = info.value.channel;
17
+ const label = name === undefined ? id : `#${name} (${id})`;
18
+ const where = name === undefined ? "it" : `#${name}`;
19
+ if (is_archived === true)
20
+ return `Slack: ${label}, ${KEY}, is archived, so EDGAR cannot post there. Set \`channel\` to another channel.`;
21
+ if (is_member === false)
22
+ return `Slack: the bot is not in ${label}, ${KEY}, so EDGAR cannot post there. Invite the bot with /invite @${bot} in ${where}.`;
23
+ return undefined;
24
+ }
25
+ /** The start check of the service: `auth.test` proves the bot token, then `conversations.info` shows whether the bot can post to `channel`. A refused token is a permanent `unauthenticated`; anything else, Slack down or rate limited too, is a warning line, so the engine never waits on Slack. */
26
+ export async function checkSetup(ctx, settings) {
27
+ const auth = await slack(ctx, "auth.test", {}, identity);
28
+ if (!auth.ok) {
29
+ const { kind, message, cause = message } = auth.error;
30
+ if (kind === "unauthenticated")
31
+ return err(permanentFailure("unauthenticated", `Slack refused ${BOT} at start (${cause}). Copy the bot token (xoxb-) from the app's OAuth & Permissions page, export it as ${BOT}, and run edgar start again.`, { cause }));
32
+ return ok([
33
+ `Slack: could not check the bot token: ${message} (${cause}). EDGAR starts anyway.`,
34
+ ]);
35
+ }
36
+ if (settings.channel === undefined)
37
+ return ok([]);
38
+ const warning = await channelWarning(ctx, settings.channel, auth.value.user);
39
+ return ok(warning === undefined ? [] : [warning]);
40
+ }
@@ -0,0 +1,8 @@
1
+ import type { Attachment } from "@kana-ai/edgar-contracts/rpc";
2
+ /** What a chat does with the files of a message: those the engine fetches into the run's inbox, and the names of those it does not take. */
3
+ export interface Shared {
4
+ readonly files: readonly Attachment[];
5
+ readonly refused: readonly string[];
6
+ }
7
+ /** Splits `files`, as a Slack message lists them, into those a chat takes and those it does not: a file of another kind, or one Slack gives no download link for, such as a file hidden by the workspace's plan. */
8
+ export declare function sharedFiles(files: readonly unknown[]): Shared;
@@ -0,0 +1,24 @@
1
+ import { sharedFile } from "#schemas/slack";
2
+ /** The kinds of file a chat reads: text and logs, data, PDFs and pictures. The engine still caps each file and masks secrets in a text one, since a person chose the kind. */
3
+ const TAKEN = [
4
+ /^text\/[a-z0-9.+-]+$/,
5
+ /^application\/(?:json|xml|yaml|x-yaml|pdf)$/,
6
+ /^image\/(?:png|jpeg|gif|webp)$/,
7
+ ];
8
+ /** Splits `files`, as a Slack message lists them, into those a chat takes and those it does not: a file of another kind, or one Slack gives no download link for, such as a file hidden by the workspace's plan. */
9
+ export function sharedFiles(files) {
10
+ const taken = [];
11
+ const refused = [];
12
+ for (const listed of files) {
13
+ const file = sharedFile.safeParse(listed);
14
+ if (!file.success)
15
+ continue;
16
+ const { id, name = id, mimetype = "", size, url_private_download: url } = file.data;
17
+ if (url === undefined || !TAKEN.some((kind) => kind.test(mimetype))) {
18
+ refused.push(name);
19
+ continue;
20
+ }
21
+ taken.push({ id, name, url, ...(size === undefined ? {} : { bytes: size }) });
22
+ }
23
+ return { files: taken, refused };
24
+ }
@@ -0,0 +1,2 @@
1
+ /** Reads a Slack thread that a card or its comments link, for a run's inbox: its newest messages, oldest first, quoted as a card quotes a linked thread. As for a thread that a person links in Slack, only a thread in `[extensions.slack] channel` or in a public channel is read, since everyone who reads the card's run may see it. A Slack link that is not a message's permalink, such as a file, is not this reader's. */
2
+ export declare const readLink: import("@kana-ai/edgar-sdk").ReadLink;
@@ -0,0 +1,28 @@
1
+ import { defineReadLink, err, ok, permanentFailure } from "@kana-ai/edgar-sdk";
2
+ import { BOT, HOST } from "#api/client";
3
+ import { linked, quote, shareable, threadAt } from "#inbound/route";
4
+ import { settingsOf } from "#schemas/config";
5
+ /** Reads a Slack thread that a card or its comments link, for a run's inbox: its newest messages, oldest first, quoted as a card quotes a linked thread. As for a thread that a person links in Slack, only a thread in `[extensions.slack] channel` or in a public channel is read, since everyone who reads the card's run may see it. A Slack link that is not a message's permalink, such as a file, is not this reader's. */
6
+ export const readLink = defineReadLink({
7
+ hosts: [`*.${HOST}`],
8
+ secrets: [BOT],
9
+ capabilities: [`network:${HOST}`],
10
+ read: async (ctx, url) => {
11
+ const link = linked(url)[0];
12
+ if (link === undefined)
13
+ return ok({ kind: "not_mine" });
14
+ const settings = settingsOf(ctx.config);
15
+ const own = settings.ok ? settings.value.channel : undefined;
16
+ if (!(await shareable(ctx, link.channel, own))) {
17
+ return err(permanentFailure("forbidden", "the thread is not in a public channel or in the channel of `[extensions.slack]`"));
18
+ }
19
+ const read = await threadAt(ctx, link.channel, link.ts);
20
+ if (!read.ok)
21
+ return read;
22
+ return ok({
23
+ kind: "read",
24
+ title: `Slack thread in channel ${link.channel}`,
25
+ text: read.value.map(quote).join("\n"),
26
+ });
27
+ },
28
+ });
@@ -1,9 +1,41 @@
1
- import { type Ctx } from "@kana-ai/edgar-sdk";
2
- import { type APP, type BOT } from "#api/client";
1
+ import type { Trust } from "@kana-ai/edgar-contracts/rpc";
2
+ import { type Ctx, type Failure, type Result } from "@kana-ai/edgar-sdk";
3
+ import type { z } from "zod";
4
+ import { type APP, type BOT, type SlackCtx } from "#api/client";
5
+ import { type Message } from "#outbound/messages";
3
6
  import type { Config } from "#schemas/config";
7
+ import { userInfo } from "#schemas/slack";
4
8
  /** The service's context: the bot token for the Web API and the app token for the socket. */
5
9
  export type ServiceCtx = Ctx<typeof BOT | typeof APP>;
10
+ /** The workspace EDGAR's app is in, as the envelope of an event names it. */
11
+ export interface Home {
12
+ readonly team: string | undefined;
13
+ readonly enterprise: string | undefined;
14
+ }
15
+ /** The inbox delivery of the event being routed: its id, which each message that routing it writes carries, and whether it is routed again, at a start after the routing may have run. */
16
+ export interface Delivery {
17
+ readonly id: string;
18
+ readonly again: boolean;
19
+ }
20
+ type SlackUser = z.infer<typeof userInfo>["user"];
6
21
  /** The text as the person wrote it: no `<@U…>` mention, a link as its address, and `&lt;`, `&gt;`, `&amp;` as their characters. Slack sends a message's text escaped, and each tool escapes what it posts, so this is the one place that reads the escape back. */
7
22
  export declare function clean(text: string): string;
8
- /** Routes one Socket Mode envelope's payload. Each failure is told to the person or logged, so one bad event never stops the service. */
9
- export declare function route(ctx: ServiceCtx, settings: Config, type: string, payload: unknown): Promise<void>;
23
+ /** Whether `person` is on the team: a member of the app's workspace, or of its organization on Enterprise Grid. A bot, a guest and a person of another workspace, such as in a channel shared with it, are outside. */
24
+ export declare function trustOf(person: SlackUser, home: Home): Trust;
25
+ /** One message of Slack as a line of a card: who wrote it, EDGAR for EDGAR's own, and its words on one line. */
26
+ export declare function quote(message: Message): string;
27
+ /** A Slack thread that a message links, by its permalink: its channel, the `ts` of its first message, and the link. */
28
+ interface Linked {
29
+ readonly channel: string;
30
+ readonly ts: string;
31
+ readonly url: string;
32
+ }
33
+ /** The Slack threads that `text` links, the first `LINKS` of them. A permalink's `p` part is its message's `ts` with no dot, and its `thread_ts` names the thread of a reply. */
34
+ export declare function linked(text: string): readonly Linked[];
35
+ /** The newest `THREAD_MESSAGES` messages of a thread, oldest first, read at most `THREAD_PAGES` pages of `conversations.replies` deep. */
36
+ export declare function threadAt(ctx: SlackCtx, channel: string, ts: string): Promise<Result<readonly Message[], Failure>>;
37
+ /** Whether a linked thread may go on a card, which everyone who reads the card sees: only one in `own` channel or in a public channel. A failed `conversations.info` counts as not public. */
38
+ export declare function shareable(ctx: SlackCtx, channel: string, own: string | undefined): Promise<boolean>;
39
+ /** Routes one Socket Mode envelope's payload, of the inbox `delivery` when it came through the inbox. Each failure is told to the person or logged, so one bad event never stops the service. An event routed again finds what its first routing wrote by the delivery id, and is then not routed again: a stop between routing it and marking it handled does not answer a person twice. */
40
+ export declare function route(ctx: ServiceCtx, settings: Config, type: string, payload: unknown, delivery?: Delivery): Promise<void>;
41
+ export {};