@kana-ai/edgar-ext-slack 0.1.3 → 0.1.5

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.
@@ -1,9 +1,9 @@
1
1
  import { attempt, done, ok, } from "@kana-ai/edgar-sdk";
2
2
  import { slack } from "#api/client";
3
3
  import { sharedFiles } from "#inbound/files";
4
- import { boundCard, listed, mark, newestMarked, post, runOf, status, threadStatus, waitingRelays, } from "#outbound/messages";
4
+ import { REACTION, boundCard, listed, mark, newestMarked, post, react, runOf, status, threadStatus, waitingRelays, } from "#outbound/messages";
5
5
  import { cutEscaped, escape } from "#outbound/tools";
6
- import { CONTEXT, REPLY } from "#outbound/words";
6
+ import { CONTEXT, REPLY, SAYS } from "#outbound/words";
7
7
  import { answer, answerValue, channelInfo, home, messages, permalink, pressed, said, stopped, userInfo, } from "#schemas/slack";
8
8
  /** The metadata fields that tie a message EDGAR writes to the delivery it answers. */
9
9
  function keyed(delivery) {
@@ -95,11 +95,12 @@ async function writer(ctx, settings, message) {
95
95
  const found = await slack(ctx, "users.info", { user: message.user }, userInfo);
96
96
  if (!found.ok) {
97
97
  ctx.log(`users.info ${message.user}: ${found.error.message}`);
98
- return { allowed: settings.allow === undefined, trust: "outside" };
98
+ return { allowed: settings.allow === undefined, trust: "outside", name: undefined };
99
99
  }
100
100
  const person = found.value.user;
101
101
  const allowed = settings.allow === undefined || allows(settings.allow, person);
102
- return { allowed, trust: trustOf(person, message.home) };
102
+ const name = [person.profile?.display_name, person.real_name, person.name].find((said) => said !== undefined && said.trim() !== "");
103
+ return { allowed, trust: trustOf(person, message.home), name };
103
104
  }
104
105
  /** One message of Slack as a line of a card: who wrote it, EDGAR for EDGAR's own, and its words on one line. */
105
106
  export function quote(message) {
@@ -113,8 +114,8 @@ export function quote(message) {
113
114
  function before(all, ts, count) {
114
115
  return count === 0 ? [] : all.filter((m) => m.ts !== ts && m.text !== undefined).slice(-count);
115
116
  }
116
- /** The card a message opens, with its permalink and, in a thread, the thread's newest messages before it. The block says when its writer is outside the team, since the tracker sees EDGAR's account as the card's writer. */
117
- async function cardOf(ctx, settings, message, thread, all, trust) {
117
+ /** The card a message opens, with its permalink and, in a thread, the thread's newest messages before it. The block says when its writer is outside the team, and who they are, since the tracker sees EDGAR's account as the card's writer. */
118
+ async function cardOf(ctx, settings, message, thread, all, who) {
118
119
  const text = clean(message.text);
119
120
  const title = (text.split("\n")[0] ?? "").slice(0, TITLE_LENGTH) || "A message from Slack";
120
121
  const link = await slack(ctx, "chat.getPermalink", { channel: message.channel, message_ts: message.ts }, permalink);
@@ -131,7 +132,12 @@ async function cardOf(ctx, settings, message, thread, all, trust) {
131
132
  channel: message.channel,
132
133
  thread: thread ?? message.ts,
133
134
  };
134
- const block = { kind: "request", origin, ...(trust === "outside" ? { trust } : {}) };
135
+ const block = {
136
+ kind: "request",
137
+ origin,
138
+ ...(who.trust === "outside" ? { trust: who.trust } : {}),
139
+ ...(who.name === undefined ? {} : { requested_by: who.name, requested_by_id: message.user }),
140
+ };
135
141
  return { title, description, column: settings.card_column, block };
136
142
  }
137
143
  /** Opens `card` for a message, says so in its thread, then shows the session as processing. */
@@ -155,12 +161,13 @@ async function open(ctx, message, card) {
155
161
  const noted = await post(ctx, message.channel, root, REPLY.opened(made.output.id), extra);
156
162
  if (!noted.ok)
157
163
  ctx.log(`chat.postMessage: ${noted.error.message}`);
164
+ await react(ctx, message.channel, message.ts, REACTION.done);
158
165
  if (origin !== undefined)
159
166
  await status(ctx, origin, "processing", card.title);
160
167
  }
161
168
  /** A message with no card: the workflow `chat` answers a question in its thread, with the thread's newest messages before it and the files the message shares, and opens the message's card when it asks for work. A file of a kind it does not read gets one short reply to the person. A chat that the engine does not start, such as in a project with no `chat` workflow, opens the card at once, as a message did before chats. */
162
- async function chat(ctx, settings, message, thread, all, trust) {
163
- const card = await cardOf(ctx, settings, message, thread, all, trust);
169
+ async function chat(ctx, settings, message, thread, all, who) {
170
+ const card = await cardOf(ctx, settings, message, thread, all, who);
164
171
  const text = clean(message.text);
165
172
  const origin = card.block.origin;
166
173
  if (text === "" || origin === undefined) {
@@ -176,6 +183,15 @@ async function chat(ctx, settings, message, thread, all, trust) {
176
183
  await tell(ctx, origin, message.user, REPLY.filesNotRead(shared.refused));
177
184
  const why = refusal(await ctx.runs.chat(words, message.user, origin, card, shared.files));
178
185
  if (why === undefined) {
186
+ await react(ctx, message.channel, message.ts, REACTION.seen);
187
+ const metadata = mark("edgar_relayed", {
188
+ ...keyed(message.delivery),
189
+ user: message.user,
190
+ asked: message.ts,
191
+ });
192
+ const noted = await post(ctx, origin.channel, origin.thread, REPLY.chatting(earlier.length > 0), { metadata });
193
+ if (!noted.ok)
194
+ ctx.log(`chat.postMessage: ${noted.error.message}`);
179
195
  await threadStatus(ctx, origin.channel, origin.thread, REPLY.readingMessage);
180
196
  return;
181
197
  }
@@ -209,6 +225,7 @@ async function reply(ctx, settings, message, question, key) {
209
225
  }
210
226
  const thanks = `${asked}\n\n${REPLY.answered(message.user)}`;
211
227
  await settle(ctx, message.channel, question.ts, "edgar_answered", key, thanks, message.delivery);
228
+ await react(ctx, message.channel, message.ts, REACTION.done);
212
229
  return { kind: "handled" };
213
230
  }
214
231
  /** The newest question of `ask` that waits among `all`. */
@@ -328,6 +345,7 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
328
345
  await threadStatus(ctx, message.channel, thread, "");
329
346
  return { kind: "refused", why };
330
347
  }
348
+ await react(ctx, message.channel, message.ts, REACTION.seen);
331
349
  const card = "card" in taken ? taken.card : undefined;
332
350
  const waiting = waitingRelays(all, Date.now());
333
351
  const busy = waiting.length > 0 && !waiting.some((m) => m.metadata?.event_payload["busy"] === true);
@@ -335,12 +353,15 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
335
353
  ? REPLY.bound(card)
336
354
  : busy
337
355
  ? REPLY.busy
338
- : file
339
- ? REPLY.relayedNoFile
340
- : REPLY.relayed;
356
+ : thanked(text)
357
+ ? REPLY.welcome
358
+ : file
359
+ ? REPLY.relayedNoFile
360
+ : REPLY.relayed;
341
361
  const metadata = mark("edgar_relayed", {
342
362
  ...keyed(message.delivery),
343
363
  user: message.user,
364
+ asked: message.ts,
344
365
  ...(card === undefined ? {} : { card }),
345
366
  ...(busy ? { busy } : {}),
346
367
  });
@@ -350,6 +371,13 @@ async function relay(ctx, settings, message, thread, targets, all, bind = false)
350
371
  await threadStatus(ctx, message.channel, thread, REPLY.reading);
351
372
  return { kind: "relayed" };
352
373
  }
374
+ /** Whether `text` is a short thank-you that asks nothing more and says nothing is wrong, which gets a short reply of its own. */
375
+ function thanked(text) {
376
+ return (text.length <= 60 &&
377
+ !text.includes("?") &&
378
+ !/\b(?:but|still|however|though|not|no|please)\b|n't/i.test(text) &&
379
+ /^(?:(?:ok|okay|great|perfect|awesome|nice)[\s,.!]+)?(?:thanks|thank you|thx|ty|cheers)\b/i.test(text));
380
+ }
353
381
  /** The keys of the cards that `text` names, such as `ENG-42` alone or in a tracker link, the first `KEYS` of them. A word of the same shape that is no card, such as `UTF-8`, is refused by the tracker and passed over. */
354
382
  function cardsNamed(text) {
355
383
  const keys = text.match(/\b[A-Z][A-Z0-9]{1,9}-[1-9][0-9]{0,6}\b/g) ?? [];
@@ -407,7 +435,7 @@ async function heard(ctx, settings, message) {
407
435
  if (target === undefined) {
408
436
  const who = await writer(ctx, settings, message);
409
437
  if (who.allowed)
410
- await chat(ctx, settings, message, thread, all.value, who.trust);
438
+ await chat(ctx, settings, message, thread, all.value, who);
411
439
  return;
412
440
  }
413
441
  const relayed = await relay(ctx, settings, message, thread, [target], all.value);
@@ -452,7 +480,7 @@ async function heard(ctx, settings, message) {
452
480
  }
453
481
  const who = await writer(ctx, settings, message);
454
482
  if (who.allowed)
455
- await chat(ctx, settings, message, thread, talk, who.trust);
483
+ await chat(ctx, settings, message, thread, talk, who);
456
484
  }
457
485
  /** The stop button cancels the runs of the thread's card, then the session goes back to active. */
458
486
  async function stop(ctx, settings, event) {
@@ -468,7 +496,57 @@ async function stop(ctx, settings, event) {
468
496
  await tell(ctx, where, event.user, REPLY.notStopped(why));
469
497
  await status(ctx, origin, "active");
470
498
  }
471
- /** A press on Approve, Deny or an answer button, by an operator. */
499
+ /** The blocks of a message with no `action` button: an `actions` block keeps its other buttons, and goes when it holds no other. */
500
+ export function withoutButton(blocks, action) {
501
+ return blocks.flatMap((each) => {
502
+ if (each.type !== "actions" || each.elements === undefined)
503
+ return [each];
504
+ const elements = each.elements.filter((element) => element.action_id !== action);
505
+ return elements.length === 0 ? [] : [{ ...each, elements }];
506
+ });
507
+ }
508
+ /** What each button that moves one run does: who may press it, the engine's move, and what the thread or the person who pressed is told. */
509
+ const RUN_BUTTONS = {
510
+ edgar_replay: {
511
+ operators: REPLY.operatorsReplay,
512
+ move: async (ctx, run, by) => await ctx.runs.replay(run, by),
513
+ refused: REPLY.notReplayed,
514
+ said: SAYS.triedAgain,
515
+ },
516
+ edgar_stop: {
517
+ operators: REPLY.operatorsStop,
518
+ move: async (ctx, run, by) => await ctx.runs.stop(run, by, "stopped in Slack"),
519
+ refused: REPLY.notStopped,
520
+ said: SAYS.stoppedBy,
521
+ },
522
+ };
523
+ function isRunButton(id) {
524
+ return Object.hasOwn(RUN_BUTTONS, id);
525
+ }
526
+ /** A press on Try again or Stop, by an operator: the engine moves the run for them; the message keeps its words with no such button, so nobody presses it twice; and the thread says who asked. A move the engine refuses, such as a stop of a run that is over, is told to the person who pressed. */
527
+ async function moveRun(ctx, payload, action, run, by, where, delivery) {
528
+ const button = RUN_BUTTONS[action];
529
+ const why = refusal(await button.move(ctx, run, by));
530
+ if (why !== undefined) {
531
+ await tell(ctx, where, payload.user.id, button.refused(why));
532
+ return;
533
+ }
534
+ const channel = payload.channel?.id;
535
+ const ts = payload.message?.ts;
536
+ if (channel === undefined || ts === undefined)
537
+ return;
538
+ const said = button.said(payload.user.id);
539
+ const blocks = withoutButton(payload.message?.blocks ?? [], action);
540
+ const text = payload.message?.text ?? said;
541
+ const updated = await slack(ctx, "chat.update", { channel, ts, text, blocks }, answer);
542
+ if (!updated.ok)
543
+ ctx.log(`chat.update: ${updated.error.message}`);
544
+ const metadata = mark("edgar_post", { ...keyed(delivery), run });
545
+ const noted = await post(ctx, channel, where.thread ?? ts, said, { metadata });
546
+ if (!noted.ok)
547
+ ctx.log(`chat.postMessage: ${noted.error.message}`);
548
+ }
549
+ /** A press on Approve, Deny, Try again, Stop or an answer button, by an operator. */
472
550
  async function press(ctx, settings, payload, delivery) {
473
551
  const channel = payload.channel?.id;
474
552
  const ts = payload.message?.ts;
@@ -481,12 +559,18 @@ async function press(ctx, settings, payload, delivery) {
481
559
  const [action] = payload.actions;
482
560
  if (action === undefined || action.value === undefined)
483
561
  return;
484
- const mover = await moverOf(ctx, settings, payload.user.id, REPLY.operatorsChoose);
562
+ const runButton = isRunButton(action.action_id) ? action.action_id : undefined;
563
+ const refused = runButton === undefined ? REPLY.operatorsChoose : RUN_BUTTONS[runButton].operators;
564
+ const mover = await moverOf(ctx, settings, payload.user.id, refused);
485
565
  if ("told" in mover) {
486
566
  await tell(ctx, where, payload.user.id, mover.told);
487
567
  return;
488
568
  }
489
569
  const { by } = mover;
570
+ if (runButton !== undefined) {
571
+ await moveRun(ctx, payload, runButton, action.value, by, where, delivery);
572
+ return;
573
+ }
490
574
  let moved;
491
575
  let said = "";
492
576
  let answered;
@@ -1,6 +1,6 @@
1
1
  import { type EndNote, type NoteCard, type NoteStyle } from "@kana-ai/edgar-sdk";
2
2
  import type { Config } from "#schemas/config";
3
- import type { Plan } from "#schemas/events";
3
+ import type { Plan, RootView } from "#schemas/events";
4
4
  /** How Slack writes a link and a text that came from a card, a model or a failure. */
5
5
  export declare const style: NoteStyle;
6
6
  type Block = Readonly<Record<string, unknown>>;
@@ -11,32 +11,56 @@ export interface Layout {
11
11
  }
12
12
  /** A stage as a person reads it: its entry of `STAGE`, else its id in words with a capital first letter. */
13
13
  export declare function stageLabel(stage: string): string;
14
- /** The progress of a run as one message that changes in place. The first line is the status and the card as a link. Then one short line per step that has started, in the order of its start, with the emoji of its state and its label of `stageLabel`; more than `FOLD` done steps are one line with their count, and a step that says what people decided on the pull request keeps its own line. A stage that was skipped or never started is not in the plan, and a plan that is over leaves out each step that never ended. The last line links the run's page, when the console has an address, and each pull request the run opened. The blocks are the first line in small text, so that its emoji is small too, Slack's plan block with one task card per line, and the links in small text. */
14
+ /** The moving line under the thread while `stage` works: its phrase of `[extensions.slack.status]`, else its entry of `MOVING`, else "is on it:" and its label. */
15
+ export declare function stageStatus(stage: string, settings: Config): string;
16
+ /** The progress of a run as one message that changes in place. The first line is the status and the card as a link; once the run is over, the status is the title of its end note's kind, so a card handed to a person never reads as done. Then one short line per step that has started, in the order of its start, with the emoji of its state and its label of `stageLabel`; more than `FOLD` done steps are one line with their count, and a step that says what people decided on the pull request keeps its own line. A stage that was skipped or never started is not in the plan, and a plan that is over leaves out each step that never ended. The last line links the run's page, when the console has an address, and each pull request the run opened. The blocks are the first line in small text, so that its emoji is small too, Slack's plan block with one task card per line, the links in small text, and while the run is not over, a Stop button. */
15
17
  export declare function planLayout(plan: Plan, settings: Config): Layout;
16
- /** What an approval question shows. `input` is the call's input as the text of a code block, and `consoleUrl` is the console's address when people can open it. */
18
+ /** Markdown that a model wrote, as Slack's mrkdwn, made plain first so it notifies nobody and hides no link: a heading and `**bold**` as bold, `__text__` as italic, `[label](https://…)` as a link, and a `-` or `*` item as a bullet. A code block keeps its lines as they are. */
19
+ export declare function mrkdwn(markdown: string): string;
20
+ /** `text` in parts of at most `limit` characters, split between paragraphs, and inside a longer paragraph between lines, else between two characters; never inside an entity. */
21
+ export declare function parts(text: string, limit?: number): readonly string[];
22
+ /** What an answer in a person's thread shows: the answer that a model wrote, the person it is for, the sources it rests on, whether the model was sure, and the card and the run's page to open. */
23
+ export interface Answered {
24
+ readonly text: string;
25
+ readonly user: string | undefined;
26
+ readonly sources: readonly string[];
27
+ readonly confident: boolean | undefined;
28
+ readonly card: NoteCard | undefined;
29
+ readonly page: string | undefined;
30
+ }
31
+ /** An answer as a person reads it: a mention of the person, then the answer as mrkdwn, in as many sections as it needs, split between paragraphs; a warning line when the model was not sure; the sources in small text, a web address as a link, as many as fit in one block; and a link button to the card and to the run's page. `limit` is the most characters of the answer. */
32
+ export declare function answerLayout(answered: Answered, limit: number): Layout;
33
+ /** What an approval question shows. `input` is the call's input as the engine shows it, `policy` is how often the project asks, and `consoleUrl` is the console's address when people can open it. */
17
34
  export interface Asked {
18
35
  readonly run: string;
19
36
  readonly tool: string;
20
37
  readonly operation: string;
21
- readonly input: {
22
- readonly text: string;
23
- readonly cut: boolean;
24
- } | undefined;
38
+ readonly policy: string | undefined;
39
+ readonly input: unknown;
25
40
  readonly card: NoteCard | undefined;
26
- readonly assignee: string | undefined;
27
41
  readonly user: string | undefined;
28
42
  readonly consoleUrl: string | undefined;
29
43
  }
30
- /** The approval question: who it is for and what EDGAR wants to run, the one thing to do, the input, the Approve and Deny buttons beside a link button to the card and to the run's page in the console, and the tool's own name in small text. With no card and no console, the small text says how to see the run. */
44
+ /** A call's input as the details a person approves: each field of an object as a bullet with its name in words, at most `FIELDS` of them, and any other input as a code block of its JSON, with no two backticks side by side to end it. `cut` says that a part is left out. */
45
+ export declare function detailsOf(input: unknown): {
46
+ readonly text: string;
47
+ readonly cut: boolean;
48
+ } | undefined;
49
+ /** The approval question: who it is for and what EDGAR wants to run, the one thing to do, the input, the Approve and Deny buttons beside a link button to the card and to the run's page in the console, and the tool's own name in small text. */
31
50
  export declare function askLayout(asked: Asked): Layout;
32
- /** A question that a done stage left open: who it is for, on which card, the question made plain with its lines kept, and how to answer it. */
51
+ /** A question that a done stage left open: the people it tags, already written for Slack, on which card, the question made plain with its lines kept, and how to answer it. */
33
52
  export declare function questionLayout(asked: {
34
53
  readonly run: string;
35
54
  readonly card: NoteCard | undefined;
36
- readonly assignee: string | undefined;
37
- readonly user: string | undefined;
55
+ readonly users: readonly string[];
38
56
  readonly question: string;
39
57
  }): Layout;
40
- /** The end note of a run: the status and the card on the first line; what happened, to the person it is for, with who approved the pull request and its merge commit when the note is about that; the options of a decision as a numbered list; the one thing the person does next, which for a step that the engine stopped trying is what to check before the replay; the facts in two columns, where "Run time" is the time from the start of this run to its end, with each wait in it; a link button to the card, to each pull request and to the run's page; and the failure as the engine wrote it in small text. A note with no link says how to see the run. With no `note`, the run's outcome did not read, and the note says only that. */
41
- export declare function noteLayout(run: string, note: EndNote | undefined, user: string | undefined): Layout;
58
+ /** The end of a run whose question is already in the thread above: one small line that points to it, with the card's service and what the run used. */
59
+ export declare function askedAboveLayout(run: string, note: EndNote): Layout;
60
+ /** The end note of a run: the status and the card on the first line; what happened, to the person it is for (for a decision or a hand-back, to the people of `tagged`, already written for Slack, when it has any), with who approved the pull request and its merge commit when the note is about that; the options of a decision as a numbered list; the one thing the person does next, which for a step that the engine stopped trying is what to check before the replay; a Try again button on a failed or a stopped run, which starts the run again, and a link button to the card, to each pull request and to the run's page; one small line with on whose behalf EDGAR works (`by`, the line of `behalfLine`), the run time from the start of this run to its end with each wait in it, the tokens and the cost; for a stopped run, who stopped it (`stopper`, already written for Slack) in the sentence and as "Stopped by" in that small line; and the failure as the engine wrote it in small text. A failure with no reason says so. The run's id is never shown: the run's page is a button. With no `note`, the run's outcome did not read, and the note says only that. */
61
+ export declare function noteLayout(run: string, note: EndNote | undefined, user: string | undefined, by?: string, stopper?: string, tagged?: readonly string[]): Layout;
62
+ /** On whose behalf EDGAR works and, when the run ran on a person's own key or subscription, on whose, in one phrase when it is the same person; none when the view names neither. */
63
+ export declare function behalfLine({ by, paid, paid_with }: RootView): string | undefined;
64
+ /** The first message of a card's thread, which changes in place with the status of the card's newest run: the emoji and the status in words with the card as a link and its title; one small line with the card's service, who asked for the work and who holds the card; what the card asks, in at most two lines; and a link button to the card and to each pull request to open. A card with no status yet shows only the card. */
65
+ export declare function rootLayout(card: NoteCard, view: RootView): Layout;
42
66
  export {};