@agent-native/core 0.70.3 → 0.71.0

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 (79) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +13 -0
  3. package/corpus/core/docs/content/multi-app-workspace.md +2 -2
  4. package/corpus/core/docs/design/durable-agent-runs.md +458 -4
  5. package/corpus/core/package.json +1 -1
  6. package/corpus/core/src/agent/durable-background.ts +192 -0
  7. package/corpus/core/src/agent/production-agent.ts +330 -13
  8. package/corpus/core/src/agent/run-manager.ts +66 -3
  9. package/corpus/core/src/agent/run-store.ts +129 -23
  10. package/corpus/core/src/agent/types.ts +20 -0
  11. package/corpus/core/src/client/AgentPanel.tsx +12 -9
  12. package/corpus/core/src/client/blocks/library/FileTreeBlock.tsx +72 -14
  13. package/corpus/core/src/deploy/build.ts +96 -0
  14. package/corpus/core/src/deploy/workspace-deploy.ts +121 -0
  15. package/corpus/core/src/mcp/build-server.ts +22 -13
  16. package/corpus/core/src/server/agent-chat-plugin.ts +133 -66
  17. package/corpus/templates/analytics/.agents/skills/dashboard-management/SKILL.md +19 -0
  18. package/corpus/templates/analytics/AGENTS.md +8 -0
  19. package/corpus/templates/analytics/actions/compose-dashboard.ts +317 -0
  20. package/corpus/templates/analytics/changelog/2026-06-23-build-large-first-party-analytics-dashboards-in-one-fast-cal.md +6 -0
  21. package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +574 -0
  22. package/corpus/templates/clips/changelog/2026-06-23-dragging-the-desktop-camera-bubble-now-glides-to-a-stop-at-t.md +6 -0
  23. package/corpus/templates/clips/chrome-extension/src/background.ts +130 -32
  24. package/corpus/templates/clips/chrome-extension/src/content-script.ts +163 -13
  25. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +195 -34
  26. package/corpus/templates/clips/chrome-extension/src/overlay.css +73 -23
  27. package/corpus/templates/clips/chrome-extension/src/overlay.ts +82 -13
  28. package/corpus/templates/clips/chrome-extension/src/popup.html +62 -5
  29. package/corpus/templates/clips/chrome-extension/src/popup.ts +290 -1
  30. package/corpus/templates/clips/chrome-extension/src/styles.css +34 -0
  31. package/corpus/templates/clips/desktop/src/lib/audio-cue.ts +21 -16
  32. package/corpus/templates/clips/desktop/src/lib/recorder.ts +10 -17
  33. package/corpus/templates/clips/desktop/src/overlays/bubble.tsx +73 -23
  34. package/corpus/templates/clips/desktop/src/overlays/countdown.tsx +0 -6
  35. package/corpus/templates/clips/desktop/src/overlays/toolbar.tsx +56 -46
  36. package/corpus/templates/clips/desktop/src/styles.css +33 -5
  37. package/corpus/templates/clips/desktop/src-tauri/src/clips/mod.rs +113 -0
  38. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +3 -0
  39. package/dist/agent/durable-background.d.ts +60 -0
  40. package/dist/agent/durable-background.d.ts.map +1 -0
  41. package/dist/agent/durable-background.js +144 -0
  42. package/dist/agent/durable-background.js.map +1 -0
  43. package/dist/agent/production-agent.d.ts +20 -0
  44. package/dist/agent/production-agent.d.ts.map +1 -1
  45. package/dist/agent/production-agent.js +292 -14
  46. package/dist/agent/production-agent.js.map +1 -1
  47. package/dist/agent/run-manager.d.ts +48 -0
  48. package/dist/agent/run-manager.d.ts.map +1 -1
  49. package/dist/agent/run-manager.js +45 -3
  50. package/dist/agent/run-manager.js.map +1 -1
  51. package/dist/agent/run-store.d.ts +30 -1
  52. package/dist/agent/run-store.d.ts.map +1 -1
  53. package/dist/agent/run-store.js +124 -24
  54. package/dist/agent/run-store.js.map +1 -1
  55. package/dist/agent/types.d.ts +20 -0
  56. package/dist/agent/types.d.ts.map +1 -1
  57. package/dist/agent/types.js.map +1 -1
  58. package/dist/client/AgentPanel.d.ts.map +1 -1
  59. package/dist/client/AgentPanel.js +2 -2
  60. package/dist/client/AgentPanel.js.map +1 -1
  61. package/dist/client/blocks/library/FileTreeBlock.d.ts.map +1 -1
  62. package/dist/client/blocks/library/FileTreeBlock.js +37 -4
  63. package/dist/client/blocks/library/FileTreeBlock.js.map +1 -1
  64. package/dist/deploy/build.d.ts +29 -0
  65. package/dist/deploy/build.d.ts.map +1 -1
  66. package/dist/deploy/build.js +85 -0
  67. package/dist/deploy/build.js.map +1 -1
  68. package/dist/deploy/workspace-deploy.d.ts.map +1 -1
  69. package/dist/deploy/workspace-deploy.js +108 -0
  70. package/dist/deploy/workspace-deploy.js.map +1 -1
  71. package/dist/mcp/build-server.d.ts.map +1 -1
  72. package/dist/mcp/build-server.js +23 -9
  73. package/dist/mcp/build-server.js.map +1 -1
  74. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  75. package/dist/server/agent-chat-plugin.js +68 -13
  76. package/dist/server/agent-chat-plugin.js.map +1 -1
  77. package/docs/content/multi-app-workspace.md +2 -2
  78. package/docs/design/durable-agent-runs.md +458 -4
  79. package/package.json +1 -1
@@ -14,6 +14,20 @@ let _initPromise;
14
14
  * reaped and a zombie would keep running, eventually clobbering the new row.
15
15
  */
16
16
  export const RUN_STALE_MS = 15_000;
