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

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,10 +1,8 @@
1
1
  import { cardLine, cardMention, } from "@kana-ai/edgar-sdk";
2
2
  import { SECTION_CHARS, cutEscaped, escape, link } from "#outbound/tools";
3
- import { EMOJI, NOTE, PLAN, SAYS, STAGE, WAITS } from "#outbound/words";
3
+ import { ANSWER, EMOJI, MOVING, NOTE, PLAN, SAYS, STAGE, STATUS, WAITS, } from "#outbound/words";
4
4
  /** How Slack writes a link and a text that came from a card, a model or a failure. */
5
5
  export const style = { link, text: escape };
6
- /** The most characters of one field; Slack's limit is 2,000. */
7
- const FIELD_CHARS = 1900;
8
6
  /** The most characters of a summary or an option that a note shows before it stops at a sentence end. */
9
7
  const LEAD_CHARS = 600;
10
8
  /** The most options a decision note lists. */
@@ -21,15 +19,6 @@ function context(text) {
21
19
  elements: [{ type: "mrkdwn", text: cutEscaped(text, SECTION_CHARS - 1).text }],
22
20
  };
23
21
  }
24
- /** Facts as two aligned columns, each a bold label over its value; a fact with no value is left out, and one section holds 10. */
25
- function fields(pairs) {
26
- const shown = pairs
27
- .flatMap(([label, value]) => value === undefined
28
- ? []
29
- : [{ type: "mrkdwn", text: `*${label}*\n${cutEscaped(value, FIELD_CHARS).text}` }])
30
- .slice(0, 10);
31
- return shown.length === 0 ? [] : [{ type: "section", fields: shown }];
32
- }
33
22
  /** The targets as link buttons; a button's label holds 75 characters and its address 3,000. */
