@kana-ai/edgar-ext-slack 0.1.4 → 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,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. 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. */
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,11 +136,11 @@ 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}`);
143
+ const head = headline(what ?? (state === "queued" ? "waits" : state), title, plan.card ?? `run ${plan.run}`);
130
144
  const links = linksOf(targets);
131
145
  const lines = queued !== undefined
132
146
  ? [
@@ -144,20 +158,145 @@ export function planLayout(plan, settings) {
144
158
  text: [head, ...lines, links].filter((line) => line !== "").join("\n"),
145
159
  blocks: [
146
160
  context(head),
147
- ...(tasks.length > 0
148
- ? [{ type: "plan", title: PLAN.title[state], tasks }]
149
- : lines.map(section)),
161
+ ...(tasks.length > 0 ? [{ type: "plan", title, tasks }] : lines.map(section)),
150
162
  ...(links === "" ? [] : [context(links)]),
163
+ ...(over ? [] : [{ type: "actions", elements: [stopOf(plan.run)] }]),
164
+ ],
165
+ };
166
+ }
167
+ /** 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. */
168
+ export function mrkdwn(markdown) {
169
+ return markdown
170
+ .split(/(```[\s\S]*?```)/)
171
+ .map((part, at) => at % 2 === 1
172
+ ? escape(part)
173
+ : escape(part)
174
+ .replaceAll(/^#{1,6}\s+(.+?)\s*#*$/gm, "*$1*")
175
+ .replaceAll(/\*\*(.+?)\*\*/g, "*$1*")
176
+ .replaceAll(/__(.+?)__/g, "_$1_")
177
+ .replaceAll(/^(\s*)[-*]\s+/gm, "$1• ")
178
+ .replaceAll(/\[([^\]\n]+)\]\((https?:\/\/[^)\s|]+)\)/g, (_, label, url) => `<${url}|${label}>`))
179
+ .join("");
180
+ }
181
+ /** `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. */
182
+ export function parts(text, limit = SECTION_CHARS - 1) {
183
+ const out = [];
184
+ let current = "";
185
+ const flush = () => {
186
+ if (current !== "")
187
+ out.push(current);
188
+ current = "";
189
+ };
190
+ for (const paragraph of text.split(/\n{2,}/)) {
191
+ const joined = current === "" ? paragraph : `${current}\n\n${paragraph}`;
192
+ if (joined.length <= limit) {
193
+ current = joined;
194
+ continue;
195
+ }
196
+ flush();
197
+ let rest = paragraph;
198
+ while (rest.length > limit) {
199
+ const line = rest.lastIndexOf("\n", limit);
200
+ const head = line > 0 ? rest.slice(0, line) : cutEscaped(rest, limit - 1).text.slice(0, -1);
201
+ out.push(head);
202
+ rest = rest.slice(head.length).replace(/^\n/, "");
203
+ }
204
+ current = rest;
205
+ }
206
+ flush();
207
+ return out;
208
+ }
209
+ /** The most sources an answer lists. */
210
+ const SOURCES = 8;
211
+ /** 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. */
212
+ export function answerLayout(answered, limit) {
213
+ const body = ANSWER.said(answered.user, cutEscaped(mrkdwn(answered.text.trim()), limit).text);
214
+ const sources = answered.sources
215
+ .map((source) => source.trim())
216
+ .filter((source) => source !== "")
217
+ .slice(0, SOURCES)
218
+ .map((source) => /^https?:\/\/\S+$/.test(source)
219
+ ? link(source, source.replace(/^https?:\/\//, ""))
220
+ : escape(source))
221
+ .reduce((kept, source) => ANSWER.sources([...kept, source].join(" · ")).length < SECTION_CHARS
222
+ ? [...kept, source]
223
+ : kept, []);
224
+ const small = [
225
+ ...(answered.confident === false ? [ANSWER.unsure] : []),
226
+ ...(sources.length === 0 ? [] : [ANSWER.sources(sources.join(" · "))]),
227
+ ];
228
+ const targets = [
229
+ ...(answered.card === undefined
230
+ ? []
231
+ : [{ id: "card", label: SAYS.card, url: answered.card.url }]),
232
+ ...(answered.page === undefined ? [] : [{ id: "run", label: SAYS.run, url: answered.page }]),
233
+ ];
234
+ const buttons = buttonsOf(targets);
235
+ return {
236
+ text: [body, ...small].join("\n"),
237
+ blocks: [
238
+ ...parts(body).map((part) => ({ type: "section", text: { type: "mrkdwn", text: part } })),
239
+ ...small.map(context),
240
+ ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
151
241
  ],
152
242
  };
153
243
  }
154
- /** A tool's name as a person reads it: `github__open_pull_request` is "open pull request (github)". */
244
+ /** A tool's name as a person reads it: `github__open_pull_request` does "open pull request" in "github". */
155
245
  function toolWords(tool) {
156
246
  const [extension, name] = tool.split("__");
157
- const words = (name ?? extension ?? tool).replaceAll("_", " ");
158
- return escape(name === undefined ? words : `${words} (${extension ?? ""})`);
247
+ const doing = escape((name ?? extension ?? tool).replaceAll("_", " "));
248
+ return {
249
+ doing,
250
+ system: name === undefined || extension === undefined ? undefined : escape(extension),
251
+ };
252
+ }
253
+ /** A tool whose name says it deletes or removes something. */
254
+ const REMOVES = /(?:^|_)(?:delete|remove|drop|destroy|purge|revoke)(?:_|$)/;
255
+ /** The most characters of the details of an approval; a section's text holds 3,000. */
256
+ const DETAILS_CHARS = 2400;
257
+ /** The most fields of a call's input that an approval lists, and the most characters of one. */
258
+ const FIELDS = 12;
259
+ const VALUE_CHARS = 300;
260
+ /** 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. */
261
+ function valueWords(value) {
262
+ if (typeof value === "number" || typeof value === "boolean")
263
+ return { text: String(value), cut: false };
264
+ if (typeof value === "string" && value.trim() === "")
265
+ return { text: "_empty_", cut: false };
266
+ const scalars = Array.isArray(value) &&
267
+ value.every((item) => typeof item === "string" || typeof item === "number");
268
+ const text = typeof value === "string"
269
+ ? value.replaceAll(/\s+/g, " ").trim()
270
+ : scalars
271
+ ? value.join(", ")
272
+ : (JSON.stringify(value) ?? "null");
273
+ const shown = cutEscaped(escape(text), VALUE_CHARS);
274
+ return {
275
+ text: shown.text.includes("`")
276
+ ? `\`\`\`\u{200b}${shown.text.replaceAll(/`(?=`)/g, "`\u{200b}")}\u{200b}\`\`\``
277
+ : `\`${shown.text}\``,
278
+ cut: shown.cut,
279
+ };
280
+ }
281
+ /** 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. */
282
+ export function detailsOf(input) {
283
+ if (input === undefined || input === null)
284
+ return undefined;
285
+ if (typeof input !== "object" || Array.isArray(input)) {
286
+ const json = escape(JSON.stringify(input, null, 2)).replace(/`(?=`)/g, "`\u{200b}");
287
+ const shown = cutEscaped(json, DETAILS_CHARS);
288
+ return { text: `\`\`\`${shown.text}\`\`\``, cut: shown.cut };
289
+ }
290
+ const fields = Object.entries(input);
291
+ if (fields.length === 0)
292
+ return undefined;
293
+ const values = fields.slice(0, FIELDS).map(([key, value]) => ({ key, ...valueWords(value) }));
294
+ const lines = values.map(({ key, text }) => `• *${escape(key.replaceAll("_", " "))}*: ${text}`);
295
+ const more = fields.length > FIELDS ? [SAYS.approvalMore(fields.length - FIELDS)] : [];
296
+ const shown = cutEscaped([...lines, ...more].join("\n"), DETAILS_CHARS);
297
+ return { text: shown.text, cut: shown.cut || more.length > 0 || values.some(({ cut }) => cut) };
159
298
  }
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. */
299
+ /** 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
300
  export function askLayout(asked) {
162
301
  const { run, tool, card, input } = asked;
163
302
  const who = whoOf(asked.user);
@@ -171,15 +310,20 @@ export function askLayout(asked) {
171
310
  ];
172
311
  const about = card === undefined ? `run ${run}` : cardLine(card, style);
173
312
  const head = headline("waiting", SAYS.approvalTitle, about);
174
- const said = greeted(who, SAYS.approval(toolWords(tool)));
175
- const cut = input?.cut === true
313
+ const { doing, system } = toolWords(tool);
314
+ const details = detailsOf(input);
315
+ const removes = REMOVES.test(tool) ? [SAYS.approvalRemoves] : [];
316
+ const said = [
317
+ greeted(who, SAYS.approval(doing, system)),
318
+ SAYS.approvalWhy(asked.policy),
319
+ ...removes,
320
+ ].join("\n");
321
+ const listed = details === undefined ? undefined : `${SAYS.approvalDetails}\n${details.text}`;
322
+ const cut = details?.cut === true
176
323
  ? ` ${SAYS.approvalCut(page === undefined ? "Needs a person" : link(page, "Needs a person"))}`
177
324
  : "";
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(" · ");
325
+ const next = `*${SAYS.next}* ${SAYS.approvalNext(details !== undefined)}${cut}`;
326
+ const small = SAYS.approvalTool(escape(tool), run);
183
327
  const press = (action) => ({
184
328
  type: "button",
185
329
  action_id: `edgar_${action}`,
@@ -188,11 +332,14 @@ export function askLayout(asked) {
188
332
  ...(action === "approve" ? { style: "primary" } : {}),
189
333
  });
190
334
  return {
191
- text: [head, said, next, linksOf(targets), small].filter((line) => line !== "").join("\n"),
335
+ text: [head, said, listed ?? "", next, linksOf(targets), small]
336
+ .filter((line) => line !== "")
337
+ .join("\n"),
192
338
  blocks: [
193
339
  section(head),
194
- section(`${said}\n${next}`),
195
- ...(input === undefined ? [] : [section(`\`\`\`${input.text}\`\`\``)]),
340
+ section(said),
341
+ ...(listed === undefined ? [] : [section(listed)]),
342
+ section(next),
196
343
  { type: "actions", elements: [press("approve"), press("deny"), ...buttonsOf(targets)] },
197
344
  context(small),
198
345
  ],
@@ -200,12 +347,12 @@ export function askLayout(asked) {
200
347
  }
201
348
  /** The most characters of a question that a model wrote, so the question and its words around it fit in one section. */
202
349
  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. */
350
+ /** 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. */
204
351
  export function questionLayout(asked) {
205
352
  const { run, card } = asked;
206
353
  const name = card === undefined ? `run ${run}` : escape(card.id ?? "this card");
207
354
  const head = headline("waiting", SAYS.questionTitle, card === undefined ? name : cardLine(card, style));
208
- const said = greeted(whoOf(asked.user), SAYS.question(name));
355
+ const said = greeted(tagsOf(asked.users), SAYS.question(name));
209
356
  const question = cutEscaped(escape(asked.question.trim()), QUESTION_CHARS).text;
210
357
  const next = `*${SAYS.next}* ${SAYS.questionNext}`;
211
358
  return {
@@ -215,10 +362,33 @@ export function questionLayout(asked) {
215
362
  }
216
363
  /** "ana", "ana and bo", "ana, bo, and cy". */
217
364
  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) {
365
+ /** The people a message tags as one phrase, or nobody. */
366
+ function tagsOf(users) {
367
+ return users.length === 0 ? undefined : names.format(users);
368
+ }
369
+ /** 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. */
370
+ export function askedAboveLayout(run, note) {
371
+ const { card, facts } = note;
372
+ const line = [
373
+ `${EMOJI.decision} ${SAYS.askedAbove}`,
374
+ ...(card?.service === undefined ? [] : [escape(card.service)]),
375
+ `Run ${run}`,
376
+ ...(facts.took === undefined ? [] : [facts.took]),
377
+ ...(facts.tokens === undefined ? [] : [`${facts.tokens} tokens`]),
378
+ ...(facts.cost === undefined ? [] : [facts.cost]),
379
+ ].join(" · ");
380
+ return { text: line, blocks: [context(line)] };
381
+ }
382
+ /** 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. */
383
+ const SUMMED = new Set([
384
+ "decision",
385
+ "done",
386
+ "handed",
387
+ "opened",
388
+ "waits",
389
+ ]);
390
+ /** 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. */
391
+ export function noteLayout(run, note, user, by, stopper, tagged = []) {
222
392
  if (note === undefined)
223
393
  return { text: SAYS.unread(run), blocks: [section(SAYS.unread(run))] };
224
394
  const { card, facts, what } = note;
@@ -244,24 +414,30 @@ export function noteLayout(run, note, user) {
244
414
  ? undefined
245
415
  : (facts.why ??
246
416
  (facts.failure === undefined
247
- ? undefined
417
+ ? SAYS.noReason
248
418
  : SAYS.detail(facts.stage, lead(facts.failure, 200).text)));
249
419
  const targets = [
250
420
  ...(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 })),
421
+ ...facts.pulls.slice(0, 3).map(({ url, label }, at) => ({
422
+ id: `pull_${String(at)}`,
423
+ label: SAYS.pull(label, facts.pulls.length > 1),
424
+ url,
425
+ })),
254
426
  ...(facts.page === undefined ? [] : [{ id: "run", label: SAYS.run, url: facts.page }]),
255
427
  ];
428
+ const asking = (what === "decision" || what === "handed") && tagged.length > 0;
256
429
  const said = [
257
- greeted(who, words.said(name, count)),
430
+ greeted(asking ? tagsOf(tagged) : who, what === "handed" && facts.handedTo !== undefined
431
+ ? SAYS.handedTo(name, escape(facts.handedTo))
432
+ : what === "stopped" && stopper !== undefined
433
+ ? SAYS.stoppedWork(name, stopper)
434
+ : words.said(name, count)),
258
435
  ...(facts.approvedBy === undefined
259
436
  ? []
260
437
  : [SAYS.approvedBy(escape(names.format(facts.approvedBy)))]),
261
438
  ...(facts.commit === undefined ? [] : [SAYS.commit(escape(facts.commit))]),
262
439
  ...(why === undefined ? [] : [why]),
263
440
  ...(summary === undefined ? [] : [linked(summary.text)]),
264
- ...(what === "opened" && facts.risk !== undefined ? [escape(facts.risk)] : []),
265
441
  ...(summary?.cut === true && targets.length > 0 ? [SAYS.more] : []),
266
442
  ].join(" ");
267
443
  const options = what === "decision"
@@ -270,38 +446,98 @@ export function noteLayout(run, note, user) {
270
446
  .map((option, at) => `${String(at + 1)}. ${linked(lead(option, 300).text)}`)
271
447
  : [];
272
448
  const told = what === "failed" && facts.next !== undefined
273
- ? SAYS.replay(facts.next, run)
449
+ ? SAYS.replay(facts.next)
274
450
  : words.next?.(run, what === "decision" ? options.length : facts.pulls.length);
275
451
  const next = told === undefined ? undefined : `*${SAYS.next}* ${told}`;
276
452
  const head = headline(what, words.title, card === undefined ? name : cardLine(card, style));
277
453
  const detail = what === "failed" && facts.failure !== undefined && facts.why !== undefined
278
454
  ? [SAYS.detail(facts.stage, lead(facts.failure, 300).text)]
279
455
  : [];
280
- const small = [...detail, ...(targets.length === 0 ? [SAYS.reach(run)] : [])].join(" · ");
456
+ const small = detail.join(" · ");
281
457
  const used = [
282
- `Run ${run}`,
458
+ ...(by === undefined ? [] : [by]),
283
459
  ...(facts.took === undefined ? [] : [facts.took]),
284
460
  ...(facts.tokens === undefined ? [] : [`${facts.tokens} tokens`]),
285
461
  ...(facts.cost === undefined ? [] : [facts.cost]),
462
+ ...(what === "stopped" && stopper !== undefined ? [SAYS.stopper(stopper)] : []),
286
463
  ].join(" · ");
287
- const body = [said, ...options, ...(next === undefined ? [] : [next])];
288
- const buttons = buttonsOf(targets);
464
+ const pulls = what === "opened"
465
+ ? facts.pulls
466
+ .filter((pull) => pull.referenced !== true)
467
+ .map(({ url, label }) => `• ${link(url, label)}`)
468
+ : [];
469
+ const risk = what === "opened" && facts.risk !== undefined ? SAYS.risk(escape(facts.risk)) : "";
470
+ const body = [said, ...options, ...pulls, ...(next === undefined ? [] : [next])];
471
+ const shown = pulls.length === 0 ? targets : targets.filter(({ id }) => !id.startsWith("pull_"));
472
+ const again = what === "failed" || what === "stopped"
473
+ ? [
474
+ {
475
+ type: "button",
476
+ action_id: "edgar_replay",
477
+ text: { type: "plain_text", text: SAYS.tryAgain },
478
+ value: run,
479
+ style: "primary",
480
+ },
481
+ ]
482
+ : [];
483
+ const buttons = [...again, ...buttonsOf(targets)];
289
484
  return {
290
- text: [head, ...body, linksOf(targets), small, used].filter((line) => line !== "").join("\n"),
485
+ text: [head, ...body, risk, linksOf(shown), small, used]
486
+ .filter((line) => line !== "")
487
+ .join("\n"),
291
488
  blocks: [
292
489
  section(head),
293
490
  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
- ]),
491
+ ...(risk === "" ? [] : [section(risk)]),
492
+ ...(used === "" ? [] : [context(used)]),
303
493
  ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
304
494
  ...(small === "" ? [] : [context(small)]),
305
495
  ],
306
496
  };
307
497
  }
498
+ /** 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. */
499
+ export function behalfLine({ by, paid, paid_with }) {
500
+ if (paid === undefined || paid_with === undefined)
501
+ return by === undefined ? undefined : SAYS.behalf(by);
502
+ if (by === undefined)
503
+ return SAYS.paidOnly(paid, paid_with);
504
+ return by === paid
505
+ ? SAYS.behalfOwn(by, paid_with)
506
+ : `${SAYS.behalf(by)} · ${SAYS.paid(paid, paid_with)}`;
507
+ }
508
+ function isStatus(word) {
509
+ return Object.hasOwn(STATUS, word);
510
+ }
511
+ /** 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. */
512
+ export function rootLayout(card, view) {
513
+ const status = view.status !== undefined && isStatus(view.status) ? view.status : undefined;
514
+ const title = card.id === undefined
515
+ ? link(card.url, card.title)
516
+ : `${link(card.url, card.id)} ${escape(card.title)}`;
517
+ const head = status === undefined ? title : headline(status, STATUS[status], title);
518
+ const behalf = behalfLine(view);
519
+ const about = [
520
+ ...(card.service === undefined ? [] : [escape(card.service)]),
521
+ ...(behalf === undefined ? [] : [behalf]),
522
+ ...(view.holder === undefined ? [] : [SAYS.holder(view.holder)]),
523
+ ].join(" · ");
524
+ const ask = view.ask === undefined ? "" : cutEscaped(escape(view.ask), 600).text;
525
+ const targets = [
526
+ { id: "card", label: SAYS.card, url: card.url },
527
+ ...(view.pulls ?? []).slice(0, 3).map(({ url, label }, at, all) => ({
528
+ id: `pull_${String(at)}`,
529
+ label: SAYS.pull(label, all.length > 1),
530
+ url,
531
+ })),
532
+ ];
533
+ const buttons = buttonsOf(targets);
534
+ return {
535
+ text: [head, about, ask].filter((line) => line !== "").join("\n"),
536
+ blocks: [
537
+ section(head),
538
+ ...(about === "" ? [] : [context(about)]),
539
+ ...(ask === "" ? [] : [section(ask)]),
540
+ ...(buttons.length === 0 ? [] : [{ type: "actions", elements: buttons }]),
541
+ ],
542
+ };
543
+ }
@@ -6,20 +6,22 @@ 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
+ /** The messages of the thread, or of the channel's newest `HISTORY_PAGE` messages, each with its metadata. */
18
18
  export declare function listed(ctx: SlackCtx, channel: string, thread: string | undefined): Promise<Result<readonly Message[], Failure>>;
19
19
  /** The newest of `all`, by its timestamp, whose metadata is `kind` and passes `match`. */
20
20
  export declare function newestMarked(all: readonly Message[], kind: string, match?: (payload: Readonly<Record<string, unknown>>) => boolean): Message | undefined;
21
21
  /** The newest message, by its timestamp, in the thread or in the channel's recent history, whose metadata is `kind` and passes `match`. */
22
22
  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>>;
23
+ /** 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. */
24
+ export declare function findInChannel(ctx: SlackCtx, channel: string, kind: string, match: (payload: Readonly<Record<string, unknown>>) => boolean): Promise<Result<Message | undefined, Failure>>;
23
25
  /** 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
26
  export declare function waitingRelays(all: readonly Message[], now?: number): readonly Message[];
25
27
  /** 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 +34,16 @@ export declare function dmChannel(ctx: SlackCtx, to: {
32
34
  } | {
33
35
  readonly email: string;
34
36
  }): Promise<Result<string, Failure>>;
37
+ /** 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. */
38
+ export declare const REACTION: {
39
+ readonly seen: "eyes";
40
+ readonly done: "white_check_mark";
41
+ readonly failed: "x";
42
+ };
43
+ /** 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. */
44
+ export declare function react(ctx: SlackCtx, channel: string, ts: string, name: string, off?: boolean): Promise<void>;
45
+ /** Swaps the `seen` reaction on the message at `ts` for `done` when EDGAR answered or acted on it, else for `failed`. */
46
+ export declare function reacted(ctx: SlackCtx, channel: string, ts: string, worked: boolean): Promise<void>;
35
47
  /** The session status is a hint to the person; a failed status call is logged and never fails the delivery. */
36
48
  export declare function status(ctx: SlackCtx, origin: Origin, value: "processing" | "suspended" | "active" | "closed", title?: string): Promise<void>;
37
49
  /** 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. */
@@ -28,10 +28,13 @@ export async function post(ctx, channel, thread, text, extra = {}) {
28
28
  export async function update(ctx, channel, ts, text, extra = {}) {
29
29
  return await written(ctx, "chat.update", { channel, ts, text, ...extra });
30
30
  }
31
- /** The messages of the thread, or of the channel's recent history, each with its metadata. */
31
+ /** The most messages of a channel's history that `findInChannel` reads, newest first, and how many each page of a channel's history holds; Slack advises at most 200 a page. */
32
+ const HISTORY_MESSAGES = 1000;
33
+ const HISTORY_PAGE = 200;
34
+ /** The messages of the thread, or of the channel's newest `HISTORY_PAGE` messages, each with its metadata. */
32
35
  export async function listed(ctx, channel, thread) {
33
36
  const all = thread === undefined
34
- ? await slack(ctx, "conversations.history", { channel, limit: 100, include_all_metadata: true }, messages)
37
+ ? await slack(ctx, "conversations.history", { channel, limit: HISTORY_PAGE, include_all_metadata: true }, messages)
35
38
  : await slack(ctx, "conversations.replies", { channel, ts: thread, limit: 200, include_all_metadata: true }, messages);
36
39
  return all.ok ? ok(all.value.messages) : all;
37
40
  }
@@ -46,6 +49,24 @@ export async function findMarked(ctx, channel, thread, kind, match) {
46
49
  const all = await listed(ctx, channel, thread);
47
50
  return all.ok ? ok(newestMarked(all.value, kind, match)) : all;
48
51
  }
52
+ /** 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. */
53
+ export async function findInChannel(ctx, channel, kind, match) {
54
+ let cursor;
55
+ for (let seen = 0; seen < HISTORY_MESSAGES;) {
56
+ const args = { channel, limit: HISTORY_PAGE, include_all_metadata: true, cursor };
57
+ const page = await slack(ctx, "conversations.history", args, messages);
58
+ if (!page.ok)
59
+ return page;
60
+ const found = newestMarked(page.value.messages, kind, match);
61
+ if (found !== undefined)
62
+ return ok(found);
63
+ seen += page.value.messages.length;
64
+ cursor = page.value.response_metadata?.next_cursor;
65
+ if (cursor === undefined || cursor === "" || page.value.messages.length === 0)
66
+ break;
67
+ }
68
+ return ok(undefined);
69
+ }
49
70
  /** How long a relayed reply waits for its answer before a new reply no longer counts as one more while EDGAR is busy: the built-in answer's two stages time out within it. */
50
71
  const WAIT_MINUTES = 30;
51
72
  /** 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`. */
@@ -102,6 +123,20 @@ export async function dmChannel(ctx, to) {
102
123
  const conversation = await slack(ctx, "conversations.open", { users: user }, opened);
103
124
  return conversation.ok ? ok(conversation.value.channel.id) : conversation;
104
125
  }
126
+ /** 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. */
127
+ export const REACTION = { seen: "eyes", done: "white_check_mark", failed: "x" };
128
+ /** 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. */
129
+ export async function react(ctx, channel, ts, name, off = false) {
130
+ const method = off ? "reactions.remove" : "reactions.add";
131
+ const set = await slack(ctx, method, { channel, timestamp: ts, name }, answer);
132
+ if (!set.ok)
133
+ ctx.log(`${method} ${name}: ${set.error.message} (${set.error.cause ?? "no cause"})`);
134
+ }
135
+ /** Swaps the `seen` reaction on the message at `ts` for `done` when EDGAR answered or acted on it, else for `failed`. */
136
+ export async function reacted(ctx, channel, ts, worked) {
137
+ await react(ctx, channel, ts, REACTION.seen, true);
138
+ await react(ctx, channel, ts, worked ? REACTION.done : REACTION.failed);
139
+ }
105
140
  /** The session status is a hint to the person; a failed status call is logged and never fails the delivery. */
106
141
  export async function status(ctx, origin, value, title) {
107
142
  const args = {