17
+ /**
18
+ * Stale window for runs dispatched into a Netlify background function
19
+ * (`dispatch_mode = 'background'`). The design doc flags the 15s reaper vs a
20
+ * background cold-start as the #1 false-failure risk: the foreground POST
21
+ * inserts the `running` row, then `fireInternalDispatch` returns 202 and the
22
+ * background function may take >15s to cold-start and emit its first heartbeat.
23
+ * With the normal 15s window the reaper would falsely kill that freshly-
24
+ * inserted-but-not-yet-heartbeaten row. 90s tolerates a slow background
25
+ * cold-start while still reaping a genuinely dead background worker promptly.
26
+ *
27
+ * Only applied to rows explicitly marked background-dispatched; ordinary
28
+ * foreground runs keep the tight 15s window unchanged.
29
+ */
30
+ export const BACKGROUND_RUN_STALE_MS = 90_000;
17
31
  export const STALE_RUN_ERROR_EVENT = {
18
32
  type: "error",
19
33
  error: "The agent stopped before it could finish. It may have hit a server timeout or the worker may have been interrupted.",
@@ -37,7 +51,8 @@ async function ensureRunTables() {
37
51
  last_progress_at ${intType()},
38
52
  turn_id TEXT,
39
53
  error_code TEXT,
40
- error_detail TEXT
54
+ error_detail TEXT,
55
+ dispatch_mode TEXT
41
56
  )
42
57
  `);
43
58
  // Backfill heartbeat_at on older deployments.
@@ -83,7 +98,16 @@ async function ensureRunTables() {
83
98
  // error_code / error_detail = terminal failure classification captured
84
99
  // at completion so errored/cut-off runs are queryable for
85
100
  // pattern analysis (see listErroredRuns).
86
- for (const col of ["turn_id", "error_code", "error_detail"]) {
101
+ // dispatch_mode marks how a run was started: NULL/"foreground" for the
102
+ // normal synchronous path, "background" for a run dispatched into a
103
+ // Netlify background function. The reaper/claim widen the stale window
104
+ // for background rows so a slow cold-start isn't falsely reaped.
105
+ for (const col of [
106
+ "turn_id",
107
+ "error_code",
108
+ "error_detail",
109
+ "dispatch_mode",
110
+ ]) {
87
111
  try {
88
112
  if (isPostgres()) {
89
113
  await client.execute(`ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS ${col} TEXT`);
@@ -204,14 +228,63 @@ export async function clearLedgerForThread(threadId) {
204
228
  // Best-effort.
205
229
  }
206
230
  }
207
- export async function insertRun(id, threadId, turnId) {
231
+ export async function insertRun(id, threadId, turnId, options) {
208
232
  await ensureRunTables();
209
233
  const client = getDbExec();
210
234
  const now = Date.now();
211
235
  await client.execute({
212
- sql: `INSERT INTO agent_runs (id, thread_id, status, started_at, heartbeat_at, last_progress_at, turn_id) VALUES (?, ?, 'running', ?, ?, ?, ?)`,
213
- args: [id, threadId, now, now, now, turnId ?? id],
236
+ sql: `INSERT INTO agent_runs (id, thread_id, status, started_at, heartbeat_at, last_progress_at, turn_id, dispatch_mode) VALUES (?, ?, 'running', ?, ?, ?, ?, ?)`,
237
+ args: [
238
+ id,
239
+ threadId,
240
+ now,
241
+ now,
242
+ now,
243
+ turnId ?? id,
244
+ options?.dispatchMode ?? null,
245
+ ],
246
+ });
247
+ }
248
+ /**
249
+ * SQL fragment that resolves the per-row stale cutoff. Background-dispatched
250
+ * runs (`dispatch_mode` starting with `background`) tolerate a much longer gap
251
+ * without a heartbeat (slow Netlify background-function cold-start) before being
252
+ * reaped; every other run keeps the tight 15s window. The bound `now` is
253
+ * subtracted by the resolved window so the comparison is
254
+ * `COALESCE(heartbeat_at, started_at) < (now - window)`.
255
+ *
256
+ * `dispatch_mode` is one of NULL/"foreground" (normal sync path), "background"
257
+ * (foreground inserted the row for a background dispatch), or
258
+ * "background-processing" (the background worker claimed it). Both background
259
+ * states get the wider window via a LIKE-prefix match.
260
+ */
261
+ function backgroundAwareStaleCutoffSql() {
262
+ return `(? - CASE WHEN dispatch_mode LIKE 'background%' THEN ${BACKGROUND_RUN_STALE_MS} ELSE ${RUN_STALE_MS} END)`;
263
+ }
264
+ /**
265
+ * Atomically claim a background-dispatched run for processing. The foreground
266
+ * POST inserts the run row with `dispatch_mode = 'background'`; the FIRST
267
+ * delivery of the background dispatch flips it to `background-processing` and
268
+ * wins the claim. A duplicate Netlify delivery (background functions can be
269
+ * retried) sees `background-processing` and loses, so it no-ops — mirroring
270
+ * `claimAgentTeamRun` returning null. Returns true when this caller won.
271
+ *
272
+ * Idempotent and conditional: the WHERE clause only matches the unclaimed
273
+ * `background` state AND a still-running row, so a reaped/terminal row can't be
274
+ * re-claimed.
275
+ */
276
+ export async function claimBackgroundRun(runId) {
277
+ await ensureRunTables();
278
+ const client = getDbExec();
279
+ const { rowsAffected } = await client.execute({
280
+ sql: `UPDATE agent_runs
281
+ SET dispatch_mode = 'background-processing'
282
+ WHERE id = ?
283
+ AND status = 'running'
284
+ AND dispatch_mode = 'background'`,
285
+ args: [runId],
214
286
  });
287
+ return (rowsAffected ?? 0) > 0;
215
288
  }
216
289
  /**
217
290
  * Atomically acquire a run lease for a thread. Succeeds (returns true) only
@@ -223,17 +296,36 @@ export async function insertRun(id, threadId, turnId) {
223
296
  * Callers that win the claim then insert the run row normally; callers that
224
297
  * lose skip the run and return the existing active runId to the caller.
225
298
  */
226
- export async function tryClaimRunSlot(threadId, maxStaleMs = RUN_STALE_MS) {
299
+ export async function tryClaimRunSlot(threadId, maxStaleMs) {
227
300
  await ensureRunTables();
228
301
  const client = getDbExec();
229
- const heartbeatCutoff = Date.now() - maxStaleMs;
302
+ const now = Date.now();
303
+ // Default: per-row background-aware window so a live background run (which can
304
+ // legitimately go >15s between heartbeats during a cold-start) isn't seen as
305
+ // "free" and double-claimed by a racing foreground POST. An explicit
306
+ // `maxStaleMs` override keeps a flat window for callers that want one.
307
+ if (typeof maxStaleMs === "number") {
308
+ const heartbeatCutoff = now - maxStaleMs;
309
+ const { rows } = await client.execute({
310
+ sql: `SELECT id FROM agent_runs
311
+ WHERE thread_id = ?
312
+ AND status = 'running'
313
+ AND COALESCE(heartbeat_at, started_at) >= ?
314
+ ORDER BY started_at DESC LIMIT 1`,
315
+ args: [threadId, heartbeatCutoff],
316
+ });
317
+ if (rows.length > 0) {
318
+ return { claimed: false, activeRunId: rows[0].id };
319
+ }
320
+ return { claimed: true, activeRunId: null };
321
+ }
230
322
  const { rows } = await client.execute({
231
323
  sql: `SELECT id FROM agent_runs
232
324
  WHERE thread_id = ?
233
325
  AND status = 'running'
234
- AND COALESCE(heartbeat_at, started_at) >= ?
326
+ AND COALESCE(heartbeat_at, started_at) >= ${backgroundAwareStaleCutoffSql()}
235
327
  ORDER BY started_at DESC LIMIT 1`,
236
- args: [threadId, heartbeatCutoff],
328
+ args: [threadId, now],
237
329
  });
238
330
  if (rows.length > 0) {
239
331
  const row = rows[0];
@@ -293,11 +385,17 @@ export async function bumpRunProgress(runId) {
293
385
  * (producer likely crashed), flip it to "errored" so watchers stop waiting.
294
386
  * Returns true if the row was reaped.
295
387
  */
296
- export async function reapIfStale(runId, maxStaleMs = RUN_STALE_MS) {
388
+ export async function reapIfStale(runId, maxStaleMs) {
297
389
  await ensureRunTables();
298
390
  const client = getDbExec();
299
391
  const completedAt = Date.now();
300
- const cutoff = completedAt - maxStaleMs;
392
+ // Background-dispatched runs get the wider stale window so a slow cold-start
393
+ // isn't reaped; foreground runs keep the tight 15s window. An explicit
394
+ // override forces a flat window for callers that want one.
395
+ const staleClause = typeof maxStaleMs === "number"
396
+ ? `COALESCE(heartbeat_at, started_at) < ?`
397
+ : `COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`;
398
+ const staleArgs = typeof maxStaleMs === "number" ? [completedAt - maxStaleMs] : [completedAt];
301
399
  const { rowsAffected } = await client.execute({
302
400
  sql: `UPDATE agent_runs
303
401
  SET status = 'errored',
@@ -306,13 +404,13 @@ export async function reapIfStale(runId, maxStaleMs = RUN_STALE_MS) {
306
404
  error_detail = ?
307
405
  WHERE id = ?
308
406
  AND status = 'running'
309
- AND COALESCE(heartbeat_at, started_at) < ?`,
407
+ AND ${staleClause}`,
310
408
  args: [
311
409
  completedAt,
312
410
  STALE_RUN_ERROR_EVENT.errorCode,
313
411
  STALE_RUN_ERROR_EVENT.details,
314
412
  runId,
315
- cutoff,
413
+ ...staleArgs,
316
414
  ],
317
415
  });
318
416
  const reaped = (rowsAffected ?? 0) > 0;
