@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,18 +1,12 @@
1
1
  import { cardLine, defineEventHook, done, endNote, noteCard, notePull, ok, runCard, } from "@kana-ai/edgar-sdk";
2
2
  import { apiAccess } from "#api/client";
3
- import { askLayout, noteLayout, planLayout, questionLayout, stageLabel, style, } from "#outbound/layout";
4
- import { findMarked, listed, mark, newestMarked, post, status, threadStatus, update, waitingRelays, } from "#outbound/messages";
5
- import { cardThread, directOf, homeOf, mentioned, oneMore, openThread, rootOf, threadOf, } from "#outbound/places";
3
+ import { answerLayout, behalfLine, askLayout, askedAboveLayout, noteLayout, planLayout, questionLayout, stageStatus, style, } from "#outbound/layout";
4
+ import { findMarked, listed, mark, newestMarked, post, reacted, status, threadStatus, update, waitingRelays, } from "#outbound/messages";
5
+ import { cardThread, directOf, homeOf, joinedRoot, mentioned, oneMore, rootOf, stopperOf, taggedOf, threadOf, } from "#outbound/places";
6
6
  import { cutEscaped, escape } from "#outbound/tools";
7
- import { ANSWER, ANSWER_FLOWS, PLAN, REPLY, REVIEW_WAIT, SAYS, reviewedLabel, } from "#outbound/words";
8
- import { settingsOf } from "#schemas/config";
9
- import { answerOutcome, approvalRequested, failedOutcome, openedOutcome, outcomeRecord, planState, postOutcome, pullOutcome, questionOutcome, reviewOutcome, runRead, runTrigger, slackOrigin, waitingForSlot, } from "#schemas/events";
10
- /** The most characters of a call's input an approval question shows; a section's text holds 3,000. */
11
- const INPUT_CHARS = 2400;
12
- /** A call's input as the text of a code block: markup made plain, no two backticks side by side to end the block, and at most `INPUT_CHARS` characters, cut between two characters and never inside an entity. `cut` says that a part is left out. */
13
- function inputBlock(shown) {
14
- return cutEscaped(escape(shown).replace(/`(?=`)/g, "`​"), INPUT_CHARS);
15
- }
7
+ import { ACTED, ANSWER, ANSWER_FLOWS, REPLY, REVIEW_WAIT, SAYS, reviewedLabel, } from "#outbound/words";
8
+ import { settingsOf, userId } from "#schemas/config";
9
+ import { actorsOutcome, answerOutcome, approvalRequested, endActors, endPaid, failedOutcome, openedOutcome, outcomeRecord, outputOutcome, planState, postOutcome, pullOutcome, questionOutcome, reviewOutcome, runRead, runRequester, runTrigger, slackOrigin, waitingForSlot, } from "#schemas/events";
16
10
  /** The card events of a person who writes to EDGAR. */
17
11
  const written = new Set(["comment", "mention"]);
18
12
  /** `Began` of each run that has not ended. It is a cache and no more: the hook's process ends after `idle_seconds` with no work, so a run that is not here is read again from its first event. */
@@ -24,11 +18,33 @@ function beganFrom(payload) {
24
18
  return {
25
19
  card: noteCard(card),
26
20
  assignee: trigger?.assignee,
21
+ requester: trigger?.requested_by === undefined
22
+ ? undefined
23
+ : { name: trigger.requested_by, id: trigger.requested_by_id },
24
+ ask: trigger?.ask,
27
25
  quiet: part || written.has(card?.event ?? ""),
26
+ part,
28
27
  workflow: trigger?.workflow,
29
28
  relayed: slackOrigin.safeParse(trigger?.relayed).data,
29
+ requestedBy: requestedByOf(payload),
30
30
  };
31
31
  }
32
+ function requestedByOf(payload) {
33
+ const asked = runRequester.safeParse(payload).data;
34
+ if (asked?.requester !== undefined)
35
+ return asked.requester;
36
+ const id = asked?.requested_by_id;
37
+ if (id !== undefined && userId.safeParse(id).success)
38
+ return { slack: id };
39
+ return asked?.requested_by === undefined ? undefined : { name: asked.requested_by };
40
+ }
41
+ /** The people a question or a decision of the run tags: those of `named`, then the run's requester, then the card's assignee when `mentioned` finds their Slack user, so EDGAR's own tracker user is never written. */
42
+ async function whoCanAct(ctx, run, message, named, first, settings) {
43
+ const { assignee, requestedBy } = first;
44
+ const user = assignee === undefined ? undefined : await mentioned(ctx, run, message, assignee, settings);
45
+ const entries = requestedBy === undefined ? named : [...named, requestedBy];
46
+ return await taggedOf(ctx, run, message, entries, settings, user === undefined ? [] : [`<@${user}>`]);
47
+ }
32
48
  /** What the run of `event` began with: from the event when it is the `run_created`, else from memory, else from the run's first event, which `runs.read` gives. A run that does not read is one log line, and its messages name no card and are not quiet. */
33
49
  async function beganOf(ctx, event) {
34
50
  const known = event.kind === "run_created" ? beganFrom(event.payload) : began.get(event.run);
@@ -46,16 +62,22 @@ async function beganOf(ctx, event) {
46
62
  return {
47
63
  card: undefined,
48
64
  assignee: undefined,
65
+ requester: undefined,
66
+ ask: undefined,
49
67
  quiet: false,
68
+ part: false,
50
69
  workflow: undefined,
51
70
  relayed: undefined,
71
+ requestedBy: undefined,
52
72
  };
53
73
  }
54
74
  const found = beganFrom(first.payload);
55
75
  began.set(event.run, found);
56
76
  return found;
57
77
  }