34
23
  function buttonsOf(targets) {
35
24
  return targets
@@ -91,6 +80,11 @@ export function stageLabel(stage) {
91
80
  const words = stage.replaceAll(/[_-]+/g, " ").trim();
92
81
  return known ?? `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
93
82
  }
83
+ /** 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. */
84
+ export function stageStatus(stage, settings) {
85
+ const known = Object.hasOwn(MOVING, stage) ? MOVING[stage] : undefined;
86
+ return settings.status[stage] ?? known ?? PLAN.status(stageLabel(stage));
87
+ }
94
88
  /** The line of one stage: a done stage that read what people decided on the pull request says that, a stage that waits is named by what it waits on, and only the wait that a person ends has the raised hand. */
95
89
  function rowOf({ stage, state, label }) {
96
90
  if (state === "done" && label !== undefined)
@@ -102,11 +96,31 @@ function rowOf({ stage, state, label }) {
102
96
  ? { id: stage, status: "waits", label: PLAN.waiting(stageLabel(stage)) }
103
97
  : { id: stage, status: wait.person ? "waiting" : "waits", label: wait.label };
104
98
  }
105
- /** 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. */
99
+ /** What a plan that is over says it ended as: the kind of its end note, kept in `ended`, or for a plan written before the kind was kept, `done` for the outcome `done` and `failed` for any other. */
100
+ function endedAs(ended) {
101
+ if (isKind(ended))
102
+ return ended;
103
+ return ended === "done" ? "done" : "failed";
104
+ }
105
+ function isKind(word) {
106
+ return Object.hasOwn(NOTE, word);
107
+ }
108
+ /** The Stop button of a run that is not over, which cancels the run. */
109
+ function stopOf(run) {
110
+ const text = { type: "plain_text", text: SAYS.stop };
111
+ return { type: "button", action_id: "edgar_stop", text, value: run, style: "danger" };
112
+ }
113
+ /** The progress of a run as one message that changes in place. A plan that holds its card's line, as in a thread that a person's message opened, starts with the status and the card as a link; in the card's own thread, whose first message says both, it starts with its steps. 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 status line, when there is one, 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. */
106
114
  export function planLayout(plan, settings) {
107
115
  const over = plan.ended !== undefined;
108
116
  const queued = over || plan.tasks.length > 0 ? undefined : plan.queued;
109
- const state = queued !== undefined ? "queued" : !over ? "working" : plan.ended === "done" ? "done" : "failed";
117
+ const state = queued !== undefined ? "queued" : "working";
118
+ const what = plan.ended === undefined ? undefined : endedAs(plan.ended);
119
+ const title = what === undefined
120
+ ? PLAN.title[state]
121
+ : what === "failed"
122
+ ? PLAN.title.failed
123
+ : NOTE[what].title;
110
124
  const shown = plan.tasks.filter((task) => !(over && task.state === "working"));
111
125
  const plain = (task) => task.state === "done" && task.label === undefined;
112
126
  const done = shown.filter(plain);
@@ -122,12 +136,10 @@ export function planLayout(plan, settings) {
122
136
  : [{ id: "run", label: SAYS.run, url: `${base}/runs/${encodeURIComponent(plan.run)}` }]),
123
137
  ...plan.pulls.map(({ url, label }, at) => ({
124
138
  id: `pull_${String(at)}`,
125
- label: SAYS.pull(label),
139
+ label: SAYS.pull(label, plan.pulls.length > 1),
126
140
  url,
127
141
  })),
128
142
  ];
129
- const head = headline(state === "queued" ? "waits" : state, PLAN.title[state], plan.card ?? `run ${plan.run}`);
130
- const links = linksOf(targets);
131
143
  const lines = queued !== undefined
132
144
  ? [
133
145
  PLAN.queued(queued.key, queued.value === undefined ? undefined : escape(queued.value), queued.limit, queued.workflow === undefined ? undefined : escape(queued.workflow)),
@@ -135,6 +147,13 @@ export function planLayout(plan, settings) {
135
147
  : rows.length === 0 && !over
136
148
  ? [PLAN.started]
137
149
  : rows.map((row) => `${EMOJI[row.status]} ${escape(row.label)}`);
150
+ const status = what ?? (state === "queued" ? "waits" : state);
151
+ const head = plan.card !== undefined
152
+ ? headline(status, title, plan.card)
153
+ : lines.length === 0
154
+ ? `${EMOJI[status]} *${title}*`
155
+ : "";
156
+ const links = linksOf(targets);
138
157
  const tasks = rows.map((row) => ({
139
158
  task_id: row.id.slice(0, 255),
140
159
  title: row.label,
@@ -143,21 +162,146 @@ export function planLayout(plan, settings) {
143
162
  return {
144
163
  text: [head, ...lines, links].filter((line) => line !== "").join("\n"),
145
164
  blocks: [
146
- context(head),
147
- ...(tasks.length > 0
148
- ? [{ type: "plan", title: PLAN.title[state], tasks }]
149
- : lines.map(section)),
165
+ ...(head === "" ? [] : [context(head)]),
166
+ ...(tasks.length > 0 ? [{ type: "plan", title, tasks }] : lines.map(section)),
150
167
  ...(links === "" ? [] : [context(links)]),
168
+ ...(over ? [] : [{ type: "actions", elements: [stopOf(plan.run)] }]),
169
+ ],
170
+ };
171
+ }
172
+ /** 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, also with the address or the label in angle brackets, and a `-` or `*` item as a bullet. A code block keeps its lines as they are. */
173
+ export function mrkdwn(markdown) {
174
+ return markdown
175
+ .split(/(```[\s\S]*?```)/)
176
+ .map((part, at) => at % 2 === 1
177
+ ? escape(part)
178
+ : escape(part)
179
+ .replaceAll(/^#{1,6}\s+(.+?)\s*#*$/gm, "*$1*")
180
+ .replaceAll(/\*\*(.+?)\*\*/g, "*$1*")
181
+ .replaceAll(/__(.+?)__/g, "_$1_")
182
+ .replaceAll(/^(\s*)[-*]\s+/gm, "$1• ")
183
+ .replaceAll(/\[([^\]\n]+)\]\((?:&lt;)?(https?:\/\/[^)\s|]+?)(?:&gt;)?\)/g, (_, label, url) => `<${url}|${label.replace(/^&lt;(.+)&gt;$/, "$1")}>`))
184
+ .join("");
185
+ }
186
+ /** `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. */
187
+ export function parts(text, limit = SECTION_CHARS - 1) {
188
+ const out = [];
189
+ let current = "";
190
+ const flush = () => {
191
+ if (current !== "")
192
+ out.push(current);
193
+ current = "";
194
+ };
195
+ for (const paragraph of text.split(/\n{2,}/)) {
196
+ const joined = current === "" ? paragraph : `${current}\n\n${paragraph}`;
197
+ if (joined.length <= limit) {
198
+ current = joined;
199
+ continue;
200
+ }
201
+ flush();
202
+ let rest = paragraph;
203
+ while (rest.length > limit) {
204
+ const line = rest.lastIndexOf("\n", limit);
205
+ const head = line > 0 ? rest.slice(0, line) : cutEscaped(rest, limit - 1).text.slice(0, -1);
206
+ out.push(head);
207
+ rest = rest.slice(head.length).replace(/^\n/, "");
208
+ }
209
+ current = rest;
210
+ }
211
+ flush();
212
+ return out;
213
+ }
214
+ /** The most sources an answer lists. */
215
+ const SOURCES = 8;
216
+ /** 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. */
217
+ export function answerLayout(answered, limit) {
218
+ const body = ANSWER.said(answered.user, cutEscaped(mrkdwn(answered.text.trim()), limit).text);
219
+ const sources = answered.sources
220
+ .map((source) => source.trim())
221
+ .filter((source) => source !== "")
222
+ .slice(0, SOURCES)
223
+ .map((source) => /^https?:\/\/\S+$/.test(source)
224
+ ? link(source, source.replace(/^https?:\/\//, ""))
225
+ : escape(source))
226
+ .reduce((kept, source) => ANSWER.sources([...kept, source].join(" · ")).length < SECTION_CHARS
227
+ ? [...kept, source]
228
+ : kept, []);
229
+ const small = [
230
+ ...(answered.confident === false ? [ANSWER.unsure] : []),
231
+ ...(sources.length === 0 ? [] : [ANSWER.sources(sources.join(" · "))]),
232
+ ];
233
+ const targets = [
234
+ ...(answered.card === undefined
235
+ ? []
236
+ : [{ id: "card", label: SAYS.card, url: answered.card.url }]),
237
+ ...(answered.page === undefined ? [] : [{ id: "run", label: SAYS.run, url: answered.page }]),
238
+ ];
239
+ const buttons = buttonsOf(targets);
240
+ return {
241
+ text: [body, ...small].join("\n"),
242
+ blocks: [
243
+ ...parts(body).map((part) => ({ type: "section", text: { type: "mrkdwn", text: part } })),
244
+ ...small.map(context),
245
+ ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
151
246
  ],
152
247
  };
153
248
  }
154
- /** A tool's name as a person reads it: `github__open_pull_request` is "open pull request (github)". */
249
+ /** A tool's name as a person reads it: `github__open_pull_request` does "open pull request" in "github". */
155
250
  function toolWords(tool) {
156
251
  const [extension, name] = tool.split("__");
157
- const words = (name ?? extension ?? tool).replaceAll("_", " ");
158
- return escape(name === undefined ? words : `${words} (${extension ?? ""})`);
252
+ const doing = escape((name ?? extension ?? tool).replaceAll("_", " "));
253
+ return {
254
+ doing,
255
+ system: name === undefined || extension === undefined ? undefined : escape(extension),
256
+ };
159
257
  }
160
- /** 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. */
258
+ /** A tool whose name says it deletes or removes something. */
259
+ const REMOVES = /(?:^|_)(?:delete|remove|drop|destroy|purge|revoke)(?:_|$)/;
260
+ /** The most characters of the details of an approval; a section's text holds 3,000. */
261
+ const DETAILS_CHARS = 2400;
262
+ /** The most fields of a call's input that an approval lists, and the most characters of one. */
263
+ const FIELDS = 12;
264
+ const VALUE_CHARS = 300;
265
+ /** One value of a call's input as a person reads it, in code so that no markup in it shows as Slack formatting: a text on one line, a list of texts and numbers joined, anything else as compact JSON, each made plain and cut; a number or a flag as it is. A value that holds a backtick goes in a code block, with no two backticks side by side to end it, so it shows as written. */
266
+ function valueWords(value) {
267
+ if (typeof value === "number" || typeof value === "boolean")
268
+ return { text: String(value), cut: false };
269
+ if (typeof value === "string" && value.trim() === "")
270
+ return { text: "_empty_", cut: false };
271
+ const scalars = Array.isArray(value) &&
272
+ value.every((item) => typeof item === "string" || typeof item === "number");
273
+ const text = typeof value === "string"
274
+ ? value.replaceAll(/\s+/g, " ").trim()
275
+ : scalars
276
+ ? value.join(", ")
277
+ : (JSON.stringify(value) ?? "null");
278
+ const shown = cutEscaped(escape(text), VALUE_CHARS);
279
+ return {
280
+ text: shown.text.includes("`")
281
+ ? `\`\`\`\u{200b}${shown.text.replaceAll(/`(?=`)/g, "`\u{200b}")}\u{200b}\`\`\``
282
+ : `\`${shown.text}\``,
283
+ cut: shown.cut,
284
+ };
285
+ }
286
+ /** 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. */
287
+ export function detailsOf(input) {
288
+ if (input === undefined || input === null)
289
+ return undefined;
290
+ if (typeof input !== "object" || Array.isArray(input)) {
291
+ const json = escape(JSON.stringify(input, null, 2)).replace(/`(?=`)/g, "`\u{200b}");
292
+ const shown = cutEscaped(json, DETAILS_CHARS);
293
+ return { text: `\`\`\`${shown.text}\`\`\``, cut: shown.cut };
294
+ }
295
+ const fields = Object.entries(input);
296
+ if (fields.length === 0)
297
+ return undefined;
298
+ const values = fields.slice(0, FIELDS).map(([key, value]) => ({ key, ...valueWords(value) }));
299
+ const lines = values.map(({ key, text }) => `• *${escape(key.replaceAll("_", " "))}*: ${text}`);
300
+ const more = fields.length > FIELDS ? [SAYS.approvalMore(fields.length - FIELDS)] : [];
301
+ const shown = cutEscaped([...lines, ...more].join("\n"), DETAILS_CHARS);
302
+ return { text: shown.text, cut: shown.cut || more.length > 0 || values.some(({ cut }) => cut) };
303
+ }
304
+ /** 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. */
161
305
  export function askLayout(asked) {
162
306
  const { run, tool, card, input } = asked;
163
307
  const who = whoOf(asked.user);
@@ -171,15 +315,20 @@ export function askLayout(asked) {
171
315
  ];
172
316
  const about = card === undefined ? `run ${run}` : cardLine(card, style);
173
317
  const head = headline("waiting", SAYS.approvalTitle, about);
174
- const said = greeted(who, SAYS.approval(toolWords(tool)));
175
- const cut = input?.cut === true
318
+ const { doing, system } = toolWords(tool);
319
+ const details = detailsOf(input);
320
+ const removes = REMOVES.test(tool) ? [SAYS.approvalRemoves] : [];
321
+ const said = [
322
+ greeted(who, SAYS.approval(doing, system)),
323
+ SAYS.approvalWhy(asked.policy),
324
+ ...removes,
325
+ ].join("\n");
326
+ const listed = details === undefined ? undefined : `${SAYS.approvalDetails}\n${details.text}`;
327
+ const cut = details?.cut === true
176
328
  ? ` ${SAYS.approvalCut(page === undefined ? "Needs a person" : link(page, "Needs a person"))}`
177
329
  : "";
178
- const next = `*${SAYS.next}* ${SAYS.approvalNext(input !== undefined)}${cut}`;
179
- const small = [
180
- SAYS.approvalTool(escape(tool), run),
181
- ...(targets.length === 0 ? [SAYS.reach(run)] : []),
182
- ].join(" · ");
330
+ const next = `*${SAYS.next}* ${SAYS.approvalNext(details !== undefined)}${cut}`;
331
+ const small = SAYS.approvalTool(escape(tool), run);
183
332
  const press = (action) => ({
184
333
  type: "button",
185
334
  action_id: `edgar_${action}`,
@@ -188,11 +337,14 @@ export function askLayout(asked) {
188
337
  ...(action === "approve" ? { style: "primary" } : {}),
189
338
  });
190
339
  return {
191
- text: [head, said, next, linksOf(targets), small].filter((line) => line !== "").join("\n"),
340
+ text: [head, said, listed ?? "", next, linksOf(targets), small]
341
+ .filter((line) => line !== "")
342
+ .join("\n"),
192
343
  blocks: [
193
344
  section(head),
194
- section(`${said}\n${next}`),
195
- ...(input === undefined ? [] : [section(`\`\`\`${input.text}\`\`\``)]),
345
+ section(said),
346
+ ...(listed === undefined ? [] : [section(listed)]),
347
+ section(next),
196
348
  { type: "actions", elements: [press("approve"), press("deny"), ...buttonsOf(targets)] },
197
349
  context(small),
198
350
  ],
@@ -200,14 +352,14 @@ export function askLayout(asked) {
200
352
  }
201
353
  /** The most characters of a question that a model wrote, so the question and its words around it fit in one section. */
202
354
  const QUESTION_CHARS = 2400;
203
- /** 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. */
355
+ /** 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, which names the number of another option only when the question lists numbered options. */
204
356
  export function questionLayout(asked) {
205
357
  const { run, card } = asked;
206
358
  const name = card === undefined ? `run ${run}` : escape(card.id ?? "this card");
207
359
  const head = headline("waiting", SAYS.questionTitle, card === undefined ? name : cardLine(card, style));
208
- const said = greeted(whoOf(asked.user), SAYS.question(name));
360
+ const said = greeted(tagsOf(asked.users), SAYS.question(name));
209
361
  const question = cutEscaped(escape(asked.question.trim()), QUESTION_CHARS).text;
210
- const next = `*${SAYS.next}* ${SAYS.questionNext}`;
362
+ const next = `*${SAYS.next}* ${SAYS.questionNext(/^\s*\d+[.)]\s+\S/m.test(question))}`;
211
363
  return {
212
364
  text: [head, said, question, next].join("\n"),
213
365
  blocks: [section(head), section([said, question, next].join("\n"))],
@@ -215,10 +367,29 @@ export function questionLayout(asked) {
215
367
  }
216
368
  /** "ana", "ana and bo", "ana, bo, and cy". */
217
369
  const names = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
218
- /** The kinds of end note that say the summary of the run's proposal after their first sentence: what the run did, what it asks, what it changed, or what it waits on. A note on what people decided on the pull request says none: the proposal was written before the pull request. */
219
- const SUMMED = new Set(["decision", "done", "opened", "waits"]);
220
- /** 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. */
221
- export function noteLayout(run, note, user) {
370
+ /** The people a message tags as one phrase, or nobody. */
371
+ function tagsOf(users) {
372
+ return users.length === 0 ? undefined : names.format(users);
373
+ }
374
+ /** What a run used, as one small line that goes under its question when the run ends on it: the run time, the tokens and the cost; no block when the run names none. */
375
+ export function usedLayout({ facts }) {
376
+ const line = [
377
+ ...(facts.took === undefined ? [] : [facts.took]),
378
+ ...(facts.tokens === undefined ? [] : [`${facts.tokens} tokens`]),
379
+ ...(facts.cost === undefined ? [] : [facts.cost]),
380
+ ].join(" · ");
381
+ return { text: line, blocks: line === "" ? [] : [context(line)] };
382
+ }
383
+ /** The kinds of end note that say the summary of the run's proposal after their first sentence: what the run did, what it asks, why it handed the card back, what it changed, or what it waits on. A note on what people decided on the pull request says none: the proposal was written before the pull request. */
384
+ const SUMMED = new Set([
385
+ "decision",
386
+ "done",
387
+ "handed",
388
+ "opened",
389
+ "waits",
390
+ ]);
391
+ /** 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. */
392
+ export function noteLayout(run, note, user, by, stopper, tagged = []) {
222
393
  if (note === undefined)
223
394
  return { text: SAYS.unread(run), blocks: [section(SAYS.unread(run))] };
224
395
  const { card, facts, what } = note;
@@ -244,24 +415,30 @@ export function noteLayout(run, note, user) {
244
415
  ? undefined
245
416
  : (facts.why ??
246
417
  (facts.failure === undefined
247
- ? undefined
418
+ ? SAYS.noReason
248
419
  : SAYS.detail(facts.stage, lead(facts.failure, 200).text)));
249
420
  const targets = [
250
421
  ...(card === undefined ? [] : [{ id: "card", label: SAYS.card, url: card.url }]),
251
- ...facts.pulls
252
- .slice(0, 3)
253
- .map(({ url, label }, at) => ({ id: `pull_${String(at)}`, label: SAYS.pull(label), url })),
422
+ ...facts.pulls.slice(0, 3).map(({ url, label }, at) => ({
423
+ id: `pull_${String(at)}`,
424
+ label: SAYS.pull(label, facts.pulls.length > 1),
425
+ url,
426
+ })),
254
427
  ...(facts.page === undefined ? [] : [{ id: "run", label: SAYS.run, url: facts.page }]),
255
428
  ];
429
+ const asking = (what === "decision" || what === "handed") && tagged.length > 0;
256
430
  const said = [
257
- greeted(who, words.said(name, count)),
431
+ greeted(asking ? tagsOf(tagged) : who, what === "handed" && facts.handedTo !== undefined
432
+ ? SAYS.handedTo(name, escape(facts.handedTo))
433
+ : what === "stopped" && stopper !== undefined
434
+ ? SAYS.stoppedWork(name, stopper)
435
+ : words.said(name, count)),
258
436
  ...(facts.approvedBy === undefined
259
437
  ? []
260
438
  : [SAYS.approvedBy(escape(names.format(facts.approvedBy)))]),
261
439
  ...(facts.commit === undefined ? [] : [SAYS.commit(escape(facts.commit))]),
262
440
  ...(why === undefined ? [] : [why]),
263
441
  ...(summary === undefined ? [] : [linked(summary.text)]),
264
- ...(what === "opened" && facts.risk !== undefined ? [escape(facts.risk)] : []),
265
442
  ...(summary?.cut === true && targets.length > 0 ? [SAYS.more] : []),
266
443
  ].join(" ");
267
444
  const options = what === "decision"
@@ -270,38 +447,128 @@ export function noteLayout(run, note, user) {
270
447
  .map((option, at) => `${String(at + 1)}. ${linked(lead(option, 300).text)}`)
271
448
  : [];
272
449
  const told = what === "failed" && facts.next !== undefined
273
- ? SAYS.replay(facts.next, run)
450
+ ? SAYS.replay(facts.next)
274
451
  : words.next?.(run, what === "decision" ? options.length : facts.pulls.length);
275
452
  const next = told === undefined ? undefined : `*${SAYS.next}* ${told}`;
276
453
  const head = headline(what, words.title, card === undefined ? name : cardLine(card, style));
277
454
  const detail = what === "failed" && facts.failure !== undefined && facts.why !== undefined
278
455
  ? [SAYS.detail(facts.stage, lead(facts.failure, 300).text)]
279
456
  : [];
280
- const small = [...detail, ...(targets.length === 0 ? [SAYS.reach(run)] : [])].join(" · ");
457
+ const small = detail.join(" · ");
281
458
  const used = [
282
- `Run ${run}`,
459
+ ...(by === undefined ? [] : [by]),
283
460
  ...(facts.took === undefined ? [] : [facts.took]),
284
461
  ...(facts.tokens === undefined ? [] : [`${facts.tokens} tokens`]),
285
462
  ...(facts.cost === undefined ? [] : [facts.cost]),
463
+ ...(what === "stopped" && stopper !== undefined ? [SAYS.stopper(stopper)] : []),
286
464
  ].join(" · ");
287
- const body = [said, ...options, ...(next === undefined ? [] : [next])];
288
- const buttons = buttonsOf(targets);
465
+ const pulls = what === "opened"
466
+ ? facts.pulls
467
+ .filter((pull) => pull.referenced !== true)
468
+ .map(({ url, label }) => `• ${link(url, label)}`)
469
+ : [];
470
+ const risk = what === "opened" && facts.risk !== undefined ? SAYS.risk(escape(facts.risk)) : "";
471
+ const body = [said, ...options, ...pulls, ...(next === undefined ? [] : [next])];
472
+ const shown = pulls.length === 0 ? targets : targets.filter(({ id }) => !id.startsWith("pull_"));
473
+ const again = what === "failed" || what === "stopped"
474
+ ? [
475
+ {
476
+ type: "button",
477
+ action_id: "edgar_replay",
478
+ text: { type: "plain_text", text: SAYS.tryAgain },
479
+ value: run,
480
+ style: "primary",
481
+ },
482
+ ]
483
+ : [];
484
+ const buttons = [...again, ...buttonsOf(targets)];
289
485
  return {
290
- text: [head, ...body, linksOf(targets), small, used].filter((line) => line !== "").join("\n"),
486
+ text: [head, ...body, risk, linksOf(shown), small, used]
487
+ .filter((line) => line !== "")
488
+ .join("\n"),
291
489
  blocks: [
292
490
  section(head),
293
491
  section(body.join("\n")),
294
- ...fields([
295
- ["Service", card?.service === undefined ? undefined : escape(card.service)],
296
- ["Step", facts.stage === undefined ? undefined : escape(facts.stage)],
297
- ["Run time", facts.took],
298
- ["Tokens", facts.tokens],
299
- ["Cost", facts.cost],
300
- ["Assignee", who],
301
- ["Run", run],
302
- ]),
492
+ ...(risk === "" ? [] : [section(risk)]),
493
+ ...(used === "" ? [] : [context(used)]),
303
494
  ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
304
495
  ...(small === "" ? [] : [context(small)]),
305
496
  ],
306
497
  };
307
498
  }
499
+ /** 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. */
500
+ export function behalfLine({ by, paid, paid_with }) {
501
+ if (paid === undefined || paid_with === undefined)
502
+ return by === undefined ? undefined : SAYS.behalf(by);
503
+ if (by === undefined)
504
+ return SAYS.paidOnly(paid, paid_with);
505
+ return by === paid
506
+ ? SAYS.behalfOwn(by, paid_with)
507
+ : `${SAYS.behalf(by)} · ${SAYS.paid(paid, paid_with)}`;
508
+ }
509
+ function isStatus(word) {
510
+ return Object.hasOwn(STATUS, word);
511
+ }
512
+ /** A word of mrkdwn: a link, a code span and an entity stay whole in it, so a cut between words never breaks one. */
513
+ const WORDS = /(?:<[^>]*>|`[^`\n]*`|\S)+|\s+/g;
514
+ /** Whether `word` opens a bracket, an angle bracket or a code span that it does not close. */
515
+ function unclosed(word) {
516
+ const count = (mark) => word.split(mark).length - 1;
517
+ return (count("[") > count("]") ||
518
+ count("(") > count(")") ||
519
+ count("&lt;") > count("&gt;") ||
520
+ count("`") % 2 === 1);
521
+ }
522
+ /** `markdown` as mrkdwn within `limit` characters, cut only between words, and with " …" when cut. A text that ends in "…" was cut already: its last word is only a part, so it goes, with each word before it that opens what it never closes. */
523
+ function wholeWords(markdown, limit) {
524
+ const before = markdown.trim().endsWith("…");
525
+ const words = mrkdwn(before ? markdown.trim().slice(0, -1) : markdown.trim()).match(WORDS) ?? [];
526
+ const kept = [];
527
+ let length = 0;
528
+ for (const word of words) {
529
+ if (length + word.length > limit - 2)
530
+ break;
531
+ kept.push(word);
532
+ length += word.length;
533
+ }
534
+ const cut = before || kept.length < words.length;
535
+ if (before && kept.length === words.length && !/^\s/.test(kept.at(-1) ?? " "))
536
+ kept.pop();
537
+ while (kept.length > 0 && (/^\s/.test(kept.at(-1) ?? "") || (cut && unclosed(kept.at(-1) ?? ""))))
538
+ kept.pop();
539
+ return cut ? `${kept.join("")} …`.trimStart() : kept.join("");
540
+ }
541
+ /** 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, unless the title already names it, who asked for the work and who holds the card; what the card asks, in at most two lines, with its Markdown as mrkdwn and cut only between words; and a link button to the card and to each pull request to open. A card with no status yet shows only the card. */
542
+ export function rootLayout(card, view) {
543
+ const status = view.status !== undefined && isStatus(view.status) ? view.status : undefined;
544
+ const title = card.id === undefined
545
+ ? link(card.url, card.title)
546
+ : `${link(card.url, card.id)} ${escape(card.title)}`;
547
+ const head = status === undefined ? title : headline(status, STATUS[status], title);
548
+ const behalf = behalfLine(view);
549
+ const named = card.service !== undefined && card.title.toLowerCase().includes(card.service.toLowerCase());
550
+ const about = [
551
+ ...(card.service === undefined || named ? [] : [escape(card.service)]),
552
+ ...(behalf === undefined ? [] : [behalf]),
553
+ ...(view.holder === undefined ? [] : [SAYS.holder(view.holder)]),
554
+ ].join(" · ");
555
+ const ask = view.ask === undefined ? "" : wholeWords(view.ask, 600);
556
+ const targets = [
557
+ { id: "card", label: SAYS.card, url: card.url },
558
+ ...(view.pulls ?? []).slice(0, 3).map(({ url, label }, at, all) => ({
559
+ id: `pull_${String(at)}`,
560
+ label: SAYS.pull(label, all.length > 1),
561
+ url,
562
+ })),
563
+ ];
564
+ const buttons = buttonsOf(targets);
565
+ return {
566
+ text: [head, about, ask].filter((line) => line !== "").join("\n"),
567
+ blocks: [
568
+ section(head),
569
+ ...(about === "" ? [] : [context(about)]),
570
+ ...(ask === "" ? [] : [section(ask)]),
571
+ ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
572
+ ],
573
+ };
574
+ }
@@ -6,20 +6,24 @@ import { type message, posted } from "#schemas/slack";
6
6
  /** A message EDGAR posted, as Slack lists it. */
7
7
  export type Message = z.infer<typeof message>;
8
8
  /** The metadata of an EDGAR message of `kind`, so a later call can find it. */
9
- export declare function mark(kind: "edgar_post" | "edgar_ask" | "edgar_answered" | "edgar_closed" | "edgar_plan" | "edgar_approval" | "edgar_question" | "edgar_card" | "edgar_ready" | "edgar_end" | "edgar_relayed" | "edgar_relay_done" | "edgar_answer" | "edgar_post_to" | "edgar_post_done", payload: Readonly<Record<string, unknown>>): {
10
- event_type: "edgar_answer" | "edgar_answered" | "edgar_approval" | "edgar_ask" | "edgar_card" | "edgar_closed" | "edgar_end" | "edgar_plan" | "edgar_post" | "edgar_post_done" | "edgar_post_to" | "edgar_question" | "edgar_ready" | "edgar_relay_done" | "edgar_relayed";
9
+ export declare function mark(kind: "edgar_post" | "edgar_ask" | "edgar_answered" | "edgar_closed" | "edgar_plan" | "edgar_approval" | "edgar_question" | "edgar_card" | "edgar_ready" | "edgar_end" | "edgar_relayed" | "edgar_relay_done" | "edgar_answer" | "edgar_said" | "edgar_post_to" | "edgar_post_done", payload: Readonly<Record<string, unknown>>): {
10
+ event_type: "edgar_answer" | "edgar_answered" | "edgar_approval" | "edgar_ask" | "edgar_card" | "edgar_closed" | "edgar_end" | "edgar_plan" | "edgar_post" | "edgar_post_done" | "edgar_post_to" | "edgar_question" | "edgar_ready" | "edgar_relay_done" | "edgar_relayed" | "edgar_said";
11
11
  event_payload: Readonly<Record<string, unknown>>;
12
12
  };
13
13
  /** Posts `text` with `extra` fields (blocks, metadata) in `channel`, in `thread` when given. Blocks that Slack refuses are left out, as `written` says. */
14
14
  export declare function post(ctx: SlackCtx, channel: string, thread: string | undefined, text: string, extra?: Readonly<Record<string, unknown>>): Promise<Result<z.infer<typeof posted>, Failure>>;
15
15
  /** Changes the message at `ts` to `text` with `extra` fields (blocks, metadata). Blocks that Slack refuses are left out, as `written` says. */
16
16
  export declare function update(ctx: SlackCtx, channel: string, ts: string, text: string, extra?: Readonly<Record<string, unknown>>): Promise<Result<z.infer<typeof posted>, Failure>>;
17
- /** The messages of the thread, or of the channel's recent history, each with its metadata. */
17
+ /** Deletes the message at `ts`; a message that is already gone is no failure. */
18
+ export declare function remove(ctx: SlackCtx, channel: string, ts: string): Promise<Result<undefined, Failure>>;
19
+ /** The messages of the thread, or of the channel's newest `HISTORY_PAGE` messages, each with its metadata. */
18
20
  export declare function listed(ctx: SlackCtx, channel: string, thread: string | undefined): Promise<Result<readonly Message[], Failure>>;
19
21
  /** The newest of `all`, by its timestamp, whose metadata is `kind` and passes `match`. */
20
22
  export declare function newestMarked(all: readonly Message[], kind: string, match?: (payload: Readonly<Record<string, unknown>>) => boolean): Message | undefined;
21
23
  /** The newest message, by its timestamp, in the thread or in the channel's recent history, whose metadata is `kind` and passes `match`. */
22
24
  export declare function findMarked(ctx: SlackCtx, channel: string, thread: string | undefined, kind: string, match: (payload: Readonly<Record<string, unknown>>) => boolean): Promise<Result<Message | undefined, Failure>>;
25
+ /** The newest message of the channel's newest `HISTORY_MESSAGES` whose metadata is `kind` and passes `match`, read page by page, newest first, up to the first page that holds one. A page that fails, such as a rate limit that outlasts the client's waits, fails the answer and never reads as none, so a caller never opens a second thread for a card that has one. */
26
+ export declare function findInChannel(ctx: SlackCtx, channel: string, kind: string, match: (payload: Readonly<Record<string, unknown>>) => boolean): Promise<Result<Message | undefined, Failure>>;
23
27
  /** The notes of `all` that say EDGAR put a person's reply on a card and that no run has answered yet, oldest first; with `now`, only those of the last `WAIT_MINUTES`. */
24
28
  export declare function waitingRelays(all: readonly Message[], now?: number): readonly Message[];
25
29
  /** The card that a thread with no run is bound to: the card that the newest note of a relayed reply there names. */
@@ -32,6 +36,16 @@ export declare function dmChannel(ctx: SlackCtx, to: {
32
36
  } | {
33
37
  readonly email: string;
34
38
  }): Promise<Result<string, Failure>>;
39
+ /** The reactions EDGAR puts on a person's message: `seen` as soon as it takes the message, then `done` once it answered or acted on it, or `failed` when it could not. */
40
+ export declare const REACTION: {
41
+ readonly seen: "eyes";
42
+ readonly done: "white_check_mark";
43
+ readonly failed: "x";
44
+ };
45
+ /** Puts the reaction `name` on the message at `ts`, or takes it off with `off`. A reaction is a hint to the person: a refusal, such as one that is already there, is one log line and never fails the delivery. */
46
+ export declare function react(ctx: SlackCtx, channel: string, ts: string, name: string, off?: boolean): Promise<void>;
47
+ /** Swaps the `seen` reaction on the message at `ts` for `done` when EDGAR answered or acted on it, else for `failed`. */
48
+ export declare function reacted(ctx: SlackCtx, channel: string, ts: string, worked: boolean): Promise<void>;
35
49
  /** The session status is a hint to the person; a failed status call is logged and never fails the delivery. */
36
50
  export declare function status(ctx: SlackCtx, origin: Origin, value: "processing" | "suspended" | "active" | "closed", title?: string): Promise<void>;
37
51
  /** The moving line under a thread, which Slack shows as the app's name and then `text`; `""` removes it. Slack removes it when the app posts in the thread, and by itself after 2 minutes with no message. It is a hint to the person; a failed call is logged with Slack's own error and never fails the delivery. */