@@ -543,12 +641,13 @@ export async function getCurrentTurnEventsForThread(threadId) {
543
641
  export async function reapAllStaleRuns() {
544
642
  await ensureRunTables();
545
643
  const client = getDbExec();
546
- const heartbeatCutoff = Date.now() - RUN_STALE_MS;
644
+ const now = Date.now();
645
+ // Background-dispatched runs use the wider window; everything else 15s.
547
646
  const stale = await client.execute({
548
647
  sql: `SELECT id FROM agent_runs
549
648
  WHERE status = 'running'
550
- AND COALESCE(heartbeat_at, started_at) < ?`,
551
- args: [heartbeatCutoff],
649
+ AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,
650
+ args: [now],
552
651
  });
553
652
  const completedAt = Date.now();
554
653
  const { rowsAffected } = await client.execute({
@@ -558,12 +657,12 @@ export async function reapAllStaleRuns() {
558
657
  error_code = ?,
559
658
  error_detail = ?
560
659
  WHERE status = 'running'
561
- AND COALESCE(heartbeat_at, started_at) < ?`,
660
+ AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,
562
661
  args: [
563
662
  completedAt,
564
663
  STALE_RUN_ERROR_EVENT.errorCode,
565
664
  STALE_RUN_ERROR_EVENT.details,
566
- heartbeatCutoff,
665
+ completedAt,
567
666
  ],
568
667
  });
569
668
  for (const row of stale.rows) {
@@ -589,15 +688,15 @@ export async function cleanupOldRuns(olderThanMs, erroredOlderThanMs) {
589
688
  // SELECT covers BOTH UPDATE conditions so the terminal-event-append loop
590
689
  // below catches every row we're about to flip — a 24h-old row with a
591
690
  // somehow-fresh heartbeat would slip past a heartbeat-only SELECT.
592
- const heartbeatCutoff = Date.now() - RUN_STALE_MS;
691
+ const now = Date.now();
593
692
  const stale = await client.execute({
594
693
  sql: `SELECT id FROM agent_runs
595
694
  WHERE status = 'running'
596
695
  AND (
597
- COALESCE(heartbeat_at, started_at) < ?
696
+ COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}
598
697
  OR started_at < ?
599
698
  )`,
600
- args: [heartbeatCutoff, cutoff],
699
+ args: [now, cutoff],
601
700
  });
602
701
  const completedAt = Date.now();
603
702
  await client.execute({
@@ -614,7 +713,8 @@ export async function cleanupOldRuns(olderThanMs, erroredOlderThanMs) {
614
713
  cutoff,
615
714
  ],
616
715
  });
617
- // Also expire runs whose heartbeat is stale — producer has died.
716
+ // Also expire runs whose heartbeat is stale — producer has died. Uses the
717
+ // background-aware window so a slow background cold-start isn't reaped early.
618
718
  await client.execute({
619
719
  sql: `UPDATE agent_runs
620
720
  SET status = 'errored',
@@ -622,12 +722,12 @@ export async function cleanupOldRuns(olderThanMs, erroredOlderThanMs) {
622
722
  error_code = ?,
623
723
  error_detail = ?
624
724
  WHERE status = 'running'
625
- AND COALESCE(heartbeat_at, started_at) < ?`,
725
+ AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,
626
726
  args: [
627
727
  completedAt,
628
728
  STALE_RUN_ERROR_EVENT.errorCode,
629
729
  STALE_RUN_ERROR_EVENT.details,
630
- heartbeatCutoff,
730
+ completedAt,
631
731
  ],
632
732
  });
633
733
  for (const row of stale.rows) {
@@ -1 +1 @@
1
- {"version":3,"file":"run-store.js","sourceRoot":"","sources":["../../src/agent/run-store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG1D,IAAI,YAAuC,CAAC;AAE5C;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC;AAEnC,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,IAAI,EAAE,OAAO;IACb,KAAK,EACH,qHAAqH;IACvH,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,IAAI;IACjB,OAAO,EACL,gIAAgI;CAC1H,CAAC;AAEX,KAAK,UAAU,eAAe;IAC5B,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,MAAM,CAAC,OAAO,CAAC;;;;;;uBAMJ,OAAO,EAAE;yBACP,OAAO,EAAE;yBACT,OAAO,EAAE;6BACL,OAAO,EAAE;;;;;OAK/B,CAAC,CAAC;YACH,8CAA8C;YAC9C,IAAI,CAAC;gBACH,IAAI,UAAU,EAAE,EAAE,CAAC;oBACjB,MAAM,MAAM,CAAC,OAAO,CAClB,gEAAgE,OAAO,EAAE,EAAE,CAC5E,CAAC;oBACF,MAAM,MAAM,CAAC,OAAO,CAClB,mEAAmE,CACpE,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,MAAM,MAAM,CAAC,OAAO,CAClB,kDAAkD,OAAO,EAAE,EAAE,CAC9D,CAAC;gBACJ,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,iCAAiC;YACnC,CAAC;YACD,IAAI,CAAC;gBACH,IAAI,CAAC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,CAAC;aACxE;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,KAAK,UAAU,sBAAsB,CACnC,KAAa,EACb,KAA8B;IAE9B,MAAM,eAAe,EAAE,CAAC;IACxB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;QACpC,GAAG,EAAE,yFAAyF;QAC9F,IAAI,EAAE,CAAC,KAAK,CAAC;KACd,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAEN,CAAC;IACd,IAAI,IAAI,EAAE,UAAU,EAAE,CAAC;QACrB,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC3C,IACE,MAAM,EAAE,IAAI,KAAK,MAAM;gBACvB,MAAM,EAAE,IAAI,KAAK,OAAO;gBACxB,MAAM,EAAE,IAAI,KAAK,iBAAiB;gBAClC,MAAM,EAAE,IAAI,KAAK,YAAY;gBAC7B,MAAM,EAAE,IAAI,KAAK,eAAe,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,uDAAuD;QACzD,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtD,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE,8GAA8G;QACnH,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;KAC9C,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SQL persistence for agent runs and events.\n * Enables cross-isolate access on Cloudflare Workers and\n * reliable reconnection after page refreshes.\n */\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport { captureError } from \"../server/capture-error.js\";\nimport type { AgentChatEvent } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\n/**\n * Max time without a heartbeat before a \"running\" run is considered dead.\n * The run-manager heartbeats every 1.5s, so 15s tolerates ~9 missed writes.\n * Widened from 6s to absorb real-world DB latency spikes and GC pauses that\n * caused false-positive reaps: a live run whose heartbeat lagged 6s+ would be\n * reaped and a zombie would keep running, eventually clobbering the new row.\n */\nexport const RUN_STALE_MS = 15_000;\n\nexport const STALE_RUN_ERROR_EVENT = {\n type: \"error\",\n error:\n \"The agent stopped before it could finish. It may have hit a server timeout or the worker may have been interrupted.\",\n errorCode: \"stale_run\",\n recoverable: true,\n details:\n \"The run heartbeat stopped while the run was still marked running. Partial output and tool calls were preserved when available.\",\n} as const;\n\nasync function ensureRunTables(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_runs (\n id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'running',\n abort_reason TEXT,\n started_at ${intType()} NOT NULL,\n completed_at ${intType()},\n heartbeat_at ${intType()},\n last_progress_at ${intType()},\n turn_id TEXT,\n error_code TEXT,\n error_detail TEXT\n )\n `);\n // Backfill heartbeat_at on older deployments.\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS heartbeat_at ${intType()}`,\n );\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS abort_reason TEXT`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN heartbeat_at ${intType()}`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n try {\n if (!isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN abort_reason TEXT`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n // Backfill last_progress_at — this is distinct from heartbeat_at.\n // heartbeat_at = \"the producer process is alive\" (bumped on a timer).\n // last_progress_at = \"the agent is actually emitting events\" (bumped on\n // each emit). The gap between them is the stuck-detector signal.\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS last_progress_at ${intType()}`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN last_progress_at ${intType()}`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n // Backfill turn_id / error_code / error_detail.\n // turn_id = stable identity for one logical assistant turn that may\n // span several continuation runs, so the durable record\n // can be folded across runs instead of dropped per-run.\n // error_code / error_detail = terminal failure classification captured\n // at completion so errored/cut-off runs are queryable for\n // pattern analysis (see listErroredRuns).\n for (const col of [\"turn_id\", \"error_code\", \"error_detail\"] as const) {\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS ${col} TEXT`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN ${col} TEXT`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n }\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_run_events (\n run_id TEXT NOT NULL,\n seq ${intType()} NOT NULL,\n event_data TEXT NOT NULL,\n PRIMARY KEY (run_id, seq)\n )\n `);\n // Tool-call result ledger: persists the outcome of write tool calls that\n // completed AFTER their chunk was abandoned (zombie completions). A\n // resumed continuation can recover the real result by matching\n // thread_id + tool_key (name:stableInputHash) instead of re-executing\n // the side effect. Entries are scoped to the thread and expire with it.\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_tool_ledger (\n thread_id TEXT NOT NULL,\n tool_key TEXT NOT NULL,\n result_summary TEXT NOT NULL,\n completed_at ${intType()} NOT NULL,\n PRIMARY KEY (thread_id, tool_key)\n )\n `);\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n// ─── Tool-call result ledger ─────────────────────────────────────────────────\n//\n// When the run-level abort signal fires (soft timeout / user cancel) while a\n// write tool is in-flight, `Promise.race` abandons the call — but the action's\n// Promise continues running in the background (a \"zombie\"). If the zombie\n// resolves before the continuation's next tool dispatch, we record the result\n// here so the continuation can recover it without re-executing the side effect.\n//\n// Keyed by (thread_id, tool_key) where tool_key = \"<toolName>:<stableJsonHash>\".\n// The write is fire-and-forget from the hot path; reads are synchronous look-\n// ups at the start of each write-tool dispatch in the continuation.\n\n/** Max length for a persisted result summary (8 KB). */\nconst LEDGER_RESULT_MAX_CHARS = 8_000;\n\n/**\n * Persist a zombie tool-call completion to the ledger. Called by the detached\n * promise continuation after `Promise.race` abandons it. Best-effort — never\n * throws so a ledger write failure doesn't break any caller.\n */\nexport async function writeLedgerEntry(\n threadId: string,\n toolKey: string,\n resultSummary: string,\n): Promise<void> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n const capped =\n resultSummary.length > LEDGER_RESULT_MAX_CHARS\n ? resultSummary.slice(0, LEDGER_RESULT_MAX_CHARS) +\n `\\n...[ledger truncated at ${LEDGER_RESULT_MAX_CHARS} chars]`\n : resultSummary;\n await client.execute({\n sql: `INSERT INTO agent_tool_ledger (thread_id, tool_key, result_summary, completed_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT (thread_id, tool_key) DO UPDATE SET\n result_summary = excluded.result_summary,\n completed_at = excluded.completed_at`,\n args: [threadId, toolKey, capped, Date.now()],\n });\n } catch {\n // Ledger is best-effort; never surface failures to the caller.\n }\n}\n\n/**\n * Look up a prior zombie completion for this thread + tool key. Returns the\n * persisted result summary, or `null` when no entry exists.\n */\nexport async function readLedgerEntry(\n threadId: string,\n toolKey: string,\n): Promise<string | null> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT result_summary FROM agent_tool_ledger WHERE thread_id = ? AND tool_key = ?`,\n args: [threadId, toolKey],\n });\n if (rows.length === 0) return null;\n const row = rows[0] as { result_summary: string };\n return row.result_summary;\n } catch {\n return null;\n }\n}\n\n/**\n * Delete ledger entries for a thread. Called after a turn fully completes so\n * old entries don't bleed into the next turn's disambiguation.\n * Best-effort — never throws.\n */\nexport async function clearLedgerForThread(threadId: string): Promise<void> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `DELETE FROM agent_tool_ledger WHERE thread_id = ?`,\n args: [threadId],\n });\n } catch {\n // Best-effort.\n }\n}\n\nexport async function insertRun(\n id: string,\n threadId: string,\n turnId?: string,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `INSERT INTO agent_runs (id, thread_id, status, started_at, heartbeat_at, last_progress_at, turn_id) VALUES (?, ?, 'running', ?, ?, ?, ?)`,\n args: [id, threadId, now, now, now, turnId ?? id],\n });\n}\n\n/**\n * Atomically acquire a run lease for a thread. Succeeds (returns true) only\n * when no other run for the same thread is currently status='running' with a\n * fresh heartbeat. Works for both Postgres and SQLite: the stale-cutoff\n * comparison lets a dead producer's run be replaced without waiting for the\n * reaper, mirroring the logic in `reapIfStale`.\n *\n * Callers that win the claim then insert the run row normally; callers that\n * lose skip the run and return the existing active runId to the caller.\n */\nexport async function tryClaimRunSlot(\n threadId: string,\n maxStaleMs: number = RUN_STALE_MS,\n): Promise<{ claimed: boolean; activeRunId: string | null }> {\n await ensureRunTables();\n const client = getDbExec();\n const heartbeatCutoff = Date.now() - maxStaleMs;\n const { rows } = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE thread_id = ?\n AND status = 'running'\n AND COALESCE(heartbeat_at, started_at) >= ?\n ORDER BY started_at DESC LIMIT 1`,\n args: [threadId, heartbeatCutoff],\n });\n if (rows.length > 0) {\n const row = rows[0] as { id: string };\n return { claimed: false, activeRunId: row.id };\n }\n return { claimed: true, activeRunId: null };\n}\n\n/**\n * Record terminal failure classification for a run so cut-off / errored runs\n * can be surfaced for pattern analysis (see listErroredRuns). Best-effort —\n * never throws, since it runs on the completion path that must not fail the run.\n */\nexport async function setRunError(\n runId: string,\n errorCode: string | undefined,\n errorDetail: string | undefined,\n): Promise<void> {\n if (!errorCode && !errorDetail) return;\n try {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET error_code = ?, error_detail = ? WHERE id = ?`,\n args: [\n errorCode ?? null,\n errorDetail ? errorDetail.slice(0, 2000) : null,\n runId,\n ],\n });\n } catch {\n // Diagnostics are best-effort; never let them break completion.\n }\n}\n\n/** Update the run's liveness heartbeat. Called periodically by run-manager. */\nexport async function updateRunHeartbeat(runId: string): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET heartbeat_at = ? WHERE id = ?`,\n args: [Date.now(), runId],\n });\n}\n\n/**\n * Bump `last_progress_at` — call this whenever the agent actually emits an\n * event (token, tool call, message). Distinct from `heartbeat_at` so the\n * stuck-detector can tell \"process alive but nothing happening\" from\n * \"process dead.\" Callers should throttle (run-manager debounces to ~1/s).\n */\nexport async function bumpRunProgress(runId: string): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET last_progress_at = ? WHERE id = ?`,\n args: [Date.now(), runId],\n });\n}\n\n/**\n * If the given run is marked \"running\" in SQL but its heartbeat is stale\n * (producer likely crashed), flip it to \"errored\" so watchers stop waiting.\n * Returns true if the row was reaped.\n */\nexport async function reapIfStale(\n runId: string,\n maxStaleMs: number = RUN_STALE_MS,\n): Promise<boolean> {\n await ensureRunTables();\n const client = getDbExec();\n const completedAt = Date.now();\n const cutoff = completedAt - maxStaleMs;\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE id = ?\n AND status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ?`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n runId,\n cutoff,\n ],\n });\n const reaped = (rowsAffected ?? 0) > 0;\n if (reaped) {\n await safeAppendTerminalRunEvent(\n runId,\n STALE_RUN_ERROR_EVENT,\n \"reap-if-stale\",\n );\n }\n return reaped;\n}\n\nexport async function updateRunStatus(\n runId: string,\n status: \"completed\" | \"errored\" | \"aborted\",\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET status = ?, completed_at = ? WHERE id = ?`,\n args: [status, Date.now(), runId],\n });\n}\n\n/**\n * Conditional terminal status write: only updates if the row still belongs to\n * this run AND is still status='running'. Returns true when the update landed.\n *\n * This is the safe variant used by the producer's finally block so a zombie run\n * (reaped while executing) can never clobber the status written by the reaper\n * or a replacement run.\n */\nexport async function updateRunStatusIfRunning(\n runId: string,\n status: \"completed\" | \"errored\" | \"aborted\",\n): Promise<boolean> {\n await ensureRunTables();\n const client = getDbExec();\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs SET status = ?, completed_at = ? WHERE id = ? AND status = 'running'`,\n args: [status, Date.now(), runId],\n });\n return (rowsAffected ?? 0) > 0;\n}\n\n/** Read the current status of a run row. Returns null when the row is missing. */\nexport async function getRunStatus(runId: string): Promise<string | null> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT status FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return null;\n return String((rows[0] as { status: string }).status);\n}\n\nexport async function markRunAborted(\n runId: string,\n reason?: string,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET status = 'aborted', abort_reason = ?, completed_at = ? WHERE id = ?`,\n args: [reason ?? \"user\", Date.now(), runId],\n });\n await safeAppendTerminalRunEvent(runId, { type: \"done\" }, \"mark-aborted\");\n}\n\nexport async function isRunAborted(runId: string): Promise<boolean> {\n return (await getRunAbortState(runId)).aborted;\n}\n\nexport async function getRunAbortState(\n runId: string,\n): Promise<{ aborted: boolean; reason?: string }> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT status, abort_reason FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return { aborted: false };\n const row = rows[0] as { status: string; abort_reason?: string | null };\n if (row.status !== \"aborted\") return { aborted: false };\n return {\n aborted: true,\n ...(row.abort_reason ? { reason: row.abort_reason } : {}),\n };\n}\n\nexport async function insertRunEvent(\n runId: string,\n seq: number,\n eventData: string,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n // ON CONFLICT DO NOTHING: a (runId, seq) collision can happen on the\n // soft-timeout / terminal-event path where `pendingTerminalEvent` was\n // assigned a seq that later gets reused by an event pushed after it.\n // It can also race with `appendTerminalRunEvent` (max-seq + 1) when a\n // run aborts at the same time the producer emits its final event.\n // Treat the second write as a no-op so the run completes cleanly.\n await client.execute({\n sql: `INSERT INTO agent_run_events (run_id, seq, event_data) VALUES (?, ?, ?) ON CONFLICT (run_id, seq) DO NOTHING`,\n args: [runId, seq, eventData],\n });\n}\n\nexport async function getRunEventsSince(\n runId: string,\n fromSeq: number,\n): Promise<Array<{ seq: number; eventData: string }>> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT seq, event_data FROM agent_run_events WHERE run_id = ? AND seq >= ? ORDER BY seq ASC`,\n args: [runId, fromSeq],\n });\n return rows.map((r) => {\n const row = r as { seq: number | string; event_data: string };\n return { seq: Number(row.seq), eventData: row.event_data };\n });\n}\n\nexport async function getRunById(runId: string): Promise<{\n id: string;\n threadId: string;\n status: string;\n startedAt: number;\n} | null> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, status, started_at FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return null;\n const r = rows[0] as {\n id: string;\n thread_id: string;\n status: string;\n started_at: number | string;\n };\n return {\n id: r.id,\n threadId: r.thread_id,\n status: r.status,\n startedAt: Number(r.started_at),\n };\n}\n\nexport async function getRunByThread(\n threadId: string,\n options?: { includeTerminal?: boolean },\n): Promise<{\n id: string;\n threadId: string;\n turnId?: string | null;\n status: string;\n startedAt: number;\n heartbeatAt: number | null;\n completedAt: number | null;\n lastProgressAt: number | null;\n} | null> {\n await ensureRunTables();\n const client = getDbExec();\n const sql = options?.includeTerminal\n ? `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at FROM agent_runs WHERE thread_id = ? ORDER BY started_at DESC LIMIT 1`\n : `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at FROM agent_runs WHERE thread_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1`;\n const { rows } = await client.execute({ sql, args: [threadId] });\n if (rows.length === 0) return null;\n const r = rows[0] as {\n id: string;\n thread_id: string;\n turn_id?: string | null;\n status: string;\n started_at: number | string;\n heartbeat_at: number | string | null;\n completed_at: number | string | null;\n last_progress_at: number | string | null;\n };\n return {\n id: r.id,\n threadId: r.thread_id,\n turnId: r.turn_id ?? null,\n status: r.status,\n startedAt: Number(r.started_at),\n heartbeatAt: r.heartbeat_at == null ? null : Number(r.heartbeat_at),\n completedAt: r.completed_at == null ? null : Number(r.completed_at),\n lastProgressAt:\n r.last_progress_at == null ? null : Number(r.last_progress_at),\n };\n}\n\nexport interface AgentRunSummary {\n id: string;\n threadId: string;\n turnId: string | null;\n status: string;\n startedAt: number;\n heartbeatAt: number | null;\n completedAt: number | null;\n lastProgressAt: number | null;\n errorCode: string | null;\n abortReason: string | null;\n}\n\nexport async function listRunsForThread(\n threadId: string,\n options: { limit?: number } = {},\n): Promise<AgentRunSummary[]> {\n await ensureRunTables();\n const limit = Math.min(Math.max(options.limit ?? 10, 1), 50);\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at, error_code, abort_reason\n FROM agent_runs\n WHERE thread_id = ?\n ORDER BY started_at DESC\n LIMIT ?`,\n args: [threadId, limit],\n });\n return rows.map((r) => {\n const row = r as {\n id: string;\n thread_id: string;\n turn_id?: string | null;\n status: string;\n started_at: number | string;\n heartbeat_at?: number | string | null;\n completed_at?: number | string | null;\n last_progress_at?: number | string | null;\n error_code?: string | null;\n abort_reason?: string | null;\n };\n return {\n id: row.id,\n threadId: row.thread_id,\n turnId: row.turn_id ?? null,\n status: row.status,\n startedAt: Number(row.started_at),\n heartbeatAt: row.heartbeat_at == null ? null : Number(row.heartbeat_at),\n completedAt: row.completed_at == null ? null : Number(row.completed_at),\n lastProgressAt:\n row.last_progress_at == null ? null : Number(row.last_progress_at),\n errorCode: row.error_code ?? null,\n abortReason: row.abort_reason ?? null,\n };\n });\n}\n\n/**\n * Read the current logical turn's recorded events for a thread, parsed into\n * `AgentChatEvent`s in seq order, for per-turn tool-call journal classification\n * (see `tool-call-journal.ts`). Read-only and additive — reuses the existing\n * `agent_runs` / `agent_run_events` ledger with no schema change.\n *\n * A logical turn may span several continuation runs (each chunk is its own run\n * sharing one `turn_id`), so we union the events of every run that belongs to\n * the latest turn for this thread. Events are ordered by (started_at, seq) so\n * earlier chunks come before later ones and the positional `tool_start` →\n * `tool_done` matching in the classifier stays correct across chunk boundaries.\n *\n * Returns an empty array when the thread has no run yet or no parseable events.\n * Best-effort on parse: malformed ledger rows are skipped rather than thrown.\n */\nexport async function getCurrentTurnEventsForThread(\n threadId: string,\n): Promise<AgentChatEvent[]> {\n await ensureRunTables();\n const client = getDbExec();\n // Find the latest run for this thread (terminal or running) to learn the\n // logical turn id. The journal is consulted on the resume path, where the\n // just-interrupted run is typically already terminal.\n const latest = await client.execute({\n sql: `SELECT id, turn_id FROM agent_runs WHERE thread_id = ? ORDER BY started_at DESC LIMIT 1`,\n args: [threadId],\n });\n if (latest.rows.length === 0) return [];\n const latestRow = latest.rows[0] as { id: string; turn_id: string | null };\n const turnId = latestRow.turn_id ?? latestRow.id;\n // Gather every run that belongs to this logical turn, oldest chunk first, and\n // read their events in seq order. COALESCE(turn_id, id) folds older rows that\n // predate the turn_id backfill into a turn keyed by their own run id.\n const { rows } = await client.execute({\n sql: `SELECT e.event_data AS event_data\n FROM agent_run_events e\n JOIN agent_runs r ON r.id = e.run_id\n WHERE r.thread_id = ?\n AND COALESCE(r.turn_id, r.id) = ?\n ORDER BY r.started_at ASC, e.seq ASC`,\n args: [threadId, turnId],\n });\n const events: AgentChatEvent[] = [];\n for (const r of rows) {\n const raw = (r as { event_data?: string }).event_data;\n if (!raw) continue;\n try {\n events.push(JSON.parse(raw) as AgentChatEvent);\n } catch {\n // Skip malformed ledger rows — the journal is best-effort.\n }\n }\n return events;\n}\n\n/**\n * Expire any \"running\" rows whose heartbeat is stale — producer died.\n * Safe to call at server startup on multi-isolate deployments: only rows\n * without a fresh heartbeat get reaped, so runs owned by OTHER live\n * isolates (which keep heartbeating) are left alone.\n */\nexport async function reapAllStaleRuns(): Promise<number> {\n await ensureRunTables();\n const client = getDbExec();\n const heartbeatCutoff = Date.now() - RUN_STALE_MS;\n const stale = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ?`,\n args: [heartbeatCutoff],\n });\n const completedAt = Date.now();\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ?`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n heartbeatCutoff,\n ],\n });\n for (const row of stale.rows) {\n const id = (row as { id?: unknown }).id;\n if (typeof id === \"string\") {\n await safeAppendTerminalRunEvent(\n id,\n STALE_RUN_ERROR_EVENT,\n \"reap-all-stale\",\n );\n }\n }\n return rowsAffected ?? 0;\n}\n\n/** Delete old runs and expire stale \"running\" rows that haven't had activity\n * (e.g. worker crashed before updating status). Completed runs are pruned at\n * `olderThanMs`; errored/aborted runs are kept until `erroredOlderThanMs` (a\n * longer window, falling back to `olderThanMs`) so their event log survives\n * for cut-off pattern analysis via listErroredRuns. */\nexport async function cleanupOldRuns(\n olderThanMs: number,\n erroredOlderThanMs?: number,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const cutoff = Date.now() - olderThanMs;\n const erroredCutoff =\n Date.now() - Math.max(erroredOlderThanMs ?? 0, olderThanMs);\n // Expire stale running rows on the absolute-age threshold — safety net\n // for runs that never received a heartbeat (very old deployments). The\n // SELECT covers BOTH UPDATE conditions so the terminal-event-append loop\n // below catches every row we're about to flip — a 24h-old row with a\n // somehow-fresh heartbeat would slip past a heartbeat-only SELECT.\n const heartbeatCutoff = Date.now() - RUN_STALE_MS;\n const stale = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE status = 'running'\n AND (\n COALESCE(heartbeat_at, started_at) < ?\n OR started_at < ?\n )`,\n args: [heartbeatCutoff, cutoff],\n });\n const completedAt = Date.now();\n await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running' AND started_at < ?`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n cutoff,\n ],\n });\n // Also expire runs whose heartbeat is stale — producer has died.\n await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ?`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n heartbeatCutoff,\n ],\n });\n for (const row of stale.rows) {\n const id = (row as { id?: unknown }).id;\n if (typeof id === \"string\") {\n await safeAppendTerminalRunEvent(\n id,\n STALE_RUN_ERROR_EVENT,\n \"cleanup-old-runs\",\n );\n }\n }\n // Delete events for old terminal runs. Completed runs prune at `cutoff`;\n // errored/aborted runs are retained until the (longer) `erroredCutoff`.\n await client.execute({\n sql: `DELETE FROM agent_run_events WHERE run_id IN (\n SELECT id FROM agent_runs\n WHERE (status = 'completed' AND completed_at < ?)\n OR (status IN ('errored', 'aborted') AND completed_at < ?)\n )`,\n args: [cutoff, erroredCutoff],\n });\n await client.execute({\n sql: `DELETE FROM agent_runs\n WHERE (status = 'completed' AND completed_at < ?)\n OR (status IN ('errored', 'aborted') AND completed_at < ?)`,\n args: [cutoff, erroredCutoff],\n });\n}\n\n/**\n * List recent errored/aborted runs for cut-off pattern analysis. Read-only,\n * bounded, and ordered newest-first. Surfaced via the list-errored-runs action\n * so the team can see why chats are failing (terminal error code, duration,\n * turn linkage) instead of discovering it ad hoc.\n */\nexport async function listErroredRuns(options?: {\n limit?: number;\n sinceMs?: number;\n}): Promise<\n Array<{\n id: string;\n threadId: string;\n turnId: string | null;\n status: string;\n errorCode: string | null;\n errorDetail: string | null;\n startedAt: number;\n completedAt: number | null;\n durationMs: number | null;\n }>\n> {\n await ensureRunTables();\n const client = getDbExec();\n const limit = Math.min(Math.max(Math.floor(options?.limit ?? 100), 1), 1000);\n const since =\n options?.sinceMs && options.sinceMs > 0 ? Date.now() - options.sinceMs : 0;\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, turn_id, status, error_code, error_detail, started_at, completed_at\n FROM agent_runs\n WHERE status IN ('errored', 'aborted')\n AND COALESCE(completed_at, started_at) >= ?\n ORDER BY COALESCE(completed_at, started_at) DESC\n LIMIT ${limit}`,\n args: [since],\n });\n return rows.map((r) => {\n const row = r as {\n id: string;\n thread_id: string;\n turn_id: string | null;\n status: string;\n error_code: string | null;\n error_detail: string | null;\n started_at: number | string;\n completed_at: number | string | null;\n };\n const startedAt = Number(row.started_at);\n const completedAt =\n row.completed_at == null ? null : Number(row.completed_at);\n return {\n id: row.id,\n threadId: row.thread_id,\n turnId: row.turn_id ?? null,\n status: row.status,\n errorCode: row.error_code ?? null,\n errorDetail: row.error_detail ?? null,\n startedAt,\n completedAt,\n durationMs: completedAt == null ? null : completedAt - startedAt,\n };\n });\n}\n\n/**\n * Idempotently append a terminal event to a run's event stream. No-op if the\n * stream already ends in a terminal event. Used by reapers AND by SSE\n * reconnect paths that discover an `errored` run row with no terminal event\n * (e.g. an earlier reaper's silent `.catch(() => {})` swallowed the append).\n *\n * Persisting from the reconnect path is what keeps the system self-healing:\n * subsequent reconnects replay the proper terminal event from SQL instead of\n * synthesizing a fresh one each time.\n */\nexport async function ensureTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n): Promise<void> {\n return appendTerminalRunEvent(runId, event);\n}\n\n/**\n * Append a terminal run event, retrying once on failure and reporting to\n * Sentry if both attempts fail. Background reaper paths can't surface errors\n * to a user, but they MUST eventually persist a terminal event — losing it\n * leaves reconnecting clients staring at a bare `status='errored'` row with\n * no payload to render. The previous `.catch(() => {})` callsites silently\n * dropped transient SQL blips and produced exactly that bug. Never throws.\n */\nasync function safeAppendTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n source: string,\n): Promise<void> {\n let firstError: unknown;\n try {\n await appendTerminalRunEvent(runId, event);\n return;\n } catch (err) {\n firstError = err;\n }\n // Brief backoff — most \"transient\" SQL failures (connection blip, lock\n // contention) clear within a couple hundred ms.\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n try {\n await appendTerminalRunEvent(runId, event);\n } catch (retryErr) {\n captureError(retryErr, {\n tags: {\n component: \"agent-run-store\",\n operation: \"append-terminal-event\",\n source,\n },\n extra: {\n runId,\n eventType: typeof event.type === \"string\" ? event.type : \"(unknown)\",\n firstError:\n firstError instanceof Error ? firstError.message : String(firstError),\n },\n });\n }\n}\n\nasync function appendTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT seq, event_data FROM agent_run_events WHERE run_id = ? ORDER BY seq DESC LIMIT 1`,\n args: [runId],\n });\n const last = rows[0] as\n | { seq?: number | string; event_data?: string }\n | undefined;\n if (last?.event_data) {\n try {\n const parsed = JSON.parse(last.event_data);\n if (\n parsed?.type === \"done\" ||\n parsed?.type === \"error\" ||\n parsed?.type === \"missing_api_key\" ||\n parsed?.type === \"loop_limit\" ||\n parsed?.type === \"auto_continue\"\n ) {\n return;\n }\n } catch {\n // Ignore malformed rows and append the terminal event.\n }\n }\n const nextSeq = last ? Number(last.seq ?? -1) + 1 : 0;\n await client.execute({\n sql: `INSERT INTO agent_run_events (run_id, seq, event_data) VALUES (?, ?, ?) ON CONFLICT (run_id, seq) DO NOTHING`,\n args: [runId, nextSeq, JSON.stringify(event)],\n });\n}\n"]}
1
+ {"version":3,"file":"run-store.js","sourceRoot":"","sources":["../../src/agent/run-store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG1D,IAAI,YAAuC,CAAC;AAE5C;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC;AAEnC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAE9C,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,IAAI,EAAE,OAAO;IACb,KAAK,EACH,qHAAqH;IACvH,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,IAAI;IACjB,OAAO,EACL,gIAAgI;CAC1H,CAAC;AAEX,KAAK,UAAU,eAAe;IAC5B,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,MAAM,CAAC,OAAO,CAAC;;;;;;uBAMJ,OAAO,EAAE;yBACP,OAAO,EAAE;yBACT,OAAO,EAAE;6BACL,OAAO,EAAE;;;;;;OAM/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;YAC3C,IACE,MAAM,EAAE,IAAI,KAAK,MAAM;gBACvB,MAAM,EAAE,IAAI,KAAK,OAAO;gBACxB,MAAM,EAAE,IAAI,KAAK,iBAAiB;gBAClC,MAAM,EAAE,IAAI,KAAK,YAAY;gBAC7B,MAAM,EAAE,IAAI,KAAK,eAAe,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,uDAAuD;QACzD,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtD,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE,8GAA8G;QACnH,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;KAC9C,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * SQL persistence for agent runs and events.\n * Enables cross-isolate access on Cloudflare Workers and\n * reliable reconnection after page refreshes.\n */\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport { captureError } from \"../server/capture-error.js\";\nimport type { AgentChatEvent } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\n/**\n * Max time without a heartbeat before a \"running\" run is considered dead.\n * The run-manager heartbeats every 1.5s, so 15s tolerates ~9 missed writes.\n * Widened from 6s to absorb real-world DB latency spikes and GC pauses that\n * caused false-positive reaps: a live run whose heartbeat lagged 6s+ would be\n * reaped and a zombie would keep running, eventually clobbering the new row.\n */\nexport const RUN_STALE_MS = 15_000;\n\n/**\n * Stale window for runs dispatched into a Netlify background function\n * (`dispatch_mode = 'background'`). The design doc flags the 15s reaper vs a\n * background cold-start as the #1 false-failure risk: the foreground POST\n * inserts the `running` row, then `fireInternalDispatch` returns 202 and the\n * background function may take >15s to cold-start and emit its first heartbeat.\n * With the normal 15s window the reaper would falsely kill that freshly-\n * inserted-but-not-yet-heartbeaten row. 90s tolerates a slow background\n * cold-start while still reaping a genuinely dead background worker promptly.\n *\n * Only applied to rows explicitly marked background-dispatched; ordinary\n * foreground runs keep the tight 15s window unchanged.\n */\nexport const BACKGROUND_RUN_STALE_MS = 90_000;\n\nexport const STALE_RUN_ERROR_EVENT = {\n type: \"error\",\n error:\n \"The agent stopped before it could finish. It may have hit a server timeout or the worker may have been interrupted.\",\n errorCode: \"stale_run\",\n recoverable: true,\n details:\n \"The run heartbeat stopped while the run was still marked running. Partial output and tool calls were preserved when available.\",\n} as const;\n\nasync function ensureRunTables(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_runs (\n id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'running',\n abort_reason TEXT,\n started_at ${intType()} NOT NULL,\n completed_at ${intType()},\n heartbeat_at ${intType()},\n last_progress_at ${intType()},\n turn_id TEXT,\n error_code TEXT,\n error_detail TEXT,\n dispatch_mode TEXT\n )\n `);\n // Backfill heartbeat_at on older deployments.\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS heartbeat_at ${intType()}`,\n );\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS abort_reason TEXT`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN heartbeat_at ${intType()}`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n try {\n if (!isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN abort_reason TEXT`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n // Backfill last_progress_at — this is distinct from heartbeat_at.\n // heartbeat_at = \"the producer process is alive\" (bumped on a timer).\n // last_progress_at = \"the agent is actually emitting events\" (bumped on\n // each emit). The gap between them is the stuck-detector signal.\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS last_progress_at ${intType()}`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN last_progress_at ${intType()}`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n // Backfill turn_id / error_code / error_detail.\n // turn_id = stable identity for one logical assistant turn that may\n // span several continuation runs, so the durable record\n // can be folded across runs instead of dropped per-run.\n // error_code / error_detail = terminal failure classification captured\n // at completion so errored/cut-off runs are queryable for\n // pattern analysis (see listErroredRuns).\n // dispatch_mode marks how a run was started: NULL/\"foreground\" for the\n // normal synchronous path, \"background\" for a run dispatched into a\n // Netlify background function. The reaper/claim widen the stale window\n // for background rows so a slow cold-start isn't falsely reaped.\n for (const col of [\n \"turn_id\",\n \"error_code\",\n \"error_detail\",\n \"dispatch_mode\",\n ] as const) {\n try {\n if (isPostgres()) {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN IF NOT EXISTS ${col} TEXT`,\n );\n } else {\n await client.execute(\n `ALTER TABLE agent_runs ADD COLUMN ${col} TEXT`,\n );\n }\n } catch {\n // Column already exists — ignore\n }\n }\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_run_events (\n run_id TEXT NOT NULL,\n seq ${intType()} NOT NULL,\n event_data TEXT NOT NULL,\n PRIMARY KEY (run_id, seq)\n )\n `);\n // Tool-call result ledger: persists the outcome of write tool calls that\n // completed AFTER their chunk was abandoned (zombie completions). A\n // resumed continuation can recover the real result by matching\n // thread_id + tool_key (name:stableInputHash) instead of re-executing\n // the side effect. Entries are scoped to the thread and expire with it.\n await client.execute(`\n CREATE TABLE IF NOT EXISTS agent_tool_ledger (\n thread_id TEXT NOT NULL,\n tool_key TEXT NOT NULL,\n result_summary TEXT NOT NULL,\n completed_at ${intType()} NOT NULL,\n PRIMARY KEY (thread_id, tool_key)\n )\n `);\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\n// ─── Tool-call result ledger ─────────────────────────────────────────────────\n//\n// When the run-level abort signal fires (soft timeout / user cancel) while a\n// write tool is in-flight, `Promise.race` abandons the call — but the action's\n// Promise continues running in the background (a \"zombie\"). If the zombie\n// resolves before the continuation's next tool dispatch, we record the result\n// here so the continuation can recover it without re-executing the side effect.\n//\n// Keyed by (thread_id, tool_key) where tool_key = \"<toolName>:<stableJsonHash>\".\n// The write is fire-and-forget from the hot path; reads are synchronous look-\n// ups at the start of each write-tool dispatch in the continuation.\n\n/** Max length for a persisted result summary (8 KB). */\nconst LEDGER_RESULT_MAX_CHARS = 8_000;\n\n/**\n * Persist a zombie tool-call completion to the ledger. Called by the detached\n * promise continuation after `Promise.race` abandons it. Best-effort — never\n * throws so a ledger write failure doesn't break any caller.\n */\nexport async function writeLedgerEntry(\n threadId: string,\n toolKey: string,\n resultSummary: string,\n): Promise<void> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n const capped =\n resultSummary.length > LEDGER_RESULT_MAX_CHARS\n ? resultSummary.slice(0, LEDGER_RESULT_MAX_CHARS) +\n `\\n...[ledger truncated at ${LEDGER_RESULT_MAX_CHARS} chars]`\n : resultSummary;\n await client.execute({\n sql: `INSERT INTO agent_tool_ledger (thread_id, tool_key, result_summary, completed_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT (thread_id, tool_key) DO UPDATE SET\n result_summary = excluded.result_summary,\n completed_at = excluded.completed_at`,\n args: [threadId, toolKey, capped, Date.now()],\n });\n } catch {\n // Ledger is best-effort; never surface failures to the caller.\n }\n}\n\n/**\n * Look up a prior zombie completion for this thread + tool key. Returns the\n * persisted result summary, or `null` when no entry exists.\n */\nexport async function readLedgerEntry(\n threadId: string,\n toolKey: string,\n): Promise<string | null> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT result_summary FROM agent_tool_ledger WHERE thread_id = ? AND tool_key = ?`,\n args: [threadId, toolKey],\n });\n if (rows.length === 0) return null;\n const row = rows[0] as { result_summary: string };\n return row.result_summary;\n } catch {\n return null;\n }\n}\n\n/**\n * Delete ledger entries for a thread. Called after a turn fully completes so\n * old entries don't bleed into the next turn's disambiguation.\n * Best-effort — never throws.\n */\nexport async function clearLedgerForThread(threadId: string): Promise<void> {\n try {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `DELETE FROM agent_tool_ledger WHERE thread_id = ?`,\n args: [threadId],\n });\n } catch {\n // Best-effort.\n }\n}\n\nexport async function insertRun(\n id: string,\n threadId: string,\n turnId?: string,\n options?: { dispatchMode?: \"foreground\" | \"background\" },\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `INSERT INTO agent_runs (id, thread_id, status, started_at, heartbeat_at, last_progress_at, turn_id, dispatch_mode) VALUES (?, ?, 'running', ?, ?, ?, ?, ?)`,\n args: [\n id,\n threadId,\n now,\n now,\n now,\n turnId ?? id,\n options?.dispatchMode ?? null,\n ],\n });\n}\n\n/**\n * SQL fragment that resolves the per-row stale cutoff. Background-dispatched\n * runs (`dispatch_mode` starting with `background`) tolerate a much longer gap\n * without a heartbeat (slow Netlify background-function cold-start) before being\n * reaped; every other run keeps the tight 15s window. The bound `now` is\n * subtracted by the resolved window so the comparison is\n * `COALESCE(heartbeat_at, started_at) < (now - window)`.\n *\n * `dispatch_mode` is one of NULL/\"foreground\" (normal sync path), \"background\"\n * (foreground inserted the row for a background dispatch), or\n * \"background-processing\" (the background worker claimed it). Both background\n * states get the wider window via a LIKE-prefix match.\n */\nfunction backgroundAwareStaleCutoffSql(): string {\n return `(? - CASE WHEN dispatch_mode LIKE 'background%' THEN ${BACKGROUND_RUN_STALE_MS} ELSE ${RUN_STALE_MS} END)`;\n}\n\n/**\n * Atomically claim a background-dispatched run for processing. The foreground\n * POST inserts the run row with `dispatch_mode = 'background'`; the FIRST\n * delivery of the background dispatch flips it to `background-processing` and\n * wins the claim. A duplicate Netlify delivery (background functions can be\n * retried) sees `background-processing` and loses, so it no-ops — mirroring\n * `claimAgentTeamRun` returning null. Returns true when this caller won.\n *\n * Idempotent and conditional: the WHERE clause only matches the unclaimed\n * `background` state AND a still-running row, so a reaped/terminal row can't be\n * re-claimed.\n */\nexport async function claimBackgroundRun(runId: string): Promise<boolean> {\n await ensureRunTables();\n const client = getDbExec();\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs\n SET dispatch_mode = 'background-processing'\n WHERE id = ?\n AND status = 'running'\n AND dispatch_mode = 'background'`,\n args: [runId],\n });\n return (rowsAffected ?? 0) > 0;\n}\n\n/**\n * Atomically acquire a run lease for a thread. Succeeds (returns true) only\n * when no other run for the same thread is currently status='running' with a\n * fresh heartbeat. Works for both Postgres and SQLite: the stale-cutoff\n * comparison lets a dead producer's run be replaced without waiting for the\n * reaper, mirroring the logic in `reapIfStale`.\n *\n * Callers that win the claim then insert the run row normally; callers that\n * lose skip the run and return the existing active runId to the caller.\n */\nexport async function tryClaimRunSlot(\n threadId: string,\n maxStaleMs?: number,\n): Promise<{ claimed: boolean; activeRunId: string | null }> {\n await ensureRunTables();\n const client = getDbExec();\n const now = Date.now();\n // Default: per-row background-aware window so a live background run (which can\n // legitimately go >15s between heartbeats during a cold-start) isn't seen as\n // \"free\" and double-claimed by a racing foreground POST. An explicit\n // `maxStaleMs` override keeps a flat window for callers that want one.\n if (typeof maxStaleMs === \"number\") {\n const heartbeatCutoff = now - maxStaleMs;\n const { rows } = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE thread_id = ?\n AND status = 'running'\n AND COALESCE(heartbeat_at, started_at) >= ?\n ORDER BY started_at DESC LIMIT 1`,\n args: [threadId, heartbeatCutoff],\n });\n if (rows.length > 0) {\n return { claimed: false, activeRunId: (rows[0] as { id: string }).id };\n }\n return { claimed: true, activeRunId: null };\n }\n const { rows } = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE thread_id = ?\n AND status = 'running'\n AND COALESCE(heartbeat_at, started_at) >= ${backgroundAwareStaleCutoffSql()}\n ORDER BY started_at DESC LIMIT 1`,\n args: [threadId, now],\n });\n if (rows.length > 0) {\n const row = rows[0] as { id: string };\n return { claimed: false, activeRunId: row.id };\n }\n return { claimed: true, activeRunId: null };\n}\n\n/**\n * Record terminal failure classification for a run so cut-off / errored runs\n * can be surfaced for pattern analysis (see listErroredRuns). Best-effort —\n * never throws, since it runs on the completion path that must not fail the run.\n */\nexport async function setRunError(\n runId: string,\n errorCode: string | undefined,\n errorDetail: string | undefined,\n): Promise<void> {\n if (!errorCode && !errorDetail) return;\n try {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET error_code = ?, error_detail = ? WHERE id = ?`,\n args: [\n errorCode ?? null,\n errorDetail ? errorDetail.slice(0, 2000) : null,\n runId,\n ],\n });\n } catch {\n // Diagnostics are best-effort; never let them break completion.\n }\n}\n\n/** Update the run's liveness heartbeat. Called periodically by run-manager. */\nexport async function updateRunHeartbeat(runId: string): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET heartbeat_at = ? WHERE id = ?`,\n args: [Date.now(), runId],\n });\n}\n\n/**\n * Bump `last_progress_at` — call this whenever the agent actually emits an\n * event (token, tool call, message). Distinct from `heartbeat_at` so the\n * stuck-detector can tell \"process alive but nothing happening\" from\n * \"process dead.\" Callers should throttle (run-manager debounces to ~1/s).\n */\nexport async function bumpRunProgress(runId: string): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET last_progress_at = ? WHERE id = ?`,\n args: [Date.now(), runId],\n });\n}\n\n/**\n * If the given run is marked \"running\" in SQL but its heartbeat is stale\n * (producer likely crashed), flip it to \"errored\" so watchers stop waiting.\n * Returns true if the row was reaped.\n */\nexport async function reapIfStale(\n runId: string,\n maxStaleMs?: number,\n): Promise<boolean> {\n await ensureRunTables();\n const client = getDbExec();\n const completedAt = Date.now();\n // Background-dispatched runs get the wider stale window so a slow cold-start\n // isn't reaped; foreground runs keep the tight 15s window. An explicit\n // override forces a flat window for callers that want one.\n const staleClause =\n typeof maxStaleMs === \"number\"\n ? `COALESCE(heartbeat_at, started_at) < ?`\n : `COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`;\n const staleArgs =\n typeof maxStaleMs === \"number\" ? [completedAt - maxStaleMs] : [completedAt];\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE id = ?\n AND status = 'running'\n AND ${staleClause}`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n runId,\n ...staleArgs,\n ],\n });\n const reaped = (rowsAffected ?? 0) > 0;\n if (reaped) {\n await safeAppendTerminalRunEvent(\n runId,\n STALE_RUN_ERROR_EVENT,\n \"reap-if-stale\",\n );\n }\n return reaped;\n}\n\nexport async function updateRunStatus(\n runId: string,\n status: \"completed\" | \"errored\" | \"aborted\",\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET status = ?, completed_at = ? WHERE id = ?`,\n args: [status, Date.now(), runId],\n });\n}\n\n/**\n * Conditional terminal status write: only updates if the row still belongs to\n * this run AND is still status='running'. Returns true when the update landed.\n *\n * This is the safe variant used by the producer's finally block so a zombie run\n * (reaped while executing) can never clobber the status written by the reaper\n * or a replacement run.\n */\nexport async function updateRunStatusIfRunning(\n runId: string,\n status: \"completed\" | \"errored\" | \"aborted\",\n): Promise<boolean> {\n await ensureRunTables();\n const client = getDbExec();\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs SET status = ?, completed_at = ? WHERE id = ? AND status = 'running'`,\n args: [status, Date.now(), runId],\n });\n return (rowsAffected ?? 0) > 0;\n}\n\n/** Read the current status of a run row. Returns null when the row is missing. */\nexport async function getRunStatus(runId: string): Promise<string | null> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT status FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return null;\n return String((rows[0] as { status: string }).status);\n}\n\nexport async function markRunAborted(\n runId: string,\n reason?: string,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n await client.execute({\n sql: `UPDATE agent_runs SET status = 'aborted', abort_reason = ?, completed_at = ? WHERE id = ?`,\n args: [reason ?? \"user\", Date.now(), runId],\n });\n await safeAppendTerminalRunEvent(runId, { type: \"done\" }, \"mark-aborted\");\n}\n\nexport async function isRunAborted(runId: string): Promise<boolean> {\n return (await getRunAbortState(runId)).aborted;\n}\n\nexport async function getRunAbortState(\n runId: string,\n): Promise<{ aborted: boolean; reason?: string }> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT status, abort_reason FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return { aborted: false };\n const row = rows[0] as { status: string; abort_reason?: string | null };\n if (row.status !== \"aborted\") return { aborted: false };\n return {\n aborted: true,\n ...(row.abort_reason ? { reason: row.abort_reason } : {}),\n };\n}\n\nexport async function insertRunEvent(\n runId: string,\n seq: number,\n eventData: string,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n // ON CONFLICT DO NOTHING: a (runId, seq) collision can happen on the\n // soft-timeout / terminal-event path where `pendingTerminalEvent` was\n // assigned a seq that later gets reused by an event pushed after it.\n // It can also race with `appendTerminalRunEvent` (max-seq + 1) when a\n // run aborts at the same time the producer emits its final event.\n // Treat the second write as a no-op so the run completes cleanly.\n await client.execute({\n sql: `INSERT INTO agent_run_events (run_id, seq, event_data) VALUES (?, ?, ?) ON CONFLICT (run_id, seq) DO NOTHING`,\n args: [runId, seq, eventData],\n });\n}\n\nexport async function getRunEventsSince(\n runId: string,\n fromSeq: number,\n): Promise<Array<{ seq: number; eventData: string }>> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT seq, event_data FROM agent_run_events WHERE run_id = ? AND seq >= ? ORDER BY seq ASC`,\n args: [runId, fromSeq],\n });\n return rows.map((r) => {\n const row = r as { seq: number | string; event_data: string };\n return { seq: Number(row.seq), eventData: row.event_data };\n });\n}\n\nexport async function getRunById(runId: string): Promise<{\n id: string;\n threadId: string;\n status: string;\n startedAt: number;\n} | null> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, status, started_at FROM agent_runs WHERE id = ?`,\n args: [runId],\n });\n if (rows.length === 0) return null;\n const r = rows[0] as {\n id: string;\n thread_id: string;\n status: string;\n started_at: number | string;\n };\n return {\n id: r.id,\n threadId: r.thread_id,\n status: r.status,\n startedAt: Number(r.started_at),\n };\n}\n\nexport async function getRunByThread(\n threadId: string,\n options?: { includeTerminal?: boolean },\n): Promise<{\n id: string;\n threadId: string;\n turnId?: string | null;\n status: string;\n startedAt: number;\n heartbeatAt: number | null;\n completedAt: number | null;\n lastProgressAt: number | null;\n} | null> {\n await ensureRunTables();\n const client = getDbExec();\n const sql = options?.includeTerminal\n ? `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at FROM agent_runs WHERE thread_id = ? ORDER BY started_at DESC LIMIT 1`\n : `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at FROM agent_runs WHERE thread_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1`;\n const { rows } = await client.execute({ sql, args: [threadId] });\n if (rows.length === 0) return null;\n const r = rows[0] as {\n id: string;\n thread_id: string;\n turn_id?: string | null;\n status: string;\n started_at: number | string;\n heartbeat_at: number | string | null;\n completed_at: number | string | null;\n last_progress_at: number | string | null;\n };\n return {\n id: r.id,\n threadId: r.thread_id,\n turnId: r.turn_id ?? null,\n status: r.status,\n startedAt: Number(r.started_at),\n heartbeatAt: r.heartbeat_at == null ? null : Number(r.heartbeat_at),\n completedAt: r.completed_at == null ? null : Number(r.completed_at),\n lastProgressAt:\n r.last_progress_at == null ? null : Number(r.last_progress_at),\n };\n}\n\nexport interface AgentRunSummary {\n id: string;\n threadId: string;\n turnId: string | null;\n status: string;\n startedAt: number;\n heartbeatAt: number | null;\n completedAt: number | null;\n lastProgressAt: number | null;\n errorCode: string | null;\n abortReason: string | null;\n}\n\nexport async function listRunsForThread(\n threadId: string,\n options: { limit?: number } = {},\n): Promise<AgentRunSummary[]> {\n await ensureRunTables();\n const limit = Math.min(Math.max(options.limit ?? 10, 1), 50);\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, turn_id, status, started_at, heartbeat_at, completed_at, last_progress_at, error_code, abort_reason\n FROM agent_runs\n WHERE thread_id = ?\n ORDER BY started_at DESC\n LIMIT ?`,\n args: [threadId, limit],\n });\n return rows.map((r) => {\n const row = r as {\n id: string;\n thread_id: string;\n turn_id?: string | null;\n status: string;\n started_at: number | string;\n heartbeat_at?: number | string | null;\n completed_at?: number | string | null;\n last_progress_at?: number | string | null;\n error_code?: string | null;\n abort_reason?: string | null;\n };\n return {\n id: row.id,\n threadId: row.thread_id,\n turnId: row.turn_id ?? null,\n status: row.status,\n startedAt: Number(row.started_at),\n heartbeatAt: row.heartbeat_at == null ? null : Number(row.heartbeat_at),\n completedAt: row.completed_at == null ? null : Number(row.completed_at),\n lastProgressAt:\n row.last_progress_at == null ? null : Number(row.last_progress_at),\n errorCode: row.error_code ?? null,\n abortReason: row.abort_reason ?? null,\n };\n });\n}\n\n/**\n * Read the current logical turn's recorded events for a thread, parsed into\n * `AgentChatEvent`s in seq order, for per-turn tool-call journal classification\n * (see `tool-call-journal.ts`). Read-only and additive — reuses the existing\n * `agent_runs` / `agent_run_events` ledger with no schema change.\n *\n * A logical turn may span several continuation runs (each chunk is its own run\n * sharing one `turn_id`), so we union the events of every run that belongs to\n * the latest turn for this thread. Events are ordered by (started_at, seq) so\n * earlier chunks come before later ones and the positional `tool_start` →\n * `tool_done` matching in the classifier stays correct across chunk boundaries.\n *\n * Returns an empty array when the thread has no run yet or no parseable events.\n * Best-effort on parse: malformed ledger rows are skipped rather than thrown.\n */\nexport async function getCurrentTurnEventsForThread(\n threadId: string,\n): Promise<AgentChatEvent[]> {\n await ensureRunTables();\n const client = getDbExec();\n // Find the latest run for this thread (terminal or running) to learn the\n // logical turn id. The journal is consulted on the resume path, where the\n // just-interrupted run is typically already terminal.\n const latest = await client.execute({\n sql: `SELECT id, turn_id FROM agent_runs WHERE thread_id = ? ORDER BY started_at DESC LIMIT 1`,\n args: [threadId],\n });\n if (latest.rows.length === 0) return [];\n const latestRow = latest.rows[0] as { id: string; turn_id: string | null };\n const turnId = latestRow.turn_id ?? latestRow.id;\n // Gather every run that belongs to this logical turn, oldest chunk first, and\n // read their events in seq order. COALESCE(turn_id, id) folds older rows that\n // predate the turn_id backfill into a turn keyed by their own run id.\n const { rows } = await client.execute({\n sql: `SELECT e.event_data AS event_data\n FROM agent_run_events e\n JOIN agent_runs r ON r.id = e.run_id\n WHERE r.thread_id = ?\n AND COALESCE(r.turn_id, r.id) = ?\n ORDER BY r.started_at ASC, e.seq ASC`,\n args: [threadId, turnId],\n });\n const events: AgentChatEvent[] = [];\n for (const r of rows) {\n const raw = (r as { event_data?: string }).event_data;\n if (!raw) continue;\n try {\n events.push(JSON.parse(raw) as AgentChatEvent);\n } catch {\n // Skip malformed ledger rows — the journal is best-effort.\n }\n }\n return events;\n}\n\n/**\n * Expire any \"running\" rows whose heartbeat is stale — producer died.\n * Safe to call at server startup on multi-isolate deployments: only rows\n * without a fresh heartbeat get reaped, so runs owned by OTHER live\n * isolates (which keep heartbeating) are left alone.\n */\nexport async function reapAllStaleRuns(): Promise<number> {\n await ensureRunTables();\n const client = getDbExec();\n const now = Date.now();\n // Background-dispatched runs use the wider window; everything else 15s.\n const stale = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,\n args: [now],\n });\n const completedAt = Date.now();\n const { rowsAffected } = await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n completedAt,\n ],\n });\n for (const row of stale.rows) {\n const id = (row as { id?: unknown }).id;\n if (typeof id === \"string\") {\n await safeAppendTerminalRunEvent(\n id,\n STALE_RUN_ERROR_EVENT,\n \"reap-all-stale\",\n );\n }\n }\n return rowsAffected ?? 0;\n}\n\n/** Delete old runs and expire stale \"running\" rows that haven't had activity\n * (e.g. worker crashed before updating status). Completed runs are pruned at\n * `olderThanMs`; errored/aborted runs are kept until `erroredOlderThanMs` (a\n * longer window, falling back to `olderThanMs`) so their event log survives\n * for cut-off pattern analysis via listErroredRuns. */\nexport async function cleanupOldRuns(\n olderThanMs: number,\n erroredOlderThanMs?: number,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const cutoff = Date.now() - olderThanMs;\n const erroredCutoff =\n Date.now() - Math.max(erroredOlderThanMs ?? 0, olderThanMs);\n // Expire stale running rows on the absolute-age threshold — safety net\n // for runs that never received a heartbeat (very old deployments). The\n // SELECT covers BOTH UPDATE conditions so the terminal-event-append loop\n // below catches every row we're about to flip — a 24h-old row with a\n // somehow-fresh heartbeat would slip past a heartbeat-only SELECT.\n const now = Date.now();\n const stale = await client.execute({\n sql: `SELECT id FROM agent_runs\n WHERE status = 'running'\n AND (\n COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}\n OR started_at < ?\n )`,\n args: [now, cutoff],\n });\n const completedAt = Date.now();\n await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running' AND started_at < ?`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n cutoff,\n ],\n });\n // Also expire runs whose heartbeat is stale — producer has died. Uses the\n // background-aware window so a slow background cold-start isn't reaped early.\n await client.execute({\n sql: `UPDATE agent_runs\n SET status = 'errored',\n completed_at = ?,\n error_code = ?,\n error_detail = ?\n WHERE status = 'running'\n AND COALESCE(heartbeat_at, started_at) < ${backgroundAwareStaleCutoffSql()}`,\n args: [\n completedAt,\n STALE_RUN_ERROR_EVENT.errorCode,\n STALE_RUN_ERROR_EVENT.details,\n completedAt,\n ],\n });\n for (const row of stale.rows) {\n const id = (row as { id?: unknown }).id;\n if (typeof id === \"string\") {\n await safeAppendTerminalRunEvent(\n id,\n STALE_RUN_ERROR_EVENT,\n \"cleanup-old-runs\",\n );\n }\n }\n // Delete events for old terminal runs. Completed runs prune at `cutoff`;\n // errored/aborted runs are retained until the (longer) `erroredCutoff`.\n await client.execute({\n sql: `DELETE FROM agent_run_events WHERE run_id IN (\n SELECT id FROM agent_runs\n WHERE (status = 'completed' AND completed_at < ?)\n OR (status IN ('errored', 'aborted') AND completed_at < ?)\n )`,\n args: [cutoff, erroredCutoff],\n });\n await client.execute({\n sql: `DELETE FROM agent_runs\n WHERE (status = 'completed' AND completed_at < ?)\n OR (status IN ('errored', 'aborted') AND completed_at < ?)`,\n args: [cutoff, erroredCutoff],\n });\n}\n\n/**\n * List recent errored/aborted runs for cut-off pattern analysis. Read-only,\n * bounded, and ordered newest-first. Surfaced via the list-errored-runs action\n * so the team can see why chats are failing (terminal error code, duration,\n * turn linkage) instead of discovering it ad hoc.\n */\nexport async function listErroredRuns(options?: {\n limit?: number;\n sinceMs?: number;\n}): Promise<\n Array<{\n id: string;\n threadId: string;\n turnId: string | null;\n status: string;\n errorCode: string | null;\n errorDetail: string | null;\n startedAt: number;\n completedAt: number | null;\n durationMs: number | null;\n }>\n> {\n await ensureRunTables();\n const client = getDbExec();\n const limit = Math.min(Math.max(Math.floor(options?.limit ?? 100), 1), 1000);\n const since =\n options?.sinceMs && options.sinceMs > 0 ? Date.now() - options.sinceMs : 0;\n const { rows } = await client.execute({\n sql: `SELECT id, thread_id, turn_id, status, error_code, error_detail, started_at, completed_at\n FROM agent_runs\n WHERE status IN ('errored', 'aborted')\n AND COALESCE(completed_at, started_at) >= ?\n ORDER BY COALESCE(completed_at, started_at) DESC\n LIMIT ${limit}`,\n args: [since],\n });\n return rows.map((r) => {\n const row = r as {\n id: string;\n thread_id: string;\n turn_id: string | null;\n status: string;\n error_code: string | null;\n error_detail: string | null;\n started_at: number | string;\n completed_at: number | string | null;\n };\n const startedAt = Number(row.started_at);\n const completedAt =\n row.completed_at == null ? null : Number(row.completed_at);\n return {\n id: row.id,\n threadId: row.thread_id,\n turnId: row.turn_id ?? null,\n status: row.status,\n errorCode: row.error_code ?? null,\n errorDetail: row.error_detail ?? null,\n startedAt,\n completedAt,\n durationMs: completedAt == null ? null : completedAt - startedAt,\n };\n });\n}\n\n/**\n * Idempotently append a terminal event to a run's event stream. No-op if the\n * stream already ends in a terminal event. Used by reapers AND by SSE\n * reconnect paths that discover an `errored` run row with no terminal event\n * (e.g. an earlier reaper's silent `.catch(() => {})` swallowed the append).\n *\n * Persisting from the reconnect path is what keeps the system self-healing:\n * subsequent reconnects replay the proper terminal event from SQL instead of\n * synthesizing a fresh one each time.\n */\nexport async function ensureTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n): Promise<void> {\n return appendTerminalRunEvent(runId, event);\n}\n\n/**\n * Append a terminal run event, retrying once on failure and reporting to\n * Sentry if both attempts fail. Background reaper paths can't surface errors\n * to a user, but they MUST eventually persist a terminal event — losing it\n * leaves reconnecting clients staring at a bare `status='errored'` row with\n * no payload to render. The previous `.catch(() => {})` callsites silently\n * dropped transient SQL blips and produced exactly that bug. Never throws.\n */\nasync function safeAppendTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n source: string,\n): Promise<void> {\n let firstError: unknown;\n try {\n await appendTerminalRunEvent(runId, event);\n return;\n } catch (err) {\n firstError = err;\n }\n // Brief backoff — most \"transient\" SQL failures (connection blip, lock\n // contention) clear within a couple hundred ms.\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n try {\n await appendTerminalRunEvent(runId, event);\n } catch (retryErr) {\n captureError(retryErr, {\n tags: {\n component: \"agent-run-store\",\n operation: \"append-terminal-event\",\n source,\n },\n extra: {\n runId,\n eventType: typeof event.type === \"string\" ? event.type : \"(unknown)\",\n firstError:\n firstError instanceof Error ? firstError.message : String(firstError),\n },\n });\n }\n}\n\nasync function appendTerminalRunEvent(\n runId: string,\n event: Record<string, unknown>,\n): Promise<void> {\n await ensureRunTables();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT seq, event_data FROM agent_run_events WHERE run_id = ? ORDER BY seq DESC LIMIT 1`,\n args: [runId],\n });\n const last = rows[0] as\n | { seq?: number | string; event_data?: string }\n | undefined;\n if (last?.event_data) {\n try {\n const parsed = JSON.parse(last.event_data);\n if (\n parsed?.type === \"done\" ||\n parsed?.type === \"error\" ||\n parsed?.type === \"missing_api_key\" ||\n parsed?.type === \"loop_limit\" ||\n parsed?.type === \"auto_continue\"\n ) {\n return;\n }\n } catch {\n // Ignore malformed rows and append the terminal event.\n }\n }\n const nextSeq = last ? Number(last.seq ?? -1) + 1 : 0;\n await client.execute({\n sql: `INSERT INTO agent_run_events (run_id, seq, event_data) VALUES (?, ?, ?) ON CONFLICT (run_id, seq) DO NOTHING`,\n args: [runId, nextSeq, JSON.stringify(event)],\n });\n}\n"]}
@@ -115,6 +115,26 @@ export interface AgentChatRequest {
115
115
  attachments?: AgentChatAttachment[];
116
116
  /** Internal retry/continuation requests should not create visible user turns. */
117
117
  internalContinuation?: boolean;
118
+ /**
119
+ * Internal marker set ONLY by the durable-background self-dispatch (see
120
+ * `AGENT_CHAT_BACKGROUND_RUN_FIELD`). Present when the agent-chat handler is
121
+ * re-entered as the background worker: it carries the pre-claimed `runId` and
122
+ * logical `turnId` so the worker runs the loop inline with the background
123
+ * soft-timeout instead of re-claiming the slot or re-dispatching. Untrusted
124
+ * on its own — the `_process-run` route HMAC-verifies the dispatch before
125
+ * invoking the handler. Absent on every normal client request.
126
+ */
127
+ __backgroundRun?: {
128
+ runId: string;
129
+ turnId?: string;
130
+ /**
131
+ * Number of server-driven background→background continuations already
132
+ * chained into this logical turn (0 on the first chunk). The worker
133
+ * increments this when it re-fires `_process-run` at a soft-timeout
134
+ * boundary and refuses to chain past `MAX_BACKGROUND_RUN_CONTINUATIONS`.
135
+ */
136
+ continuationCount?: number;
137
+ };
118
138
  /**
119
139
  * Stable identity for the logical assistant turn this request belongs to.
120
140
  * The client sends the SAME turnId for the initial POST and every
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/agent/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,MAAM,WAAW,qBAAqB;IACpC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;IACnD,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,oBAAoB,CAAC,EAAE,OAAO,GAAG,qBAAqB,CAAC;IACvD,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,KAAK,CAAC,EAAE,qBAAqB,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,qBAAqB,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,qBAAqB,EAAE,CAAC;IAChC,GAAG,C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