@noetic-tools/core 5.21.0 → 5.22.0-next.1

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.
Files changed (83) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.js +8 -0
  30. package/dist/harness/model-rounds.d.ts +30 -0
  31. package/dist/harness/model-rounds.js +146 -1
  32. package/dist/harness/model-tool-round.d.ts +3 -0
  33. package/dist/harness/model-tool-round.js +201 -19
  34. package/dist/harness/park-watchers.d.ts +93 -0
  35. package/dist/harness/park-watchers.js +217 -0
  36. package/dist/harness/read-decision.d.ts +23 -0
  37. package/dist/harness/read-decision.js +100 -0
  38. package/dist/harness/spend.js +4 -0
  39. package/dist/harness/steer-inbox.js +3 -1
  40. package/dist/harness/thread-record.d.ts +77 -1
  41. package/dist/harness/thread-record.js +272 -13
  42. package/dist/index.d.ts +17 -7
  43. package/dist/index.js +10 -2
  44. package/dist/interpreter/acp-resume.d.ts +77 -0
  45. package/dist/interpreter/acp-resume.js +164 -0
  46. package/dist/interpreter/acp-tools.d.ts +11 -0
  47. package/dist/interpreter/acp-tools.js +94 -7
  48. package/dist/interpreter/connection-steps.d.ts +24 -1
  49. package/dist/interpreter/connection-steps.js +77 -2
  50. package/dist/interpreter/execute-acp-agent.js +111 -15
  51. package/dist/interpreter/execute-action.js +7 -0
  52. package/dist/interpreter/execute-call.js +30 -4
  53. package/dist/interpreter/execute-control.js +21 -0
  54. package/dist/interpreter/execute-invoke-tool.js +149 -5
  55. package/dist/interpreter/execute-wait.js +67 -9
  56. package/dist/interpreter/execute.js +4 -0
  57. package/dist/interpreter/turn-ending.d.ts +15 -0
  58. package/dist/interpreter/turn-ending.js +46 -0
  59. package/dist/portable/builders.d.ts +1 -1
  60. package/dist/portable/builders.js +1 -1
  61. package/dist/runtime/durable/parking.d.ts +61 -0
  62. package/dist/runtime/durable/parking.js +137 -0
  63. package/dist/runtime/durable/session-store.d.ts +38 -0
  64. package/dist/runtime/durable/session-store.js +79 -1
  65. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  66. package/dist/runtime/durable/step-ledger.js +352 -15
  67. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  68. package/dist/runtime/durable/turn-lease.js +307 -0
  69. package/dist/runtime/held-calls.d.ts +192 -0
  70. package/dist/runtime/held-calls.js +496 -0
  71. package/dist/runtime/in-memory-storage.d.ts +10 -1
  72. package/dist/runtime/in-memory-storage.js +20 -2
  73. package/dist/runtime/message-queue.d.ts +2 -0
  74. package/dist/runtime/message-queue.js +8 -0
  75. package/dist/runtime/session-runner.d.ts +18 -2
  76. package/dist/runtime/session-runner.js +88 -3
  77. package/dist/runtime/tool-approval.d.ts +46 -6
  78. package/dist/runtime/tool-approval.js +160 -38
  79. package/dist/runtime/tool-call.d.ts +34 -2
  80. package/dist/runtime/tool-call.js +182 -13
  81. package/dist/runtime/tool-context.d.ts +15 -1
  82. package/dist/runtime/tool-context.js +38 -2
  83. package/package.json +3 -3
@@ -12,12 +12,30 @@
12
12
  */
13
13
  import { ConnectionUnsatisfiedError } from '@noetic-tools/types';
14
14
  import { z } from 'zod';
15
+ import { compileExpression, compute, computeMaybe, passes } from '../expression/jsonata.js';
15
16
  import { invalidConnectionError, unknownConnectionError } from './errors.js';
16
17
  import { isPlainRecord } from './values.js';
