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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,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,11 +157,9 @@ 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
- assignee,
138
163
  user,
139
164
  consoleUrl: settings.console_url,
140
165
  });
@@ -148,7 +173,7 @@ async function ask(ctx, event, place, settings, first) {
148
173
  await status(ctx, place.origin, "suspended");
149
174
  return ok(undefined);
150
175
  }
151
- /** 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. */
152
177
  async function question(ctx, event, stage, place, settings, first) {
153
178
  const asked = questionOutcome.safeParse(event.payload).data?.outcome.output.question;
154
179
  if (asked === undefined)
@@ -161,27 +186,28 @@ async function question(ctx, event, stage, place, settings, first) {
161
186
  return found;
162
187
  if (found.value !== undefined)
163
188
  return ok(undefined);
164
- const { assignee } = first;
165
- const user = assignee === undefined
166
- ? undefined
167
- : await mentioned(ctx, run, "the question", assignee, settings);
168
- const { text, blocks } = questionLayout({
169
- run,
170
- card: first.card,
171
- assignee,
172
- user,
173
- question: asked,
174
- });
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 });
175
192
  const sent = await post(ctx, channel, thread, text, {
176
193
  blocks,
177
194
  metadata: mark("edgar_question", { run, stage }),
178
195
  });
179
196
  return sent.ok ? ok(undefined) : sent;
180
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"]);
181
206
  /** The kinds of end note that a person must see also when the run showed no plan. */