58
- /** Writes the run's plan message in the card's thread after `change`, and answers the plan. With `first`, a run that has no plan message gets one, whose first line links the card that the run began with; without it, such a run gets none and the answer is `undefined`, so the end of a run that showed no plan posts no empty one. */
78
+ /** The plan of each run whose card's thread does not list it yet: the thread and its status message open at the run's second stage, or at the first one that asks a person, so a run that ends after one stage with nothing to tell leaves no line. A cache and no more: after a restart, the plan starts at the run's next stage. */
79
+ const held = new Map();
80
+ /** Writes the card's one status message in its thread after `change`, and answers the plan. The message is the newest plan of the thread, of whichever run wrote it: a run changes it while the message is its own, and with `first` a run takes it over once the run that wrote it is over, so each run of a card updates the same message in place and the thread never gets a second one; a run that starts while another run of the card still works shows in it when that run ends. With `first`, a thread with no status message gets one, whose first line links the card that the run began with; without it, a run whose message is not its own changes nothing and the answer is `undefined`, so the end of a run that showed no plan posts no empty one. */
59
81
  async function replan(ctx, event, place, settings, change, first) {
60
82
  const all = await listed(ctx, place.channel, place.thread);
61
83
  return all.ok ? await replanIn(ctx, event, place, settings, change, all.value, first) : all;
@@ -63,13 +85,18 @@ async function replan(ctx, event, place, settings, change, first) {
63
85
  /** `replan` on the messages `all` of the thread, read once by the caller. */
64
86
  async function replanIn(ctx, event, place, settings, change, all, first) {
65
87
  const { channel, thread } = place;
66
- const found = newestMarked(all, "edgar_plan", (p) => p["run"] === event.run);
88
+ const found = newestMarked(all, "edgar_plan");
67
89
  const ts = found?.ts;
68
- if (ts === undefined && first === undefined)
90
+ const payload = found?.metadata?.event_payload;
91
+ const own = payload?.["run"] === event.run;
92
+ const free = found === undefined || planState.safeParse(payload).data?.ended !== undefined;
93
+ if (!own && (first === undefined || !free))
69
94
  return ok(undefined);
70
- const kept = planState.safeParse(found?.metadata?.event_payload);
95
+ const kept = planState.safeParse(own ? payload : undefined);
71
96
  const card = first?.card === undefined ? {} : { card: cardLine(first.card, style) };
72
- const plan = change(kept.success ? kept.data : { run: event.run, tasks: [], pulls: [], ...card });
97
+ const fresh = held.get(event.run) ?? { run: event.run, tasks: [], pulls: [], ...card };
98
+ held.delete(event.run);
99
+ const plan = change(kept.success ? kept.data : fresh);
73
100
  const { text, blocks } = planLayout(plan, settings);
74
101
  const fields = { blocks, metadata: mark("edgar_plan", plan) };
75
102
  const sent = ts === undefined
@@ -115,7 +142,7 @@ async function ask(ctx, event, place, settings, first) {
115
142
  const asked = approvalRequested.safeParse(event.payload);
116
143
  if (!asked.success)
117
144
  return ok(undefined);
118
- const { operation_id, tool, input, assignee } = asked.data;
145
+ const { operation_id, tool, policy, input, assignee } = asked.data;
119
146
  const { channel, thread } = place;
120
147
  const same = (p) => p["operation"] === operation_id;
121
148
  const found = await findMarked(ctx, channel, thread, "edgar_approval", same);
@@ -130,9 +157,8 @@ async function ask(ctx, event, place, settings, first) {
130
157
  run: event.run,
131
158
  tool,
132
159
  operation: operation_id,
133
- input: input === undefined || input === null
134
- ? undefined
135
- : inputBlock(JSON.stringify(input, null, 2)),
160
+ policy,
161
+ input,
136
162
  card: first.card,
137
163
  user,
138
164
  consoleUrl: settings.console_url,
@@ -147,7 +173,7 @@ async function ask(ctx, event, place, settings, first) {
147
173
  await status(ctx, place.origin, "suspended");
148
174
  return ok(undefined);
149
175
  }
150
- /** Posts once in the card's thread the question that the done stage `stage` left open, to the card's assignee. EDGAR goes on with its work, and a reply in the thread goes on the card as the person's comment, which starts the run that answers it. */
176
+ /** Posts once in the card's thread the question that the done stage `stage` left open, to the people of `whoCanAct`. EDGAR goes on with its work, and a reply in the thread goes on the card as the person's comment, which starts the run that answers it. */
151
177
  async function question(ctx, event, stage, place, settings, first) {
152
178
  const asked = questionOutcome.safeParse(event.payload).data?.outcome.output.question;
153
179
  if (asked === undefined)
@@ -160,26 +186,28 @@ async function question(ctx, event, stage, place, settings, first) {
160
186
  return found;
161
187
  if (found.value !== undefined)
162
188
  return ok(undefined);
163
- const { assignee } = first;
164
- const user = assignee === undefined
165
- ? undefined
166
- : await mentioned(ctx, run, "the question", assignee, settings);
167
- const { text, blocks } = questionLayout({
168
- run,
169
- card: first.card,
170
- user,
171
- question: asked,
172
- });
189
+ const named = actorsOutcome.safeParse(event.payload).data?.outcome.output.who_can_act ?? [];
190
+ const users = await whoCanAct(ctx, run, "the question", named, first, settings);
191
+ const { text, blocks } = questionLayout({ run, card: first.card, users, question: asked });
173
192
  const sent = await post(ctx, channel, thread, text, {
174
193
  blocks,
175
194
  metadata: mark("edgar_question", { run, stage }),
176
195
  });
177
196
  return sent.ok ? ok(undefined) : sent;
178
197
  }
198
+ /** How long after it happened an event counts as late: a backlog of events, or a restart, hands it long after the run moved on. A late event shows no progress and opens no card thread, so a run long over never posts a new message at the top of the channel. */
199
+ const LATE_MS = 15 * 60 * 1000;
200
+ /** Whether `event` reaches the hook `LATE_MS` or more after it happened. */
201
+ function late(event) {
202
+ return Date.now() - event.at >= LATE_MS;
203
+ }
204
+ /** The events that only show a run's progress, which a late one no longer has to show. */
205
+ const progressOnly = new Set(["run_created", "attempt_started", "waiting_for_slot"]);
179
206
  /** The kinds of end note that a person must see also when the run showed no plan. */
180
207
  const asks = new Set([
181
208
  "recovered",
182
209
  "decision",
210
+ "handed",
183
211
  "opened",
184
212
  "merged",
185
213
  "approved",
@@ -191,18 +219,21 @@ const asks = new Set([
191
219
  function markOf(note) {
192
220
  return note?.what === "opened" ? "edgar_ready" : "edgar_end";
193
221
  }
194
- /** Posts the note at `place` once: a note with the same mark for the run is not posted again. With `shown`, a note in a thread is also shown in the conversation of the thread, as Slack does for a reply that a person also sends to the channel. */
195
- async function noteAt(ctx, place, run, note, shown, kind) {
222
+ /** Posts the note at `place` once: a note with the same mark for the run is not posted again. A note in a thread stays in the thread: nothing is sent to the top of the conversation. With `above`, a thread that already holds a question of the run gets `above` in place of the note, so the question is not asked twice. */
223
+ async function noteAt(ctx, place, run, layout, kind, above) {
196
224
  const { channel, thread } = place;
197
- const found = await findMarked(ctx, channel, thread, kind, (p) => p["run"] === run);
198
- if (!found.ok)
199
- return found;
200
- if (found.value !== undefined)
225
+ const all = await listed(ctx, channel, thread);
226
+ if (!all.ok)
227
+ return all;
228
+ if (newestMarked(all.value, kind, (p) => p["run"] === run) !== undefined)
201
229
  return ok(undefined);
230
+ const asked = above !== undefined &&
231
+ thread !== undefined &&
232
+ newestMarked(all.value, "edgar_question", (p) => p["run"] === run) !== undefined;
233
+ const note = asked ? above : layout;
202
234
  const sent = await post(ctx, channel, thread, note.text, {
203
235
  blocks: note.blocks,
204
236
  metadata: mark(kind, { run }),
205
- ...(shown && thread !== undefined ? { reply_broadcast: true } : {}),
206
237
  });
207
238
  if (!sent.ok)
208
239
  return sent;
@@ -210,13 +241,70 @@ async function noteAt(ctx, place, run, note, shown, kind) {
210
241
  ctx.log(`run ${run}: ${what} went to ${sent.value.channel} at ${sent.value.ts}`);
211
242
  return ok(undefined);
212
243
  }
213
- /** Posts `note` once in the card's thread at `home` and in each `dm`: `found` is the card's thread at home when the run has one, and a note whose run is in no thread goes in the thread of its card. The note greets the card's assignee with a mention when `mentioned` finds their Slack user, and a note that asks that person for a decision also goes in the card's thread of their own DM; a DM that Slack refuses is one log line, and the other notes are still posted. The note of a pull request that is ready for people also goes in the card's thread in `channel`, where the channel shows it too. */
214
- async function tell(ctx, event, settings, home, found, note) {
244
+ /** Who asked for the work, as Slack writes them: a mention of the Slack user that opened the card, a mention of the user that `mentioned` finds for the name, else the name as text. None when the card names nobody. */
245
+ async function behalfOf(ctx, event, first, settings) {
246
+ const { requester } = first;
247
+ if (requester === undefined)
248
+ return undefined;
249
+ const fromSlack = slackOrigin.safeParse(event.origin).success;
250
+ if (fromSlack && userId.safeParse(requester.id).success)
251
+ return `<@${requester.id ?? ""}>`;
252
+ const user = await mentioned(ctx, event.run, "the card's first message", requester.name, settings);
253
+ return user === undefined ? escape(requester.name) : `<@${user}>`;
254
+ }
255
+ /** Whose own key or subscription the run of `event` ran on, as Slack writes them: a mention of the Slack id that the engine found in `[people]`, else of the user that `mentioned` finds for their email or name, else their name; and what it was, such as "Claude subscription". None when the run ran on EDGAR's own. */
256
+ async function paidOf(ctx, event, settings) {
257
+ const paid = endPaid.safeParse(event.payload).data?.end.paid_by;
258
+ if (paid === undefined)
259
+ return undefined;
260
+ const vendor = paid.provider === undefined
261
+ ? ""
262
+ : `${paid.provider.charAt(0).toUpperCase()}${paid.provider.slice(1)} `;
263
+ const what = `${vendor}${paid.credential === "oauth" ? "subscription" : "API key"}`;
264
+ if (userId.safeParse(paid.slack).success)
265
+ return { who: `<@${paid.slack ?? ""}>`, what };
266
+ for (const given of [paid.email, paid.name]) {
267
+ const user = given === undefined
268
+ ? undefined
269
+ : await mentioned(ctx, event.run, "the card's first message", given, settings);
270
+ if (user !== undefined)
271
+ return { who: `<@${user}>`, what };
272
+ }
273
+ return { who: escape(paid.name), what };
274
+ }
275
+ /** What the card's first message shows for the run of `event` at `status`: the card's ask, who asked for the work, the card's holder when Slack knows them, whose own key or subscription the run ran on, set again at each change so an earlier run's never stays, and the pull requests of `pulls` that the run opened. */
276
+ async function viewOf(ctx, event, first, settings, status, pulls = []) {
277
+ const own = pulls.flatMap(({ url, label, referenced }) => (referenced ? [] : [{ url, label }]));
278
+ const by = await behalfOf(ctx, event, first, settings);
279
+ const paid = await paidOf(ctx, event, settings);
280
+ const holder = first.assignee === undefined
281
+ ? undefined
282
+ : await mentioned(ctx, event.run, "the card's first message", first.assignee, settings);
283
+ return {
284
+ status,
285
+ ...(first.ask === undefined ? {} : { ask: first.ask }),
286
+ ...(by === undefined ? {} : { by }),
287
+ ...(holder === undefined ? {} : { holder: `<@${holder}>` }),
288
+ paid: paid?.who,
289
+ paid_with: paid?.what,
290
+ ...(own.length === 0 ? {} : { pulls: own }),
291
+ };
292
+ }
293
+ /** Shows `view` on the card's first message at `home`, for a card that did not come from Slack: there the first message is EDGAR's own, while a person wrote the first message of a Slack card. A first message that Slack does not change is one log line. */
294
+ async function restatus(ctx, event, home, card, view) {
295
+ if (home.origin !== undefined || home.direct || card === undefined)
296
+ return;
297
+ const changed = await rootOf(ctx, home.channel, card, event.run, view);
298
+ if (!changed.ok)
299
+ ctx.log(`run ${event.run}: the card's first message keeps its status (${changed.error.message})`);
300
+ }
301
+ /** Posts `note` once in the card's thread at `home` and in each `dm`: `found` is the card's thread at home when the run has one, and a note whose run is in no thread goes in the thread of its card. The note greets the card's assignee with a mention when `mentioned` finds their Slack user, and a note that asks that person for a decision also goes in the card's thread of their own DM; a DM that Slack refuses is one log line, and the other notes are still posted. The note of a pull request that is ready for people also goes in the card's thread in `channel`, as a reply there and nothing more. */
302
+ async function tell(ctx, event, settings, home, found, note, view, tagged = []) {
215
303
  const places = [];
216
304
  if (home !== undefined && !home.direct) {
217
305
  const under = found !== undefined || note?.card === undefined
218
306
  ? ok(found)
219
- : await rootOf(ctx, home.channel, note.card, event.run);
307
+ : await rootOf(ctx, home.channel, note.card, event.run, view);
220
308
  if (!under.ok)
221
309
  return under;
222
310
  places.push({ channel: home.channel, thread: under.value });
@@ -227,14 +315,14 @@ async function tell(ctx, event, settings, home, found, note) {
227
315
  return channel;
228
316
  const thread = note?.card === undefined
229
317
  ? ok(undefined)
230
- : await rootOf(ctx, channel.value, note.card, event.run);
318
+ : await rootOf(ctx, channel.value, note.card, event.run, view);
231
319
  if (!thread.ok)
232
320
  return thread;
233
321
  places.push({ channel: channel.value, thread: thread.value });
234
322
  }
235
323
  const shown = note?.what === "opened" ? settings.channel : undefined;
236
324
  if (shown !== undefined) {
237
- const team = await oneMore(ctx, shown, note?.card, event.run, places);
325
+ const team = await oneMore(ctx, shown, note?.card, event.run, places, view);
238
326
  if (!team.ok)
239
327
  return team;
240
328
  if (team.value !== undefined)
@@ -245,20 +333,41 @@ async function tell(ctx, event, settings, home, found, note) {
245
333
  : await mentioned(ctx, event.run, "the end note", note.assignee, settings);
246
334
  if (user !== undefined && note?.what === "decision") {
247
335
  const direct = await directOf(ctx, user);
248
- const own = direct.ok ? await oneMore(ctx, direct.value, note.card, event.run, places) : direct;
336
+ const own = direct.ok
337
+ ? await oneMore(ctx, direct.value, note.card, event.run, places, view)
338
+ : direct;
249
339
  if (!own.ok)
250
340
  ctx.log(`run ${event.run}: the decision note did not go to the DM of ${note.assignee ?? user}, because Slack refused it (${own.error.kind})`);
251
341
  else if (own.value !== undefined)
252
342
  places.push(own.value);
253
343
  }
254
- const layout = noteLayout(event.run, note, user);
344
+ const by = note?.facts.stoppedBy;
345
+ const stopper = by === undefined ? undefined : await stopperOf(ctx, event.run, by, settings);
346
+ const layout = noteLayout(event.run, note, user, behalfLine(view), stopper, tagged);
347
+ const asked = endActors.safeParse(event.payload).data?.end.question?.trim();
348
+ const above = note?.what === "decision" && asked !== undefined && note.facts.summary === asked
349
+ ? askedAboveLayout(event.run, note)
350
+ : undefined;
255
351
  for (const place of places) {
256
- const sent = await noteAt(ctx, place, event.run, layout, place.channel === shown, markOf(note));
352
+ const sent = await noteAt(ctx, place, event.run, layout, markOf(note), above);
257
353
  if (!sent.ok)
258
354
  return sent;
259
355
  }
260
356
  return ok(undefined);
261
357
  }
358
+ /** Whether another run, such as a step of this one, already asked `asked` in the card's thread `all` while the run of `event` worked, in its decision note or its question: a chain of runs asks a person one time. */
359
+ function askedInChain(all, event, asked) {
360
+ const since = endActors.safeParse(event.payload).data?.end.started;
361
+ if (asked === undefined || since === undefined)
362
+ return false;
363
+ const words = escape(asked.trim()).slice(0, 100);
364
+ return all.some((message) => {
365
+ const kind = message.metadata?.event_type;
366
+ const other = message.metadata?.event_payload["run"] !== event.run;
367
+ const asks = kind === "edgar_end" || kind === "edgar_question";
368
+ return (asks && other && Number(message.ts) * 1000 >= since && (message.text ?? "").includes(words));
369
+ });
370
+ }
262
371
  /** Posts once in the card's thread that EDGAR will post the result in the channel that a person asked for, when a done stage's output names one in `post_in`. The message's metadata `edgar_post_to` keeps the channel and the run that heard it, so the end of a later run that is done keeps the promise. */
263
372
  async function promise(ctx, event, at) {
264
373
  const channel = postOutcome.safeParse(event.payload).data?.outcome.output.post_in;
@@ -342,8 +451,8 @@ function readyNote(run, first, plan, settings) {
342
451
  }
343
452
  /** The most characters of an answer in a thread; Slack refuses a text over 40,000. */
344
453
  const ANSWER_CHARS = 39_000;
345
- /** Marks the oldest reply of `all` that waits for an answer as answered by `run`, unless `run` answered one already. A reply that is not marked is one log line: a later reply then counts as one more while EDGAR is busy, for a while. */
346
- async function closeRelay(ctx, at, run, all) {
454
+ /** Marks the oldest reply of `all` that waits for an answer as answered by `run`, unless `run` answered one already, and swaps the reaction on the person's message for the sign of `worked`. A reply that is not marked is one log line: a later reply then counts as one more while EDGAR is busy, for a while. */
455
+ async function closeRelay(ctx, at, run, all, worked) {
347
456
  if (newestMarked(all, "edgar_relay_done", (p) => p["run"] === run) !== undefined)
348
457
  return;
349
458
  const [oldest] = waitingRelays(all);
@@ -353,36 +462,97 @@ async function closeRelay(ctx, at, run, all) {
353
462
  const closed = await update(ctx, at.channel, oldest.ts, oldest.text ?? "", { metadata });
354
463
  if (!closed.ok)
355
464
  ctx.log(`run ${run}: the relayed reply stays open (${closed.error.message})`);
465
+ const asked = oldest.metadata?.event_payload["asked"];
466
+ if (typeof asked === "string")
467
+ await reacted(ctx, at.channel, asked, worked);
468
+ }
469
+ /** The words of `ACTED` for `stage`, if any. */
470
+ function actedOn(stage) {
471
+ return Object.hasOwn(ACTED, stage) ? ACTED[stage] : undefined;
472
+ }
473
+ /** Posts `text` once in the thread `at` for the stage `stage` of `run` at `when`, to the person of the oldest reply that waits there. The reply stays open: only an answer or the run's end closes it. */
474
+ async function confirm(ctx, run, stage, when, at, text) {
475
+ const all = await listed(ctx, at.channel, at.thread);
476
+ if (!all.ok)
477
+ return all;
478
+ const same = (p) => p["run"] === run && p["stage"] === stage && p["when"] === when;
479
+ if (newestMarked(all.value, "edgar_said", same) !== undefined)
480
+ return ok(undefined);
481
+ const user = waitingRelays(all.value)[0]?.metadata?.event_payload["user"];
482
+ const said = ANSWER.said(typeof user === "string" ? user : undefined, text);
483
+ const sent = await post(ctx, at.channel, at.thread, said, {
484
+ metadata: mark("edgar_said", { run, stage, when }),
485
+ });
486
+ return sent.ok ? ok(undefined) : sent;
487
+ }
488
+ /** A stage of a run that a person's words in Slack started begins: the thread says what EDGAR starts for them, when `ACTED` has words for the stage, and the moving line under the thread names the stage, so a reply that takes a while is never silence. */
489
+ async function relayedStart(ctx, event, at, settings) {
490
+ const { stage } = event;
491
+ if (stage === null)
492
+ return ok(undefined);
493
+ const words = actedOn(stage)?.started;
494
+ if (words !== undefined) {
495
+ const said = await confirm(ctx, event.run, stage, "started", at, words);
496
+ if (!said.ok)
497
+ return said;
498
+ }
499
+ await threadStatus(ctx, at.channel, at.thread, stageStatus(stage, settings));
500
+ return ok(undefined);
356
501
  }
357
502
  /** Posts one message of `run` in the thread `at` that a person wrote in, once for the run, with the words of `said` for the person of the oldest reply that waits there, and marks that reply answered. */
358
- async function answerIn(ctx, run, at, said) {
503
+ async function answerIn(ctx, run, at, say) {
359
504
  const all = await listed(ctx, at.channel, at.thread);
360
505
  if (!all.ok)
361
506
  return all;
362
507
  if (newestMarked(all.value, "edgar_answer", (p) => p["run"] === run) !== undefined)
363
508
  return ok(undefined);
364
509
  const user = waitingRelays(all.value)[0]?.metadata?.event_payload["user"];
365
- const text = said(typeof user === "string" ? user : undefined);
510
+ const { text, blocks } = say(typeof user === "string" ? user : undefined);
366
511
  const sent = await post(ctx, at.channel, at.thread, text, {
512
+ ...(blocks.length === 0 ? {} : { blocks }),
367
513
  metadata: mark("edgar_answer", { run }),
368
514
  });
369
515
  if (!sent.ok)
370
516
  return sent;
371
- await closeRelay(ctx, at, run, all.value);
517
+ await closeRelay(ctx, at, run, all.value, true);
372
518
  return ok(undefined);
373
519
  }
374
- /** A done stage of a run that a person's words in Slack started: its answer goes in their thread, and a card that a chat opened for work is named there, so they know where to follow it. */
375
- async function relayedOutcome(ctx, event, first, at) {
376
- const text = answerOutcome.safeParse(event.payload).data?.outcome.output.text;
377
- if (text !== undefined) {
378
- const shown = cutEscaped(escape(text), ANSWER_CHARS).text;
379
- return await answerIn(ctx, event.run, at, (user) => ANSWER.said(user, shown));
520
+ /** A done stage of a run that a person's words in Slack started: what it did for them, when `ACTED` has words for it, with the text of its output's `says` field; its answer; and a card that a chat opened for work, so they know where to follow it, each go in their thread. */
521
+ async function relayedOutcome(ctx, event, first, at, settings) {
522
+ const { stage } = event;
523
+ const words = stage === null ? undefined : actedOn(stage);
524
+ const word = outcomeRecord.safeParse(event.payload).data?.outcome.outcome;
525
+ if (stage !== null && words?.done !== undefined && word === "done") {
526
+ const output = outputOutcome.safeParse(event.payload).data?.outcome.output;
527
+ const extra = words.says === undefined ? undefined : output?.[words.says];
528
+ const text = typeof extra === "string" && extra.trim() !== ""
529
+ ? `${words.done}\n${cutEscaped(escape(extra.trim()), ANSWER_CHARS).text}`
530
+ : words.done;
531
+ const said = await confirm(ctx, event.run, stage, "done", at, text);
532
+ if (!said.ok)
533
+ return said;
534
+ }
535
+ const answer = answerOutcome.safeParse(event.payload).data?.outcome.output;
536
+ if (answer !== undefined) {
537
+ const base = settings.console_url?.replace(/\/$/, "");
538
+ const page = base === undefined ? undefined : `${base}/runs/${encodeURIComponent(event.run)}`;
539
+ const answered = {
540
+ text: answer.text,
541
+ sources: answer.sources ?? [],
542
+ confident: answer.confident,
543
+ card: first.card,
544
+ page,
545
+ };
546
+ return await answerIn(ctx, event.run, at, (user) => answerLayout({ ...answered, user }, ANSWER_CHARS));
380
547
  }
381
548
  const card = first.card === undefined ? openedOutcome.safeParse(event.payload).data : undefined;
382
549
  const id = card?.outcome.output.id;
383
550
  if (id === undefined)
384
551
  return ok(undefined);
385
- return await answerIn(ctx, event.run, at, () => ANSWER.opened(escape(id)));
552
+ return await answerIn(ctx, event.run, at, () => ({
553
+ text: ANSWER.opened(escape(id)),
554
+ blocks: [],
555
+ }));
386
556
  }
387
557
  /** The end of a run that a person's words in Slack started: the reply it answered is closed and the thread's status ends. An answer run that did not end done says so in one plain line there, unless it already answered, and the answer is `true`, as nothing else needs saying. */
388
558
  async function relayedEnd(ctx, event, first, at, word) {
@@ -399,11 +569,11 @@ async function relayedEnd(ctx, event, first, at, word) {
399
569
  if (!sent.ok)
400
570
  return sent;
401
571
  }
402
- await closeRelay(ctx, at, event.run, all.value);
572
+ await closeRelay(ctx, at, event.run, all.value, word === "done" && !failed);
403
573
  await threadStatus(ctx, at.channel, at.thread, "");
404
574
  return ok(failed);
405
575
  }
406
- /** The end of a run: the plan marked over when the run showed one, the session status of a Slack thread, and the end note of `noteLayout` at each place of `tell`. A run that already said that its pull request is ready for people, when its review wait started, does not say it again. A run with no card that ends done sends no note, except the first run of a schedule that works again; a done run that showed no plan sends none either, except a note that asks for a decision, is about a pull request or says what the run waits on. A done run with no summary sends none: the plan's first line already says that it is done, and a note with nothing to tell is noise. A quiet run that ends done sends none and removes the thread status that its reply set. A note whose run is in no thread goes in the thread of its card. A failed run of a schedule whose run just before it failed the same way sends nothing. An event whose outcome `endNote` cannot read still ends the plan and the session, and its note says only that the run is over. */
576
+ /** The end of a run: the plan marked over when the run showed one, the session status of a Slack thread, and the end note of `noteLayout` at each place of `tell`. A run that already said that its pull request is ready for people, when its review wait started, does not say it again. A run with no card that ends done sends no note, except the first run of a schedule that works again; a done run that showed no plan sends none either, except a note that asks for a decision, is about a pull request or says what the run waits on. A done run with no summary sends none: the plan's first line already says that it is done, and a note with nothing to tell is noise. A decision that a step of the run, or another run, already asked in the card's thread while the run worked is not asked again. A quiet run that ends done, and a run that a stage of another run started whatever its end except a decision, marks its own plan over and removes the moving line under the card's thread, but sends no note, sets no session status and keeps no promise, since the top run of the chain says the end; one that a person's words in Slack started ends with `relayedEnd` alone. A note whose run is in no thread goes in the thread of its card. A failed run of a schedule whose run just before it failed the same way sends nothing. An event whose outcome `endNote` cannot read still ends the plan and the session, and its note says only that the run is over. A run that a person stopped and that showed no status message of its own ends with no note: the person knows, and a stop of many such runs at once must not fill the channel. A late note goes only in a thread that the card already has. */
407
577
  async function ended(ctx, event, settings, first) {
408
578
  const note = endNote(event, style, settings.console_url);
409
579
  if (note === undefined)
@@ -416,18 +586,16 @@ async function ended(ctx, event, settings, first) {
416
586
  if (!said.ok || said.value)
417
587
  return said.ok ? ok(undefined) : said;
418
588
  }
419
- if (first.quiet && note?.what === "done") {
420
- const origin = slackOrigin.safeParse(event.origin).data;
421
- if (origin !== undefined)
422
- await threadStatus(ctx, origin.channel, origin.thread, "");
589
+ const quiet = first.part ? note?.what !== "decision" : first.quiet && note?.what === "done";
590
+ if (quiet && first.relayed !== undefined)
423
591
  return ok(undefined);
424
- }
425
592
  const home = await homeOf(ctx, event, settings);
426
593
  if (!home.ok)
427
594
  return home;
428
595
  let planned = false;
429
596
  let found;
430
597
  let promised;
598
+ let chained = false;
431
599
  if (home.value !== undefined) {
432
600
  const thread = await threadOf(ctx, event, home.value);
433
601
  if (!thread.ok)
@@ -438,36 +606,59 @@ async function ended(ctx, event, settings, first) {
438
606
  const all = await listed(ctx, at.channel, found);
439
607
  if (!all.ok)
440
608
  return all;
441
- const over = (plan) => ({ ...plan, ended: word });
609
+ const over = (plan) => ({ ...plan, ended: note?.what ?? word });
442
610
  const changed = await replanIn(ctx, event, at, settings, over, all.value);
443
611
  if (!changed.ok)
444
612
  return changed;
445
613
  planned = changed.value !== undefined;
446
614
  await closeQuestions(ctx, at, event.run, note?.what === "stopped", all.value);
447
- const marker = word === "done"
615
+ const marker = word === "done" && !quiet
448
616
  ? newestMarked(all.value, "edgar_post_to", (p) => p["run"] !== event.run)
449
617
  : undefined;
450
618
  if (marker !== undefined)
451
619
  promised = { at, marker };
620
+ if (quiet)
621
+ await threadStatus(ctx, at.channel, found, "");
622
+ chained = note?.what === "decision" && askedInChain(all.value, event, note.facts.summary);
452
623
  }
453
- if (home.value.origin !== undefined) {
624
+ if (home.value.origin !== undefined && !quiet) {
454
625
  const close = settings.close_on_done && word === "done";
455
626
  await status(ctx, home.value.origin, close ? "closed" : "active");
456
627
  }
457
628
  }
629
+ if (quiet)
630
+ return ok(undefined);
458
631
  if (promised !== undefined) {
459
632
  const layout = noteLayout(event.run, note, undefined);
460
633
  const kept = await keepPromise(ctx, promised.at, promised.marker, layout);
461
634
  if (!kept.ok)
462
635
  return kept;
463
636
  }
637
+ if (note?.what === "stopped" && !planned)
638
+ return ok(undefined);
639
+ const view = note === undefined
640
+ ? {}
641
+ : await viewOf(ctx, event, first, settings, note.what, note.facts.pulls);
642
+ if (home.value !== undefined && found !== undefined && note !== undefined)
643
+ await restatus(ctx, event, home.value, first.card, view);
644
+ if (chained)
645
+ return ok(undefined);
464
646
  const told = note !== undefined && asks.has(note.what);
465
647
  const bare = note?.what === "done" && note.facts.summary === undefined;
466
648
  if (word === "done" && !told && (!planned || bare))
467
649
  return ok(undefined);
468
- return await tell(ctx, event, settings, home.value, found, note);
650
+ if (found === undefined && late(event)) {
651
+ ctx.log(`run ${event.run}: the end note came late and the card has no thread here, so it opens none`);
652
+ return ok(undefined);
653
+ }
654
+ const asking = note?.what === "decision" || note?.what === "handed";
655
+ const named = endActors.safeParse(event.payload).data?.end.who_can_act ?? [];
656
+ const tagged = asking
657
+ ? await whoCanAct(ctx, event.run, "the end note", named, first, settings)
658
+ : [];
659
+ return await tell(ctx, event, settings, home.value, found, note, view, tagged);
469
660
  }
470
- /** What each event the hook takes before the end does in the card's thread; a run with no card has no thread and no plan. The start of a run lists it on the card's first message, and its plan is posted when its first stage starts, so a run that ends with no stage leaves no line. A stage is in the plan from the moment it starts, so a stage that the run skips or never reaches is never shown. When the stage `REVIEW_WAIT` starts to wait, the note that the pull request is ready for people is posted, at the moment they can act and not at the end of the run. A done stage whose output has a `question` posts it once, as `question` says. A stage that starts also sets the moving line under the thread to its phrase of `[extensions.slack.status]`, else to its label, which Slack removes at EDGAR's next message there. */
661
+ /** What each event the hook takes before the end does in the card's thread; a run with no card has no thread and no plan. The start of a run posts nothing in a channel: a run joins the card's thread from its first stage when the card already has one; else the thread and its one status message open when the run starts its second stage, or when a person must read something, as `opening` says, so a run that ends after one stage with nothing to tell leaves no line. A run of the card that starts while another still works takes the status message over once that run is over. A stage is in the plan from the moment it starts, so a stage that the run skips or never reaches is never shown. When the stage `REVIEW_WAIT` of a top run starts to wait, the note that the pull request is ready for people is posted, at the moment they can act and not at the end of the run. A done stage whose output has a `question` posts it once, as `question` says. A stage that starts also sets the moving line under the thread to its phrase of `stageStatus`, which Slack removes at EDGAR's next message there. A quiet run shows its progress the same way, so the work that a person's reply or another run starts is never silence. */
471
662
  const steps = {
472
663
  run_created: async (event, ctx, place) => {
473
664
  if (place.origin !== undefined)
@@ -482,10 +673,10 @@ const steps = {
482
673
  const at = { ...place, thread };
483
674
  const working = (p) => withTask(p, stage, "working");
484
675
  const changed = await replan(ctx, event, at, settings, working, first);
485
- if (place.origin !== undefined)
676
+ if (place.origin !== undefined && !first.quiet)
486
677
  await status(ctx, place.origin, "processing");
487
678
  if (changed.ok)
488
- await threadStatus(ctx, place.channel, thread, settings.status[stage] ?? PLAN.status(stageLabel(stage)));
679
+ await threadStatus(ctx, place.channel, thread, stageStatus(stage, settings));
489
680
  return changed;
490
681
  },
491
682
  attempt_outcome: async (event, ctx, place, settings, first) => {
@@ -506,12 +697,15 @@ const steps = {
506
697
  if (!promised.ok)
507
698
  return promised;
508
699
  const plan = changed.value;
509
- if (stage !== REVIEW_WAIT ||
700
+ if (first.part ||
701
+ stage !== REVIEW_WAIT ||
510
702
  word !== "waiting" ||
511
703
  plan === undefined ||
512
704
  plan.pulls.length === 0)
513
705
  return changed;
514
- return await tell(ctx, event, settings, place, thread, readyNote(event.run, first, plan, settings));
706
+ const view = await viewOf(ctx, event, first, settings, "opened", plan.pulls);
707
+ await restatus(ctx, event, place, first.card, view);
708
+ return await tell(ctx, event, settings, place, thread, readyNote(event.run, first, plan, settings), view);
515
709
  },
516
710
  approval_requested: async (event, ctx, place, settings, first) => await ask(ctx, event, place, settings, first),
517
711
  waiting_for_slot: async (event, ctx, place, settings, first) => {
@@ -532,26 +726,66 @@ async function take(event, ctx, settings) {
532
726
  const first = await beganOf(ctx, event);
533
727
  if (event.kind === "run_outcome") {
534
728
  began.delete(event.run);
729
+ held.delete(event.run);
535
730
  return await ended(ctx, event, settings, first);
536
731
  }
537
- if (!isTaken(event.kind))
732
+ if (!isTaken(event.kind) || (progressOnly.has(event.kind) && late(event)))
538
733
  return ok(undefined);
539
734
  if (first.relayed !== undefined && event.kind === "attempt_outcome")
540
- return await relayedOutcome(ctx, event, first, first.relayed);
541
- if (first.quiet && event.kind !== "approval_requested")
735
+ return await relayedOutcome(ctx, event, first, first.relayed, settings);
736
+ if (first.relayed !== undefined && event.kind === "attempt_started")
737
+ return await relayedStart(ctx, event, first.relayed, settings);
738
+ const relayedOnly = first.relayed !== undefined && event.kind !== "approval_requested";
739
+ if (first.quiet && (event.kind === "run_created" || relayedOnly))
542
740
  return ok(undefined);
543
741
  const home = await homeOf(ctx, event, settings);
544
742
  if (!home.ok || home.value === undefined)
545
743
  return home;
546
744
  const thread = event.kind === "run_created"
547
- ? await openThread(ctx, event, home.value)
745
+ ? ok(home.value.origin?.thread)
548
746
  : event.kind === "approval_requested"
549
747
  ? await cardThread(ctx, event, home.value, first.card)
550
748
  : await threadOf(ctx, event, home.value);
551
749
  if (!thread.ok)
552
750
  return thread;
751
+ const opened = thread.value === undefined &&
752
+ first.card !== undefined &&
753
+ event.kind !== "run_created" &&
754
+ !late(event)
755
+ ? await opening(ctx, event, home.value.channel, first.card, async () => await viewOf(ctx, event, first, settings, "working"))
756
+ : thread;
757
+ if (!opened.ok || (opened.value === undefined && event.kind !== "run_created"))
758
+ return opened;
553
759
  const step = steps[event.kind];
554
- return await step(event, ctx, { ...home.value, thread: thread.value }, settings, first);
760
+ return await step(event, ctx, { ...home.value, thread: opened.value }, settings, first);
761
+ }
762
+ /** The card's thread for a step of a run that its thread does not list yet: the card's thread when the card already has one, which `joinedRoot` gives the run, so the run shows from its first stage; else none while `held` keeps the run's plan, and then the thread that `rootOf` opens and gives the run. With no thread yet, the plan is held until the run starts its second stage or a done stage asks a person a question, so a run that ends after one stage with nothing to tell posts no new message at the top of the channel. */
763
+ async function opening(ctx, event, channel, card, view) {
764
+ const base = held.get(event.run) ?? {
765
+ run: event.run,
766
+ tasks: [],
767
+ pulls: [],
768
+ card: cardLine(card, style),
769
+ };
770
+ const { stage } = event;
771
+ const word = outcomeRecord.safeParse(event.payload).data?.outcome.outcome;
772
+ const wait = waitingForSlot.safeParse(event.payload).data;
773
+ const next = event.kind === "attempt_started" && stage !== null
774
+ ? withTask(base, stage, "working")
775
+ : event.kind === "attempt_outcome" && stage !== null && word !== undefined
776
+ ? afterOutcome(base, stage, event.payload, word)
777
+ : event.kind === "waiting_for_slot" && wait !== undefined
778
+ ? { ...base, queued: wait }
779
+ : base;
780
+ const asked = event.kind === "attempt_outcome" && questionOutcome.safeParse(event.payload).success;
781
+ if (!asked && next.tasks.length < 2) {
782
+ const joined = await joinedRoot(ctx, channel, card, event.run, await view());
783
+ if (!joined.ok || joined.value !== undefined)
784
+ return joined;
785
+ held.set(event.run, next);
786
+ return ok(undefined);
787
+ }
788
+ return await rootOf(ctx, channel, card, event.run, await view());
555
789
  }
556
790
  async function deliver(event, ctx) {
557
791
  const settings = settingsOf(ctx.config);