18
+ /** How many times an event is read before a trigger gives up on turning it into a turn. */
19
+ const ENTRY_ATTEMPTS = 3;
20
+ /** How long `idle` waits for a due event to be read before it stops waiting on it. */
21
+ const DUE_WAIT_MS = 1e4;
22
+ const DUE_POLL_MS = 10;
17
23
  //#endregion
18
24
  //#region Constants
19
- /** Deliveries of one event tried in-process before it waits for the next start. */
25
+ /** Deliveries of one event tried before the trigger gives up on it. */
20
26
  const MAX_DELIVERY_ATTEMPTS = 5;
27
+ /** A trigger as stored: only its data. A trigger with a function in it is not stored. */
28
+ const StoredTriggerSchema = z.object({
29
+ id: z.string().min(1),
30
+ connection: z.string().min(1),
31
+ event: z.string().min(1),
32
+ arguments: z.record(z.string(), z.unknown()).optional(),
33
+ filter: z.string().optional(),
34
+ input: z.string(),
35
+ thread: z.string().optional(),
36
+ });
37
+ /** Where triggers added while the harness runs are kept. */
38
+ const STORED_PREFIX = 'noetic/connections/triggers-added/';
21
39
  const InboxEntrySchema = z.object({
22
40
  event: z.object({
23
41
  id: z.string(),
@@ -37,6 +55,37 @@ const InboxEntrySchema = z.object({
37
55
  function prefix(triggerId) {
38
56
  return `noetic/connections/triggers/${triggerId}`;
39
57
  }
58
+ /**
59
+ * Compile a trigger's expressions.
60
+ *
61
+ * @throws NoeticConfigError `CONNECTION_INVALID` when one does not parse.
62
+ */
63
+ function compileTrigger(trigger) {
64
+ const compiled = {};
65
+ for (const field of [
66
+ 'filter',
67
+ 'input',
68
+ 'thread',
69
+ ]) {
70
+ const source = trigger[field];
71
+ if (typeof source !== 'string') {
72
+ continue;
73
+ }
74
+ try {
75
+ compiled[field] = compileExpression(source, `trigger '${trigger.id}' ${field}`);
76
+ }
77
+ catch (e) {
78
+ throw invalidConnectionError(`Trigger '${trigger.id}' has a ${field} expression that does not parse: ${e instanceof Error ? e.message : String(e)}`, 'Fix the JSONata syntax; the expression reads the event as `event`.');
79
+ }
80
+ }
81
+ return compiled;
82
+ }
83
+ /** True when a trigger is plain data, so it can be kept in storage. */
84
+ function isData(trigger) {
85
+ return (typeof trigger.input === 'string' &&
86
+ (trigger.filter === undefined || typeof trigger.filter === 'string') &&
87
+ (trigger.thread === undefined || typeof trigger.thread === 'string'));
88
+ }
40
89
  function defaultDelay(attempt) {
41
90
  return Math.min(3e4, 1e3 * 2 ** attempt);
42
91
  }
@@ -82,48 +131,241 @@ export function validateTriggers(triggers, names) {
82
131
  if (!trigger.event) {
83
132
  throw invalidConnectionError(`Trigger '${trigger.id}' names no event.`, "Set the event the trigger listens for, e.g. event: 'chat.message.created'.");
84
133
  }
134
+ compileTrigger(trigger);
85
135
  }
86
136
  }
87
137
  /** Runs a harness's triggers for its lifetime. */
88
138
  export class TriggerRunner {
89
139
  options;
90
140
  controller = new AbortController();
91
- loops = [];
141
+ triggers = new Map();
142
+ compiled = new Map();
143
+ /** Each trigger's listen loop, and what stops it. */
144
+ loops = new Map();
145
+ started = false;
92
146
  /**
93
147
  * The last delivery on each thread. A thread's events are delivered one turn
94
148
  * at a time, so each matching event starts its own turn instead of joining
95
149
  * a queued one (spec 35 § Triggers).
96
150
  */
97
151
  threads = new Map();
152
+ /** Events being stored right now, whose turns do not exist yet. */
153
+ handling = 0;
154
+ /** How often reading an event into an inbox entry has failed, by inbox key. */
155
+ entryTries = new Map();
98
156
  constructor(options) {
99
157
  this.options = options;
158
+ for (const trigger of options.triggers) {
159
+ this.triggers.set(trigger.id, trigger);
160
+ this.compiled.set(trigger.id, compileTrigger(trigger));
161
+ }
100
162
  }
101
163
  /**
102
- * Redelivers undelivered inbox entries and starts listening.
164
+ * Loads the triggers added on an earlier run, redelivers undelivered inbox
165
+ * entries, and starts listening.
103
166
  *
104
167
  * @throws ConnectionUnsatisfiedError when a trigger's connection does not offer its event.
105
168
  */
106
169
  async start() {
107
- for (const trigger of this.options.triggers) {
108
- const manifest = this.options.runtime.current(trigger.connection)?.manifest;
109
- if (manifest && !manifest.events[trigger.event]) {
110
- throw new ConnectionUnsatisfiedError({
111
- connection: trigger.connection,
112
- missing: {
113
- kind: 'event',
114
- event: trigger.event,
115
- },
116
- });
170
+ const added = await this.loadAdded();
171
+ for (const trigger of [
172
+ ...this.triggers.values(),
173
+ ]) {
174
+ if (!added.has(trigger.id)) {
175
+ this.requireEvent(trigger);
176
+ continue;
177
+ }
178
+ // A trigger kept from an earlier run may name an event its connection no
179
+ // longer offers. That stops this trigger, not every other one.
180
+ try {
181
+ this.requireEvent(trigger);
182
+ }
183
+ catch (e) {
184
+ this.report(trigger.id, e);
185
+ this.triggers.delete(trigger.id);
186
+ this.compiled.delete(trigger.id);
117
187
  }
118
188
  }
119
- for (const trigger of this.options.triggers) {
120
- await this.redeliver(trigger);
121
- this.loops.push(this.listenLoop(trigger));
189
+ this.started = true;
190
+ for (const trigger of this.triggers.values()) {
191
+ await this.begin(trigger);
122
192
  }
123
193
  }
124
194
  async close() {
125
195
  this.controller.abort();
126
- await Promise.allSettled(this.loops);
196
+ await Promise.allSettled([
197
+ ...this.loops.values(),
198
+ ].map((loop) => loop.done));
199
+ }
200
+ /** Every trigger the runner has: the harness's own, and those added while it ran. */
201
+ list() {
202
+ return [
203
+ ...this.triggers.values(),
204
+ ];
205
+ }
206
+ /**
207
+ * Add a trigger while the harness runs. One written with expressions only is kept
208
+ * in storage and is there again after a restart; one with a function in it lasts
209
+ * for this process.
210
+ *
211
+ * @throws NoeticConfigError `CONNECTION_INVALID` for an id already in use, a
212
+ * missing event or an expression that does not parse; `CONNECTION_UNKNOWN` for
213
+ * an unknown connection.
214
+ * @throws ConnectionUnsatisfiedError when the connection does not offer the event.
215
+ */
216
+ async add(trigger) {
217
+ validateTriggers([
218
+ ...this.triggers.values(),
219
+ trigger,
220
+ ], this.options.runtime.names());
221
+ this.requireEvent(trigger);
222
+ this.triggers.set(trigger.id, trigger);
223
+ this.compiled.set(trigger.id, compileTrigger(trigger));
224
+ if (isData(trigger)) {
225
+ await this.options.storage.set(`${STORED_PREFIX}${trigger.id}`, trigger);
226
+ }
227
+ if (this.started) {
228
+ await this.begin(trigger);
229
+ }
230
+ }
231
+ /** Stop and forget a trigger. Resolves false when there is none with that id. */
232
+ async remove(id) {
233
+ if (!this.triggers.has(id)) {
234
+ return false;
235
+ }
236
+ this.triggers.delete(id);
237
+ this.compiled.delete(id);
238
+ const loop = this.loops.get(id);
239
+ this.loops.delete(id);
240
+ loop?.controller.abort();
241
+ await loop?.done;
242
+ await this.options.storage.delete(`${STORED_PREFIX}${id}`);
243
+ // What it had in hand goes with it: a trigger added later under this id starts
244
+ // clean, not from this one's cursor and its list of events already seen.
245
+ for (const key of await this.options.storage.list(`${prefix(id)}/`)) {
246
+ await this.options.storage.delete(key);
247
+ }
248
+ return true;
249
+ }
250
+ /**
251
+ * Epoch ms of the earliest event a trigger is due, for triggers on a connection
252
+ * that can tell (`Connection.schedule`, as `cron()` has). Undefined when none can,
253
+ * or before the runner has started.
254
+ */
255
+ async nextDue() {
256
+ const now = (this.options.now ?? Date.now)();
257
+ let earliest;
258
+ for (const trigger of this.triggers.values()) {
259
+ const schedule = this.options.runtime.current(trigger.connection)?.schedule;
260
+ if (!schedule) {
261
+ continue;
262
+ }
263
+ const due = schedule.next(await this.cursorOf(trigger), now);
264
+ if (due !== undefined) {
265
+ earliest = earliest === undefined ? due : Math.min(earliest, due);
266
+ }
267
+ }
268
+ return earliest;
269
+ }
270
+ /**
271
+ * Resolves once the runner has nothing in hand: every scheduled event that is
272
+ * due has been read, and every turn a trigger started has finished or parked.
273
+ * It gives up waiting on a due event after `dueWaitMs`, so a source that cannot
274
+ * deliver does not hold a caller forever.
275
+ */
276
+ async idle(dueWaitMs = DUE_WAIT_MS) {
277
+ const now = this.options.now ?? Date.now;
278
+ const giveUpAt = Date.now() + dueWaitMs;
279
+ for (;;) {
280
+ await Promise.allSettled([
281
+ ...this.threads.values(),
282
+ ]);
283
+ const due = await this.nextDue();
284
+ const overdue = due !== undefined && due <= now() && Date.now() < giveUpAt;
285
+ if (!overdue && this.threads.size === 0 && this.handling === 0) {
286
+ return;
287
+ }
288
+ await wait(DUE_POLL_MS, this.controller.signal);
289
+ if (this.controller.signal.aborted) {
290
+ return;
291
+ }
292
+ }
293
+ }
294
+ async cursorOf(trigger) {
295
+ const cursor = await this.options.storage.get(`${prefix(trigger.id)}/cursor`);
296
+ return typeof cursor === 'string' ? cursor : null;
297
+ }
298
+ /**
299
+ * A trigger on a scheduled connection starts counting from now. Without a stored
300
+ * place to count from, a host that is not running when the first event falls due
301
+ * would come back, count from "now" again, and never see it.
302
+ */
303
+ async anchor(trigger) {
304
+ const schedule = this.options.runtime.current(trigger.connection)?.schedule;
305
+ if (!schedule || (await this.cursorOf(trigger)) !== null) {
306
+ return;
307
+ }
308
+ await this.advance(trigger, schedule.begin((this.options.now ?? Date.now)()));
309
+ }
310
+ /** Triggers added on an earlier run, read back from storage. */
311
+ async loadAdded() {
312
+ const added = new Set();
313
+ for (const key of await this.options.storage.list(STORED_PREFIX)) {
314
+ const parsed = StoredTriggerSchema.safeParse(await this.options.storage.get(key));
315
+ if (!parsed.success || this.triggers.has(parsed.data.id)) {
316
+ continue;
317
+ }
318
+ try {
319
+ this.compiled.set(parsed.data.id, compileTrigger(parsed.data));
320
+ this.triggers.set(parsed.data.id, parsed.data);
321
+ added.add(parsed.data.id);
322
+ }
323
+ catch (e) {
324
+ this.report(parsed.data.id, e);
325
+ }
326
+ }
327
+ return added;
328
+ }
329
+ requireEvent(trigger) {
330
+ const manifest = this.options.runtime.current(trigger.connection)?.manifest;
331
+ if (manifest && !manifest.events[trigger.event]) {
332
+ throw new ConnectionUnsatisfiedError({
333
+ connection: trigger.connection,
334
+ missing: {
335
+ kind: 'event',
336
+ event: trigger.event,
337
+ },
338
+ });
339
+ }
340
+ }
341
+ /** Redeliver what the trigger left in its inbox, then listen. */
342
+ async begin(trigger) {
343
+ await this.redeliver(trigger);
344
+ await this.anchor(trigger);
345
+ const controller = new AbortController();
346
+ const stop = () => controller.abort();
347
+ this.controller.signal.addEventListener('abort', stop, {
348
+ once: true,
349
+ });
350
+ if (this.controller.signal.aborted) {
351
+ stop();
352
+ }
353
+ this.loops.set(trigger.id, {
354
+ controller,
355
+ done: this.listenLoop(trigger, controller.signal),
356
+ });
357
+ }
358
+ /** Say on the stream that this event will not be tried again, and which one it was. */
359
+ gaveUp(trigger, event, why) {
360
+ this.options.runtime.emit({
361
+ type: 'trigger_gave_up',
362
+ data: {
363
+ connection: trigger.connection,
364
+ trigger: trigger.id,
365
+ event,
366
+ ...why,
367
+ },
368
+ });
127
369
  }
128
370
  report(trigger, error) {
129
371
  if (this.options.onError) {
@@ -143,8 +385,7 @@ export class TriggerRunner {
143
385
  this.deliver(trigger, parsed.data, key);
144
386
  }
145
387
  }
146
- async listenLoop(trigger) {
147
- const signal = this.controller.signal;
388
+ async listenLoop(trigger, signal) {
148
389
  let attempt = 0;
149
390
  while (!signal.aborted) {
150
391
  try {
@@ -165,12 +406,13 @@ export class TriggerRunner {
165
406
  }
166
407
  /** Listens until the stream ends. Returns whether it got as far as listening. */
167
408
  async listenOnce(trigger, signal) {
168
- const cursor = await this.options.storage.get(`${prefix(trigger.id)}/cursor`);
169
409
  const stream = await this.options.runtime.listenRaw(trigger.connection, {
170
410
  event: trigger.event,
171
411
  arguments: trigger.arguments,
172
- cursor: typeof cursor === 'string' ? cursor : null,
412
+ cursor: await this.cursorOf(trigger),
173
413
  signal,
414
+ // A source's `emit` waits to hear the event is in the inbox.
415
+ stores: true,
174
416
  });
175
417
  await stream.ready;
176
418
  for await (const message of stream) {
@@ -178,7 +420,20 @@ export class TriggerRunner {
178
420
  break;
179
421
  }
180
422
  if (message.type === 'event') {
181
- await this.handle(trigger, message.event);
423
+ // In hand from here: storing the event and saying when the next is due come
424
+ // before its turn exists, and `idle()` must not take that gap for rest.
425
+ this.handling += 1;
426
+ try {
427
+ await this.handle(trigger, message.event);
428
+ }
429
+ catch (e) {
430
+ message.stored?.(e);
431
+ throw e;
432
+ }
433
+ finally {
434
+ this.handling -= 1;
435
+ }
436
+ message.stored?.();
182
437
  continue;
183
438
  }
184
439
  this.options.runtime.emit({
@@ -212,15 +467,30 @@ export class TriggerRunner {
212
467
  entry = await this.entryFor(trigger, init);
213
468
  }
214
469
  catch (e) {
215
- // A filter or input that throws on one event dead-letters it rather than
216
- // re-reading it from the same cursor forever.
470
+ // It may be the event (a filter that throws on it) or the moment (a blob
471
+ // that could not be stored just now). So it is tried again: the cursor is not
472
+ // moved, the sender is told the event was not stored, and the stream is read
473
+ // again from where it was. After a few tries it is given up on, rather than
474
+ // re-read from the same cursor forever.
475
+ const tries = (this.entryTries.get(inboxKey) ?? 0) + 1;
476
+ if (tries < ENTRY_ATTEMPTS) {
477
+ this.entryTries.set(inboxKey, tries);
478
+ throw e;
479
+ }
480
+ this.entryTries.delete(inboxKey);
217
481
  this.report(trigger.id, e);
482
+ const error = e instanceof Error ? e.message : String(e);
483
+ this.gaveUp(trigger, init, {
484
+ attempts: tries,
485
+ error,
486
+ });
218
487
  await storage.set(seenKey, {
219
- failed: e instanceof Error ? e.message : String(e),
488
+ failed: error,
220
489
  });
221
490
  await this.advance(trigger, init.cursor);
222
491
  return;
223
492
  }
493
+ this.entryTries.delete(inboxKey);
224
494
  if (!entry) {
225
495
  await this.advance(trigger, init.cursor);
226
496
  return;
@@ -240,12 +510,13 @@ export class TriggerRunner {
240
510
  /** The inbox entry for an event, or `undefined` when the trigger's filter rejects it. */
241
511
  async entryFor(trigger, init) {
242
512
  const runtime = this.options.runtime;
513
+ const compiled = this.compiled.get(trigger.id) ?? {};
243
514
  const stamped = {
244
515
  ...init,
245
516
  connection: trigger.connection,
246
517
  };
247
518
  const field = runtime.current(trigger.connection)?.manifest.events[trigger.event]?.thread;
248
- const threadId = trigger.thread?.(stamped) ?? naturalThread(stamped, field) ?? trigger.id;
519
+ const threadId = (await threadOf(trigger, compiled, stamped)) ?? naturalThread(stamped, field) ?? trigger.id;
249
520
  const payload = await runtime.admit(trigger.connection, init.payload, {
250
521
  threadId,
251
522
  executionId: `trigger:${trigger.id}`,
@@ -254,13 +525,13 @@ export class TriggerRunner {
254
525
  ...stamped,
255
526
  payload,
256
527
  };
257
- if (trigger.filter && !trigger.filter(event)) {
528
+ if (!(await lets(trigger, compiled, event))) {
258
529
  return undefined;
259
530
  }
260
531
  return {
261
532
  event,
262
533
  threadId,
263
- input: trigger.input(event),
534
+ input: await inputOf(trigger, compiled, event),
264
535
  messageId: `${trigger.connection}:${trigger.id}:${init.id}`,
265
536
  };
266
537
  }
@@ -269,10 +540,16 @@ export class TriggerRunner {
269
540
  return;
270
541
  }
271
542
  await this.options.storage.set(`${prefix(trigger.id)}/cursor`, cursor);
543
+ if (this.options.runtime.current(trigger.connection)?.schedule) {
544
+ await this.options.onSchedule?.();
545
+ }
272
546
  }
273
547
  deliver(trigger, entry, inboxKey) {
274
548
  const previous = this.threads.get(entry.threadId) ?? Promise.resolve();
275
- const next = previous.then(() => this.deliverWithRetry(trigger, entry, inboxKey));
549
+ const next = previous.then(() => this.deliverWithRetry(trigger, {
550
+ entry,
551
+ inboxKey,
552
+ }));
276
553
  this.threads.set(entry.threadId, next);
277
554
  void next.finally(() => {
278
555
  if (this.threads.get(entry.threadId) === next) {
@@ -280,12 +557,24 @@ export class TriggerRunner {
280
557
  }
281
558
  });
282
559
  }
283
- /** Delivers one inbox entry, retrying a failed turn with backoff; marks it done on success. */
284
- async deliverWithRetry(trigger, entry, inboxKey) {
560
+ /**
561
+ * Delivers one inbox entry, retrying a failed turn with backoff. On success the
562
+ * event is marked done. After the last try the trigger gives up: the failure is
563
+ * reported, the event is marked seen so it is not delivered again, and nothing
564
+ * more is kept. A host that wants another try emits the event again itself.
565
+ */
566
+ async deliverWithRetry(trigger, at) {
567
+ const { entry, inboxKey } = at;
285
568
  const storage = this.options.storage;
286
- const seenKey = `${prefix(trigger.id)}/seen/${encodeURIComponent(entry.event.id)}`;
569
+ const base = prefix(trigger.id);
570
+ const eventKey = encodeURIComponent(entry.event.id);
571
+ const seenKey = `${base}/seen/${eventKey}`;
287
572
  const signal = this.controller.signal;
288
- for (let attempt = 0; attempt < MAX_DELIVERY_ATTEMPTS && !signal.aborted; attempt++) {
573
+ // Stopped: the runner closed, or this trigger was removed while it retried.
574
+ const stopped = () => signal.aborted || !this.triggers.has(trigger.id);
575
+ let lastError = '';
576
+ let attempts = 0;
577
+ for (; attempts < MAX_DELIVERY_ATTEMPTS && !stopped(); attempts++) {
289
578
  try {
290
579
  await this.options.deliver({
291
580
  trigger: trigger.id,
@@ -300,11 +589,62 @@ export class TriggerRunner {
300
589
  return;
301
590
  }
302
591
  catch (e) {
592
+ lastError = e instanceof Error ? e.message : String(e);
303
593
  this.report(trigger.id, e);
304
594
  }
305
- await wait((this.options.redeliverDelayMs ?? defaultDelay)(attempt), signal);
595
+ await wait((this.options.redeliverDelayMs ?? defaultDelay)(attempts), signal);
596
+ }
597
+ // Stopped part way, on the last try included: the inbox entry stays and is
598
+ // delivered again on the next start.
599
+ if (attempts < MAX_DELIVERY_ATTEMPTS || stopped()) {
600
+ return;
306
601
  }
307
- // Still undelivered: the inbox entry stays and is delivered again on the next start.
602
+ await storage.set(seenKey, {
603
+ failed: lastError,
604
+ });
605
+ await storage.delete(inboxKey);
606
+ this.gaveUp(trigger, entry.event, {
607
+ attempts,
608
+ error: lastError,
609
+ });
610
+ }
611
+ }
612
+ /** The thread a trigger names for an event, by its function or its expression. */
613
+ async function threadOf(trigger, compiled, event) {
614
+ if (typeof trigger.thread === 'function') {
615
+ return trigger.thread(event);
308
616
  }
617
+ if (!compiled.thread) {
618
+ return undefined;
619
+ }
620
+ const value = await computeMaybe(compiled.thread, {
621
+ event,
622
+ });
623
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
624
+ }
625
+ /** Whether a trigger's filter lets an event through. */
626
+ async function lets(trigger, compiled, event) {
627
+ if (typeof trigger.filter === 'function') {
628
+ return trigger.filter(event);
629
+ }
630
+ if (!compiled.filter) {
631
+ return true;
632
+ }
633
+ return passes(compiled.filter, {
634
+ event,
635
+ });
636
+ }
637
+ /** The message a trigger starts its turn with. An expression's value that is not text is sent as JSON. */
638
+ async function inputOf(trigger, compiled, event) {
639
+ if (typeof trigger.input === 'function') {
640
+ return trigger.input(event);
641
+ }
642
+ if (!compiled.input) {
643
+ return '';
644
+ }
645
+ const value = await compute(compiled.input, {
646
+ event,
647
+ });
648
+ return typeof value === 'string' ? value : JSON.stringify(value);
309
649
  }
310
650
  //#endregion