182
207
  const asks = new Set([
183
208
  "recovered",
184
209
  "decision",
210
+ "handed",
185
211
  "opened",
186
212
  "merged",
187
213
  "approved",
@@ -193,18 +219,21 @@ const asks = new Set([
193
219
  function markOf(note) {
194
220
  return note?.what === "opened" ? "edgar_ready" : "edgar_end";
195
221
  }
196
- /** 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. */
197
- 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) {
198
224
  const { channel, thread } = place;
199
- const found = await findMarked(ctx, channel, thread, kind, (p) => p["run"] === run);
200
- if (!found.ok)
201
- return found;
202
- 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)
203
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;
204
234
  const sent = await post(ctx, channel, thread, note.text, {
205
235
  blocks: note.blocks,
206
236
  metadata: mark(kind, { run }),
207
- ...(shown && thread !== undefined ? { reply_broadcast: true } : {}),
208
237
  });
209
238
  if (!sent.ok)
210
239
  return sent;
@@ -212,13 +241,70 @@ async function noteAt(ctx, place, run, note, shown, kind) {
212
241
  ctx.log(`run ${run}: ${what} went to ${sent.value.channel} at ${sent.value.ts}`);
213
242
  return ok(undefined);
214
243
  }
215
- /** 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. */
216
- 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 = []) {
217
303
  const places = [];
218
304
  if (home !== undefined && !home.direct) {
219
305
  const under = found !== undefined || note?.card === undefined
220
306
  ? ok(found)
221
- : await rootOf(ctx, home.channel, note.card, event.run);
307
+ : await rootOf(ctx, home.channel, note.card, event.run, view);
222
308
  if (!under.ok)
223
309
  return under;
224
310
  places.push({ channel: home.channel, thread: under.value });
@@ -229,14 +315,14 @@ async function tell(ctx, event, settings, home, found, note) {
229
315
  return channel;
230
316
  const thread = note?.card === undefined
231
317
  ? ok(undefined)
232
- : await rootOf(ctx, channel.value, note.card, event.run);
318
+ : await rootOf(ctx, channel.value, note.card, event.run, view);
233
319
  if (!thread.ok)
234
320
  return thread;
235
321
  places.push({ channel: channel.value, thread: thread.value });
236
322
  }
237
323
  const shown = note?.what === "opened" ? settings.channel : undefined;
238
324
  if (shown !== undefined) {
239
- const team = await oneMore(ctx, shown, note?.card, event.run, places);
325
+ const team = await oneMore(ctx, shown, note?.card, event.run, places, view);
240
326
  if (!team.ok)
241
327
  return team;
242
328
  if (team.value !== undefined)
@@ -247,20 +333,41 @@ async function tell(ctx, event, settings, home, found, note) {
247
333
  : await mentioned(ctx, event.run, "the end note", note.assignee, settings);
248
334
  if (user !== undefined && note?.what === "decision") {
249
335
  const direct = await directOf(ctx, user);
250
- 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;
251
339
  if (!own.ok)
252
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})`);
253
341
  else if (own.value !== undefined)
254
342
  places.push(own.value);
255
343
  }
256
- 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;
257
351
  for (const place of places) {
258
- 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);
259
353
  if (!sent.ok)
260
354
  return sent;
261
355
  }
262
356
  return ok(undefined);
263
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
+ }
264
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. */
265
372
  async function promise(ctx, event, at) {
266
373
  const channel = postOutcome.safeParse(event.payload).data?.outcome.output.post_in;
@@ -344,8 +451,8 @@ function readyNote(run, first, plan, settings) {
344
451
  }
345
452
  /** The most characters of an answer in a thread; Slack refuses a text over 40,000. */
346
453
  const ANSWER_CHARS = 39_000;
347
- /** 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. */
348
- 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) {
349
456
  if (newestMarked(all, "edgar_relay_done", (p) => p["run"] === run) !== undefined)
350
457
  return;
351
458
  const [oldest] = waitingRelays(all);
@@ -355,36 +462,97 @@ async function closeRelay(ctx, at, run, all) {
355
462
  const closed = await update(ctx, at.channel, oldest.ts, oldest.text ?? "", { metadata });
356
463
  if (!closed.ok)
357
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);
358
501
  }
359
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. */
360
- async function answerIn(ctx, run, at, said) {
503
+ async function answerIn(ctx, run, at, say) {
361
504
  const all = await listed(ctx, at.channel, at.thread);
362
505
  if (!all.ok)
363
506
  return all;
364
507
  if (newestMarked(all.value, "edgar_answer", (p) => p["run"] === run) !== undefined)
365
508
  return ok(undefined);
366
509
  const user = waitingRelays(all.value)[0]?.metadata?.event_payload["user"];
367
- const text = said(typeof user === "string" ? user : undefined);
510
+ const { text, blocks } = say(typeof user === "string" ? user : undefined);
368
511
  const sent = await post(ctx, at.channel, at.thread, text, {
512
+ ...(blocks.length === 0 ? {} : { blocks }),
369
513
  metadata: mark("edgar_answer", { run }),
370
514
  });
371
515
  if (!sent.ok)
372
516
  return sent;
373
- await closeRelay(ctx, at, run, all.value);
517
+ await closeRelay(ctx, at, run, all.value, true);
374
518
  return ok(undefined);
375
519
  }
376
- /** 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. */
377
- async function relayedOutcome(ctx, event, first, at) {
378
- const text = answerOutcome.safeParse(event.payload).data?.outcome.output.text;
379
- if (text !== undefined) {
380
- const shown = cutEscaped(escape(text), ANSWER_CHARS).text;
381
- 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));
382
547
  }
383
548
  const card = first.card === undefined ? openedOutcome.safeParse(event.payload).data : undefined;
384
549
  const id = card?.outcome.output.id;
385
550
  if (id === undefined)
386
551
  return ok(undefined);
387
- 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
+ }));
388
556
  }
389
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. */
390
558
  async function relayedEnd(ctx, event, first, at, word) {
@@ -401,11 +569,11 @@ async function relayedEnd(ctx, event, first, at, word) {
401
569
  if (!sent.ok)
402
570
  return sent;
403
571
  }
404
- await closeRelay(ctx, at, event.run, all.value);
572
+ await closeRelay(ctx, at, event.run, all.value, word === "done" && !failed);
405
573
  await threadStatus(ctx, at.channel, at.thread, "");
406
574
  return ok(failed);
407
575
  }
408
- /** 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. */
409
577
  async function ended(ctx, event, settings, first) {
410
578
  const note = endNote(event, style, settings.console_url);
411
579
  if (note === undefined)
@@ -418,18 +586,16 @@ async function ended(ctx, event, settings, first) {
418
586
  if (!said.ok || said.value)
419
587
  return said.ok ? ok(undefined) : said;
420
588
  }
421
- if (first.quiet && note?.what === "done") {
422
- const origin = slackOrigin.safeParse(event.origin).data;
423
- if (origin !== undefined)
424
- 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)
425
591
  return ok(undefined);
426
- }
427
592
  const home = await homeOf(ctx, event, settings);
428
593
  if (!home.ok)
429
594
  return home;
430
595
  let planned = false;
431
596
  let found;
432
597
  let promised;
598
+ let chained = false;
433
599
  if (home.value !== undefined) {
434
600
  const thread = await threadOf(ctx, event, home.value);
435
601
  if (!thread.ok)
@@ -440,36 +606,59 @@ async function ended(ctx, event, settings, first) {
440
606
  const all = await listed(ctx, at.channel, found);
441
607
  if (!all.ok)
442
608
  return all;
443
- const over = (plan) => ({ ...plan, ended: word });
609
+ const over = (plan) => ({ ...plan, ended: note?.what ?? word });
444
610
  const changed = await replanIn(ctx, event, at, settings, over, all.value);
445
611
  if (!changed.ok)
446
612
  return changed;
447
613
  planned = changed.value !== undefined;
448
614
  await closeQuestions(ctx, at, event.run, note?.what === "stopped", all.value);
449
- const marker = word === "done"
615
+ const marker = word === "done" && !quiet
450
616
  ? newestMarked(all.value, "edgar_post_to", (p) => p["run"] !== event.run)
451
617
  : undefined;
452
618
  if (marker !== undefined)
453
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);
454
623
  }
455
- if (home.value.origin !== undefined) {
624
+ if (home.value.origin !== undefined && !quiet) {
456
625
  const close = settings.close_on_done && word === "done";
457
626
  await status(ctx, home.value.origin, close ? "closed" : "active");
458
627
  }
459
628
  }
629
+ if (quiet)
630
+ return ok(undefined);
460
631
  if (promised !== undefined) {
461
632
  const layout = noteLayout(event.run, note, undefined);
462
633
  const kept = await keepPromise(ctx, promised.at, promised.marker, layout);
463
634
  if (!kept.ok)
464
635
  return kept;
465
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);
466
646
  const told = note !== undefined && asks.has(note.what);
467
647
  const bare = note?.what === "done" && note.facts.summary === undefined;
468
648
  if (word === "done" && !told && (!planned || bare))
469
649
  return ok(undefined);
470
- 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);
471
660
  }
472
- /** 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. */
473
662
  const steps = {
474
663
  run_created: async (event, ctx, place) => {
475
664
  if (place.origin !== undefined)
@@ -484,10 +673,10 @@ const steps = {
484
673
  const at = { ...place, thread };
485
674
  const working = (p) => withTask(p, stage, "working");
486
675
  const changed = await replan(ctx, event, at, settings, working, first);
487
- if (place.origin !== undefined)
676
+ if (place.origin !== undefined && !first.quiet)
488
677
  await status(ctx, place.origin, "processing");
489
678
  if (changed.ok)
490
- await threadStatus(ctx, place.channel, thread, settings.status[stage] ?? PLAN.status(stageLabel(stage)));
679
+ await threadStatus(ctx, place.channel, thread, stageStatus(stage, settings));
491
680
  return changed;
492
681
  },
493
682
  attempt_outcome: async (event, ctx, place, settings, first) => {
@@ -508,12 +697,15 @@ const steps = {
508
697
  if (!promised.ok)
509
698
  return promised;
510
699
  const plan = changed.value;
511
- if (stage !== REVIEW_WAIT ||
700
+ if (first.part ||
701
+ stage !== REVIEW_WAIT ||
512
702
  word !== "waiting" ||
513
703
  plan === undefined ||
514
704
  plan.pulls.length === 0)
515
705
  return changed;
516
- 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);
517
709
  },
518
710
  approval_requested: async (event, ctx, place, settings, first) => await ask(ctx, event, place, settings, first),
519
711
  waiting_for_slot: async (event, ctx, place, settings, first) => {
@@ -521,7 +713,8 @@ const steps = {
521
713
  const { thread } = place;
522
714
  if (!wait.success || thread === undefined)
523
715
  return ok(undefined);
524
- const queued = (p) => ({ ...p, queued: wait.data });
716
+ const workflow = first.workflow === undefined ? {} : { workflow: first.workflow };
717
+ const queued = (p) => ({ ...p, queued: { ...wait.data, ...workflow } });
525
718
  return await replan(ctx, event, { ...place, thread }, settings, queued, first);
526
719
  },
527
720
  };
@@ -533,26 +726,66 @@ async function take(event, ctx, settings) {
533
726
  const first = await beganOf(ctx, event);
534
727
  if (event.kind === "run_outcome") {
535
728
  began.delete(event.run);
729
+ held.delete(event.run);
536
730
  return await ended(ctx, event, settings, first);
537
731
  }
538
- if (!isTaken(event.kind))
732
+ if (!isTaken(event.kind) || (progressOnly.has(event.kind) && late(event)))
539
733
  return ok(undefined);
540
734
  if (first.relayed !== undefined && event.kind === "attempt_outcome")
541
- return await relayedOutcome(ctx, event, first, first.relayed);
542
- 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))
543
740
  return ok(undefined);
544
741
  const home = await homeOf(ctx, event, settings);
545
742
  if (!home.ok || home.value === undefined)
546
743
  return home;
547
744
  const thread = event.kind === "run_created"
548
- ? await openThread(ctx, event, home.value)
745
+ ? ok(home.value.origin?.thread)
549
746
  : event.kind === "approval_requested"
550
747
  ? await cardThread(ctx, event, home.value, first.card)
551
748
  : await threadOf(ctx, event, home.value);
552
749
  if (!thread.ok)
553
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;
554
759
  const step = steps[event.kind];
555
- 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());
556
789
  }
557
790
  async function deliver(event, ctx) {
558
791
  const settings = settingsOf(ctx.config);