@circuitwall/jarela 0.9.3 → 0.10.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 (94) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +2 -2
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  6. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  18. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  23. package/.next/standalone/.next/server/app/api/v1/dashboard/metrics/route.js +72 -5
  24. package/.next/standalone/.next/server/app/api/v1/dashboard/metrics/route.js.map +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +2 -2
  26. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +2 -2
  27. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +136 -26
  28. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/tools/route.js +2 -2
  30. package/.next/standalone/.next/server/app/index.html +2 -2
  31. package/.next/standalone/.next/server/app/index.rsc +3 -3
  32. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  33. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  34. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  35. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  36. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  37. package/.next/standalone/.next/server/app/page.js +266 -40
  38. package/.next/standalone/.next/server/app/page.js.map +1 -1
  39. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  40. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  41. package/.next/standalone/.next/server/app/setup.html +1 -1
  42. package/.next/standalone/.next/server/app/setup.rsc +2 -2
  43. package/.next/standalone/.next/server/app/setup.segments/_full.segment.rsc +2 -2
  44. package/.next/standalone/.next/server/app/setup.segments/_head.segment.rsc +1 -1
  45. package/.next/standalone/.next/server/app/setup.segments/_index.segment.rsc +2 -2
  46. package/.next/standalone/.next/server/app/setup.segments/_tree.segment.rsc +2 -2
  47. package/.next/standalone/.next/server/app/setup.segments/setup/__PAGE__.segment.rsc +1 -1
  48. package/.next/standalone/.next/server/app/setup.segments/setup.segment.rsc +1 -1
  49. package/.next/standalone/.next/server/app-paths-manifest.json +2 -2
  50. package/.next/standalone/.next/server/chunks/210.js +1 -1
  51. package/.next/standalone/.next/server/chunks/2151.js +60 -2
  52. package/.next/standalone/.next/server/chunks/2151.js.map +1 -1
  53. package/.next/standalone/.next/server/chunks/614.js +336 -93
  54. package/.next/standalone/.next/server/chunks/614.js.map +1 -1
  55. package/.next/standalone/.next/server/chunks/6765.js +35 -0
  56. package/.next/standalone/.next/server/chunks/6765.js.map +1 -1
  57. package/.next/standalone/.next/server/chunks/8697.js +15246 -15002
  58. package/.next/standalone/.next/server/chunks/8697.js.map +1 -1
  59. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  60. package/.next/standalone/.next/server/pages/404.html +2 -2
  61. package/.next/standalone/.next/server/pages/500.html +1 -1
  62. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  63. package/.next/standalone/.next/static/chunks/{3741-344e2bfc5028b9c8.js → 3741-2d64471ff763b8fa.js} +36 -1
  64. package/.next/standalone/.next/static/chunks/3741-2d64471ff763b8fa.js.map +1 -0
  65. package/.next/standalone/.next/static/chunks/app/{page-c77ab600642bbfc2.js → page-318743bf47fac345.js} +267 -41
  66. package/.next/standalone/.next/static/chunks/app/page-318743bf47fac345.js.map +1 -0
  67. package/.next/standalone/.next/static/css/b6b85b0f13bc0e98.css +5 -0
  68. package/.next/standalone/.next/static/css/b6b85b0f13bc0e98.css.map +1 -0
  69. package/.next/standalone/package.json +1 -1
  70. package/CHANGELOG.md +48 -0
  71. package/README.md +2 -0
  72. package/api/client.ts +37 -1
  73. package/api/types.ts +18 -0
  74. package/app/api/v1/threads/[thread_id]/run/route.ts +69 -22
  75. package/components/agents/AgentEditor.tsx +7 -4
  76. package/components/chat/MessageBubble.tsx +108 -1
  77. package/components/dashboard/DashboardPanel.tsx +79 -21
  78. package/hooks/useSSE.ts +22 -9
  79. package/lib/agents/prepare/system-prompt.ts +30 -0
  80. package/lib/agents/run-registry.test.ts +94 -0
  81. package/lib/agents/run-registry.ts +60 -1
  82. package/lib/stores/dashboard-metrics.test.ts +33 -0
  83. package/lib/stores/dashboard-metrics.ts +93 -1
  84. package/lib/tools/exec.ts +9 -5
  85. package/lib/tools/files.ts +6 -0
  86. package/lib/tools/safety.test.ts +95 -0
  87. package/lib/tools/safety.ts +147 -0
  88. package/package.json +1 -1
  89. package/.next/standalone/.next/static/chunks/3741-344e2bfc5028b9c8.js.map +0 -1
  90. package/.next/standalone/.next/static/chunks/app/page-c77ab600642bbfc2.js.map +0 -1
  91. package/.next/standalone/.next/static/css/53f85613a5500253.css +0 -5
  92. package/.next/standalone/.next/static/css/53f85613a5500253.css.map +0 -1
  93. /package/.next/standalone/.next/static/{6uLoytvvEtLKIblEB53e0 → 8qTBpUDFnSMYwe3Zc0bGV}/_buildManifest.js +0 -0
  94. /package/.next/standalone/.next/static/{6uLoytvvEtLKIblEB53e0 → 8qTBpUDFnSMYwe3Zc0bGV}/_ssgManifest.js +0 -0
@@ -241,8 +241,8 @@ var external = __webpack_require__(90378);
241
241
  var providers = __webpack_require__(68866);
242
242
  // EXTERNAL MODULE: ./lib/tools/external.ts
243
243
  var tools_external = __webpack_require__(18689);
244
- // EXTERNAL MODULE: ./lib/tools/index.ts + 18 modules
245
- var lib_tools = __webpack_require__(33934);
244
+ // EXTERNAL MODULE: ./lib/tools/index.ts + 19 modules
245
+ var lib_tools = __webpack_require__(23696);
246
246
  // EXTERNAL MODULE: ./lib/stores/tool-secrets.ts
247
247
  var tool_secrets = __webpack_require__(81753);
248
248
  // EXTERNAL MODULE: ./lib/api/responses.ts
@@ -279,8 +279,8 @@ var server = __webpack_require__(23211);
279
279
  var schemas = __webpack_require__(49883);
280
280
  // EXTERNAL MODULE: ./lib/tools/external.ts
281
281
  var external = __webpack_require__(18689);
282
- // EXTERNAL MODULE: ./lib/tools/index.ts + 18 modules
283
- var lib_tools = __webpack_require__(33934);
282
+ // EXTERNAL MODULE: ./lib/tools/index.ts + 19 modules
283
+ var lib_tools = __webpack_require__(23696);
284
284
  // EXTERNAL MODULE: ./lib/stores/tool-secrets.ts
285
285
  var tool_secrets = __webpack_require__(81753);
286
286
  ;// ./app/api/v1/extensions/tools/[name]/secrets/route.ts
@@ -267,6 +267,23 @@ var run_thread = __webpack_require__(38710);
267
267
  ;// ./lib/agents/run-registry.ts
268
268
  const MAX_BUFFERED = 4000; // text_delta chunks accumulate fast; cap them
269
269
  const RECENT_TTL_MS = 5 * 60000; // keep finished runs visible for 5 min
270
+ // Idle (no-progress) ceiling: if no chunk has been broadcast for this
271
+ // long the registry assumes the LLM/tool call wedged and force-finishes
272
+ // the run. This is the user-perceived "stream is dead" signal and is
273
+ // short by design — long legitimate turns keep streaming text/tool
274
+ // chunks, so they reset the idle clock on every broadcast(). The
275
+ // wall-clock ceiling (runMaxMs) is the absolute safety net for the
276
+ // degenerate case where broadcast() is never called at all (or fires
277
+ // faster than the idle window forever).
278
+ // Override with JARELA_RUN_IDLE_MS / JARELA_RUN_MAX_MS.
279
+ function runIdleMs() {
280
+ const raw = Number(process.env.JARELA_RUN_IDLE_MS);
281
+ return Number.isFinite(raw) && raw > 0 ? raw : 90000;
282
+ }
283
+ function runMaxMs() {
284
+ const raw = Number(process.env.JARELA_RUN_MAX_MS);
285
+ return Number.isFinite(raw) && raw > 0 ? raw : 15 * 60000;
286
+ }
270
287
  const runs = new Map();
271
288
  function startRun(thread_id, agent_id) {
272
289
  // If a stale completed run exists, drop it before starting a new one.
@@ -274,24 +291,65 @@ function startRun(thread_id, agent_id) {
274
291
  if (existing && existing.status === "running") {
275
292
  throw new Error(`A run is already active for thread ${thread_id}`);
276
293
  }
294
+ const now = Date.now();
277
295
  const run = {
278
296
  thread_id,
279
297
  agent_id,
280
- started_at: Date.now(),
298
+ started_at: now,
281
299
  finished_at: null,
282
300
  status: "running",
283
301
  events: [],
284
302
  subscribers: new Set(),
285
303
  final_text: "",
286
- abort: new AbortController()
304
+ abort: new AbortController(),
305
+ last_chunk_at: now
287
306
  };
288
307
  runs.set(thread_id, run);
308
+ scheduleIdleWatchdog(run);
309
+ scheduleMaxWatchdog(run);
289
310
  return run;
290
311
  }
312
+ // Self-rearming idle watchdog. Fires when no chunk has arrived for
313
+ // `idleMs`; otherwise reschedules itself for `(last_chunk_at + idleMs) -
314
+ // now`. We never carry a handle on the run — the closure just bails if
315
+ // the run is no longer the registry's entry or no longer running.
316
+ function scheduleIdleWatchdog(run) {
317
+ const idleMs = runIdleMs();
318
+ const fireIn = Math.max(0, run.last_chunk_at + idleMs - Date.now());
319
+ setTimeout(()=>{
320
+ const cur = runs.get(run.thread_id);
321
+ if (cur !== run) return;
322
+ if (run.status !== "running") return;
323
+ const idle = Date.now() - run.last_chunk_at;
324
+ if (idle < idleMs) {
325
+ scheduleIdleWatchdog(run);
326
+ return;
327
+ }
328
+ console.warn(`[run-registry] idle watchdog: force-finishing stalled run for thread ${run.thread_id} after ${idle}ms of no progress`);
329
+ try {
330
+ run.abort.abort("run_idle_timeout");
331
+ } catch {}
332
+ finishRun(run, "error");
333
+ }, fireIn).unref?.();
334
+ }
335
+ function scheduleMaxWatchdog(run) {
336
+ const max = runMaxMs();
337
+ setTimeout(()=>{
338
+ const cur = runs.get(run.thread_id);
339
+ if (cur !== run) return;
340
+ if (run.status !== "running") return;
341
+ console.warn(`[run-registry] wall-clock watchdog: force-finishing run for thread ${run.thread_id} after ${max}ms`);
342
+ try {
343
+ run.abort.abort("run_watchdog_timeout");
344
+ } catch {}
345
+ finishRun(run, "error");
346
+ }, max).unref?.();
347
+ }
291
348
  function broadcast(run, chunk) {
292
349
  // Identity-check: a superseded run must not smear trailing chunks onto
293
350
  // the replacement entry in the registry.
294
351
  if (runs.get(run.thread_id) !== run) return;
352
+ run.last_chunk_at = Date.now();
295
353
  if (chunk.type === "text_delta") {
296
354
  run.final_text += chunk.data.delta ?? "";
297
355
  }
@@ -490,31 +548,69 @@ async function POST(req, { params }) {
490
548
  // Drive the agent to completion regardless of client connection. Events
491
549
  // go to the registry; the GET subscriber (and any reattaching clients)
492
550
  // receive them via subscribe().
551
+ //
552
+ // CRITICAL: finishRun() MUST run no matter what — if it doesn't, the
553
+ // run is pinned as "running" forever, every subsequent POST returns
554
+ // 409 run_in_flight, and the user sees a silently-dead chat. The TTL
555
+ // eviction is scheduled inside finishRun(), so a leaked entry never
556
+ // self-heals. Wrap the whole body in try/finally.
493
557
  void (async ()=>{
494
- const collected = await (0,stream_collector/* collectStream */.V)(prepared.stream, {
495
- onChunk: (chunk)=>broadcast(active, chunk)
496
- });
497
- // If the stream threw mid-iteration, collectStream returns terminal="error"
498
- // but no `error` chunk was broadcast — surface one to subscribers.
499
- if (collected.terminal === "error" && collected.errorMessage) {
558
+ let terminal = "error";
559
+ let assistantContent = "";
560
+ try {
561
+ const collected = await (0,stream_collector/* collectStream */.V)(prepared.stream, {
562
+ onChunk: (chunk)=>broadcast(active, chunk)
563
+ });
564
+ assistantContent = collected.assistantContent;
565
+ terminal = collected.terminal;
566
+ // If the stream threw mid-iteration, collectStream returns terminal="error"
567
+ // but no `error` chunk was broadcast — surface one to subscribers.
568
+ if (collected.terminal === "error" && collected.errorMessage) {
569
+ broadcast(active, {
570
+ type: "error",
571
+ data: {
572
+ message: collected.errorMessage,
573
+ code: "stream_error"
574
+ }
575
+ });
576
+ }
577
+ try {
578
+ (0,run_thread/* persistAssistantMessage */._w)(thread_id, collected.assistantContent, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null);
579
+ } catch (persistErr) {
580
+ // Persistence failure must not strand the run — surface and continue
581
+ // to finishRun in the finally block.
582
+ terminal = "error";
583
+ broadcast(active, {
584
+ type: "error",
585
+ data: {
586
+ message: `persist failed: ${persistErr.message}`,
587
+ code: "persist_error"
588
+ }
589
+ });
590
+ }
591
+ } catch (err) {
592
+ // Unhandled throw from collectStream / the underlying stream. Without
593
+ // this catch, finishRun would never run and the registry entry would
594
+ // stick as "running" indefinitely (see CRITICAL note above).
595
+ terminal = "error";
500
596
  broadcast(active, {
501
597
  type: "error",
502
598
  data: {
503
- message: collected.errorMessage,
504
- code: "stream_error"
599
+ message: err.message ?? String(err),
600
+ code: "run_crashed"
505
601
  }
506
602
  });
603
+ } finally{
604
+ finishRun(active, terminal);
605
+ (0,bus/* publish */.mk)({
606
+ type: "run_completed",
607
+ thread_id,
608
+ agent_id: thread?.agent_id ?? null,
609
+ status: terminal,
610
+ preview: assistantContent.replace(/\s+/g, " ").trim().slice(0, 120),
611
+ ts: Date.now()
612
+ });
507
613
  }
508
- (0,run_thread/* persistAssistantMessage */._w)(thread_id, collected.assistantContent, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null);
509
- finishRun(active, collected.terminal);
510
- (0,bus/* publish */.mk)({
511
- type: "run_completed",
512
- thread_id,
513
- agent_id: thread?.agent_id ?? null,
514
- status: collected.terminal,
515
- preview: collected.assistantContent.replace(/\s+/g, " ").trim().slice(0, 120),
516
- ts: Date.now()
517
- });
518
614
  })();
519
615
  return new Response(JSON.stringify({
520
616
  accepted: true,
@@ -533,8 +629,14 @@ async function POST(req, { params }) {
533
629
  // `EventSource` — never `fetch().body.getReader()`, which is unreliable on
534
630
  // iOS Safari for long-lived streaming responses.
535
631
  //
536
- // Returns 404 with no body if there's no run to attach to (run never
537
- // existed, or it finished + TTL-evicted before the GET arrived).
632
+ // Emits a single synthetic `done` event and closes when there's no run to
633
+ // attach to (run never existed, or it finished + TTL-evicted before the GET
634
+ // arrived). We deliberately do NOT return 404 here: browsers map a 404 SSE
635
+ // response onto `EventSource.onerror` with no terminal event, which trips
636
+ // EventSource's auto-reconnect logic and leaves the client in a "stream
637
+ // open but silent" state — UIs gating on a `done` event hang forever
638
+ // showing the Stop/Reconnecting affordances. A 200 with `data: {"type":
639
+ // "done"}\n\n` makes the iterator drain cleanly on every transport.
538
640
  //
539
641
  // `show_tools` / `show_thinking` query params let the caller suppress
540
642
  // chunk types it doesn't want to render. Defaults: both on. The full
@@ -542,10 +644,6 @@ async function POST(req, { params }) {
542
644
  // agent run config are run-wide settings, not per-subscriber filters).
543
645
  async function GET(req, { params }) {
544
646
  const { thread_id } = await params;
545
- const run = getRun(thread_id);
546
- if (!run) return new Response(null, {
547
- status: 404
548
- });
549
647
  const showTools = req.nextUrl.searchParams.get("show_tools") !== "false";
550
648
  const showThinking = req.nextUrl.searchParams.get("show_thinking") !== "false";
551
649
  const stream_options = {
@@ -554,6 +652,18 @@ async function GET(req, { params }) {
554
652
  include_thinking: showThinking
555
653
  }
556
654
  };
655
+ const run = getRun(thread_id);
656
+ if (!run) {
657
+ const stream = new ReadableStream({
658
+ start (controller) {
659
+ controller.enqueue(route_sse({
660
+ type: "done"
661
+ }));
662
+ controller.close();
663
+ }
664
+ });
665
+ return (0,sse/* sseResponse */.t)(stream);
666
+ }
557
667
  return attachStream(thread_id, stream_options);
558
668
  }
559
669
  // DELETE aborts the currently-running agent for this thread. The agent stream
@@ -1 +1 @@
1
- {"version":3,"file":"../app/api/v1/threads/[thread_id]/run/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;ACAA,yEAAyE;AACzE,yEAAyE;AACzE,yEAAyE;AACzE,oDAAoD;AAW7C,SAASA,YACdC,MAAsB,EACtBC,OAA2B,CAAC,CAAC;IAE7B,MAAM,EAAEC,wBAAwB,IAAI,EAAE,GAAGD;IACzC,MAAME,UAAkC;QACtC,gBAAgB;QAChB,iBAAiB;QACjBC,YAAY;IACd;IACA,IAAIF,uBAAuBC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AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA;;;;;;;;AC7WA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;ACAa;AACb,6BAA6C;AAC7C;AACA,CAAC,CAAC;AACF,qCAA+C;AAC/C;AACA;AACA;AACA;AACA,CAAC,EAAC;AACF,iBAAiB,mBAAO,CAAC,KAAqB;AAC9C,sBAAsB,mBAAO,CAAC,KAAiB;AAC/C,eAAe,mBAAO,CAAC,KAAa;AACpC;AACA;AACA;AACA,IAAI,KAAmC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,gBAAgB,mBAAmB;AACnC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/./lib/api/sse.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/./lib/agents/run-registry.ts","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?c745","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:url\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","// Shared response builder for Server-Sent Event streams. Centralises the\n// content-type / cache-control / connection / proxy-buffering headers so\n// every SSE endpoint behaves identically through nginx, tailscale-serve,\n// and Cloudflare. See ADR-0009 for the proxy story.\n\nexport interface SseResponseOptions {\n /**\n * Set `X-Accel-Buffering: no`. Required when intermediate proxies\n * (nginx, tailscale-serve) might coalesce small chunks and break SSE\n * framing. Default: true.\n */\n disableProxyBuffering?: boolean;\n}\n\nexport function sseResponse(\n stream: ReadableStream,\n opts: SseResponseOptions = {},\n): Response {\n const { disableProxyBuffering = true } = opts;\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n };\n if (disableProxyBuffering) headers[\"X-Accel-Buffering\"] = \"no\";\n return new Response(stream, { headers });\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","import type { StreamChunk } from \"./base\";\n\n// In-memory registry of in-flight agent runs, keyed by thread_id. When the user\n// switches agents mid-stream, the run keeps going server-side; if they return\n// (or open a second tab), they re-attach via subscribe() and see live deltas.\n//\n// Trade-offs:\n// - Single Node process only. Multi-instance deploys would need a shared\n// pubsub (Redis, NATS) — not in scope for a local app.\n// - Buffered events are capped to MAX_BUFFERED so a 100k-token response\n// doesn't pin GBs of memory if every chunk lingers. Late attachers see the\n// most recent slice plus all subsequent events.\n\ntype Subscriber = (chunk: StreamChunk) => void;\n\nconst MAX_BUFFERED = 4000; // text_delta chunks accumulate fast; cap them\nconst RECENT_TTL_MS = 5 * 60_000; // keep finished runs visible for 5 min\n\nexport interface ActiveRun {\n thread_id: string;\n agent_id: string | null;\n started_at: number;\n finished_at: number | null;\n status: \"running\" | \"done\" | \"error\";\n events: StreamChunk[];\n subscribers: Set<Subscriber>;\n // Final assistant text — useful for notification body without replaying every event.\n final_text: string;\n // Server-side abort: when the user clicks Stop (or the last client\n // disconnects), we signal this controller so the LangGraph stream cancels\n // itself instead of running to completion in the background.\n abort: AbortController;\n}\n\nconst runs = new Map<string, ActiveRun>();\n\nexport function startRun(thread_id: string, agent_id: string | null): ActiveRun {\n // If a stale completed run exists, drop it before starting a new one.\n const existing = runs.get(thread_id);\n if (existing && existing.status === \"running\") {\n throw new Error(`A run is already active for thread ${thread_id}`);\n }\n const run: ActiveRun = {\n thread_id,\n agent_id,\n started_at: Date.now(),\n finished_at: null,\n status: \"running\",\n events: [],\n subscribers: new Set(),\n final_text: \"\",\n abort: new AbortController(),\n };\n runs.set(thread_id, run);\n return run;\n}\n\nexport function broadcast(run: ActiveRun, chunk: StreamChunk): void {\n // Identity-check: a superseded run must not smear trailing chunks onto\n // the replacement entry in the registry.\n if (runs.get(run.thread_id) !== run) return;\n if (chunk.type === \"text_delta\") {\n run.final_text += (chunk.data.delta as string) ?? \"\";\n }\n if (run.events.length < MAX_BUFFERED) {\n run.events.push(chunk);\n }\n for (const fn of run.subscribers) {\n try { fn(chunk); } catch { /* subscriber errored, ignore */ }\n }\n}\n\nexport function finishRun(run: ActiveRun, status: \"done\" | \"error\"): void {\n // Identity-check: a stale run finishing late must not flip the\n // replacement's status or evict it from the registry.\n if (runs.get(run.thread_id) !== run) return;\n run.status = status;\n run.finished_at = Date.now();\n // Drop subscribers — late attachers should NOT keep getting events on a\n // dead run. They'll get the buffered events on subscribe and that's it.\n run.subscribers.clear();\n // Auto-evict after TTL so memory doesn't grow with every conversation.\n setTimeout(() => {\n const cur = runs.get(run.thread_id);\n if (cur === run) runs.delete(run.thread_id);\n }, RECENT_TTL_MS).unref?.();\n}\n\nexport function getRun(thread_id: string): ActiveRun | null {\n return runs.get(thread_id) ?? null;\n}\n\n// Signal the agent stream to cancel. The stream loop in the route is wired\n// to listen on the AbortController and exit early, emitting an error chunk\n// the client (and the queue-drain hook) can react to. Idempotent.\nexport function abortRun(thread_id: string, reason = \"user_interrupted\"): boolean {\n const run = runs.get(thread_id);\n if (!run || run.status !== \"running\") return false;\n if (!run.abort.signal.aborted) {\n try { run.abort.abort(reason); } catch { /* */ }\n }\n return true;\n}\n\n// Abort every currently-running run. Used by the graceful-shutdown path so\n// LangGraph stream loops bail out instead of continuing past process exit.\n// Returns the number of runs that were signalled.\nexport function abortAllRuns(reason = \"server_shutdown\"): number {\n let count = 0;\n for (const run of runs.values()) {\n if (run.status !== \"running\") continue;\n if (run.abort.signal.aborted) continue;\n try { run.abort.abort(reason); count++; } catch { /* */ }\n }\n return count;\n}\n\n// Poll until every run has transitioned out of \"running\" (or until the\n// caller-supplied deadline elapses). Used during graceful shutdown after\n// `abortAllRuns()` so the stream `finally` blocks have a chance to flush\n// the trailing error chunk and call `finishRun()`. Resolves to the count\n// of runs still stuck in \"running\" when the deadline hit (0 = clean).\nexport async function waitForRunsToSettle(timeoutMs: number): Promise<number> {\n const deadline = Date.now() + Math.max(0, timeoutMs);\n while (Date.now() < deadline) {\n let stillRunning = 0;\n for (const run of runs.values()) if (run.status === \"running\") stillRunning++;\n if (stillRunning === 0) return 0;\n await new Promise<void>((resolve) => setTimeout(resolve, 50));\n }\n let stillRunning = 0;\n for (const run of runs.values()) if (run.status === \"running\") stillRunning++;\n return stillRunning;\n}\n\n// Replays buffered events synchronously, then subscribes for live ones.\n// Returns an unsubscribe fn. Caller is responsible for calling it.\nexport function subscribe(\n thread_id: string,\n onEvent: Subscriber,\n): { run: ActiveRun | null; unsubscribe: () => void } {\n const run = runs.get(thread_id);\n if (!run) return { run: null, unsubscribe: () => {} };\n // Replay buffered events first (so the new subscriber catches up).\n for (const ev of run.events) {\n try { onEvent(ev); } catch { /* */ }\n }\n if (run.status !== \"running\") {\n return { run, unsubscribe: () => {} };\n }\n run.subscribers.add(onEvent);\n return {\n run,\n unsubscribe: () => { run.subscribers.delete(onEvent); },\n };\n}\n","import { NextRequest } from \"next/server\";\nimport type { StreamOptions, StreamChunk } from \"@/lib/agents/base\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport {\n prepareThreadRun,\n persistAssistantMessage,\n RunThreadError,\n shouldEmitChunk,\n} from \"@/lib/agents/run-thread\";\nimport { broadcast, finishRun, startRun, subscribe, abortRun, getRun } from \"@/lib/agents/run-registry\";\nimport { collectStream } from \"@/lib/agents/stream-collector\";\nimport { getThread } from \"@/lib/stores/threads\";\nimport { publish as publishNotification } from \"@/lib/notifications/bus\";\nimport { sseResponse } from \"@/lib/api/sse\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst enc = new TextEncoder();\nconst sse = (obj: Record<string, unknown>) => enc.encode(`data: ${JSON.stringify(obj)}\\n\\n`);\n\n// POST is the *command* half of the run lifecycle (ADR-0008). It accepts the\n// new user message, registers a run in the in-memory registry, kicks the\n// agent loop off in a detached async task, and returns 202 immediately. The\n// caller must follow up with a GET on this same path (as an `EventSource`)\n// to subscribe to the chunk stream — see GET below.\n//\n// Splitting submit from subscribe gives us a single reliable streaming\n// primitive across all browsers (EventSource is the only WebKit-native\n// streaming API that survives iOS Safari + Tailscale HTTP/2 proxies). It\n// also collapses what was previously a WS sidecar + SSE-over-POST +\n// SSE-GET-reattach trio into one transport.\nexport async function POST(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const { message, attachments, stream_options, hot_since } = (await req.json()) as {\n message: string;\n attachments?: ContentPart[];\n stream_options?: StreamOptions;\n // ADR-0042 — explicit context boundary the chat picked. ISO timestamp,\n // null to clear the pin, omitted to leave whatever's already persisted\n // on the thread.\n hot_since?: string | null;\n };\n\n // Connection-level handoff (NOT a kill). If a run is already in flight\n // for this thread — second tab, another device, a flaky-mobile retry —\n // refuse the new submission with 409. The caller is expected to:\n // 1) roll back any optimistic user bubble it added,\n // 2) re-queue the message locally to resubmit after the current turn\n // finishes,\n // 3) open the GET subscription so the user still sees the in-flight\n // turn's deltas render.\n const existing = getRun(thread_id);\n if (existing && existing.status === \"running\") {\n return new Response(\n JSON.stringify({ accepted: false, code: \"run_in_flight\", thread_id }),\n { status: 409, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n\n const thread = getThread(thread_id);\n const active = startRun(thread_id, thread?.agent_id ?? null);\n let prepared;\n try {\n prepared = await prepareThreadRun({\n thread_id,\n message,\n options: stream_options,\n attachments,\n signal: active.abort.signal,\n hot_since,\n });\n } catch (err) {\n // Prep failure (unknown agent, model misconfig, …) — drop the run we\n // just registered and surface a synchronous error to the caller.\n finishRun(active, \"error\");\n if (err instanceof RunThreadError) {\n return new Response(\n JSON.stringify({ accepted: false, error: err.message, code: err.code }),\n { status: err.status, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n return new Response(\n JSON.stringify({ accepted: false, error: String(err), code: \"run_prepare_error\" }),\n { status: 500, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n\n // Drive the agent to completion regardless of client connection. Events\n // go to the registry; the GET subscriber (and any reattaching clients)\n // receive them via subscribe().\n void (async () => {\n const collected = await collectStream(prepared.stream as AsyncIterable<StreamChunk>, {\n onChunk: (chunk) => broadcast(active, chunk),\n });\n // If the stream threw mid-iteration, collectStream returns terminal=\"error\"\n // but no `error` chunk was broadcast — surface one to subscribers.\n if (collected.terminal === \"error\" && collected.errorMessage) {\n broadcast(active, {\n type: \"error\",\n data: { message: collected.errorMessage, code: \"stream_error\" },\n });\n }\n persistAssistantMessage(thread_id, collected.assistantContent, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null);\n finishRun(active, collected.terminal);\n publishNotification({\n type: \"run_completed\",\n thread_id,\n agent_id: thread?.agent_id ?? null,\n status: collected.terminal,\n preview: collected.assistantContent.replace(/\\s+/g, \" \").trim().slice(0, 120),\n ts: Date.now(),\n });\n })();\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, started_at: active.started_at }),\n { status: 202, headers: { \"Content-Type\": \"application/json\" } },\n );\n}\n\n// GET is the *query* half of the run lifecycle (ADR-0008). Attaches to an\n// active (or recently-finished, within the registry TTL) run and streams\n// chunks as Server-Sent Events. Always consumed client-side via\n// `EventSource` — never `fetch().body.getReader()`, which is unreliable on\n// iOS Safari for long-lived streaming responses.\n//\n// Returns 404 with no body if there's no run to attach to (run never\n// existed, or it finished + TTL-evicted before the GET arrived).\n//\n// `show_tools` / `show_thinking` query params let the caller suppress\n// chunk types it doesn't want to render. Defaults: both on. The full\n// `StreamOptions` shape is only meaningful on the POST (tool policy &\n// agent run config are run-wide settings, not per-subscriber filters).\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const run = getRun(thread_id);\n if (!run) return new Response(null, { status: 404 });\n\n const showTools = req.nextUrl.searchParams.get(\"show_tools\") !== \"false\";\n const showThinking = req.nextUrl.searchParams.get(\"show_thinking\") !== \"false\";\n const stream_options: StreamOptions = {\n filters: { include_tools: showTools, include_thinking: showThinking },\n };\n return attachStream(thread_id, stream_options);\n}\n\n// DELETE aborts the currently-running agent for this thread. The agent stream\n// loop in llm.ts catches the resulting AbortError and emits a synthetic\n// `error` + `done` event pair so subscribers (and the client's queue-drain\n// hook) finish cleanly.\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const aborted = abortRun(thread_id, \"user_interrupted\");\n return new Response(JSON.stringify({ aborted }), {\n status: aborted ? 200 : 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction attachStream(\n thread_id: string,\n stream_options?: StreamOptions,\n): Response {\n const stream = new ReadableStream({\n start(controller) {\n let clientGone = false;\n const safeEnqueue = (chunk: Uint8Array): void => {\n if (clientGone) return;\n try { controller.enqueue(chunk); } catch { clientGone = true; }\n };\n\n const onEvent = (ev: StreamChunk) => {\n if (!shouldEmitChunk(ev.type, stream_options)) return;\n safeEnqueue(sse({ type: ev.type, ...ev.data }));\n };\n\n const { run, unsubscribe } = subscribe(thread_id, onEvent);\n if (!run) {\n controller.close();\n return;\n }\n\n // If run already terminal, close after replay.\n if (run.status !== \"running\") {\n try { controller.close(); } catch { /* */ }\n return;\n }\n\n // When the run finishes (status changes), close our response. We\n // poll lightly because the run might finish due to other subscribers'\n // signals; simpler than wiring a second listener channel.\n const poll = setInterval(() => {\n const r = getRun(thread_id);\n if (!r || r.status !== \"running\") {\n clearInterval(poll);\n unsubscribe();\n if (!clientGone) {\n try { controller.close(); } catch { /* */ }\n }\n }\n }, 500);\n poll.unref?.();\n },\n cancel() {\n // Client navigated away — agent run keeps going in registry.\n },\n });\n\n return sseResponse(stream);\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/threads/[thread_id]/run/route\",\n pathname: \"/api/v1/threads/[thread_id]/run\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/run/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/threads/[thread_id]/run/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:url\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["sseResponse","stream","opts","disableProxyBuffering","headers","Connection","Response","MAX_BUFFERED","RECENT_TTL_MS","runs","Map","startRun","thread_id","agent_id","existing","get","status","Error","run","started_at","Date","now","finished_at","events","subscribers","Set","final_text","abort","AbortController","set","broadcast","chunk","type","data","delta","length","push","fn","finishRun","clear","setTimeout","cur","delete","unref","getRun","abortRun","reason","signal","aborted","abortAllRuns","count","values","waitForRunsToSettle","timeoutMs","deadline","Math","max","stillRunning","Promise","resolve","subscribe","onEvent","unsubscribe","ev","add","prepareThreadRun","persistAssistantMessage","RunThreadError","shouldEmitChunk","collectStream","getThread","publish","publishNotification","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","message","attachments","stream_options","hot_since","json","accepted","code","thread","active","prepared","options","err","error","String","collected","onChunk","terminal","errorMessage","assistantContent","usedTools","toolEvents","usage","context_snapshot","preview","replace","trim","slice","ts","GET","showTools","nextUrl","searchParams","showThinking","filters","include_tools","include_thinking","attachStream","DELETE","_req","ReadableStream","start","controller","clientGone","safeEnqueue","enqueue","close","poll","setInterval","r","clearInterval","cancel"],"sourceRoot":"","ignoreList":[0,4,6,10,16,27,38,40]}
1
+ {"version":3,"file":"../app/api/v1/threads/[thread_id]/run/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;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;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACsC;AACxG;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA;;;;;;;;AC7WA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;ACAa;AACb,6BAA6C;AAC7C;AACA,CAAC,CAAC;AACF,qCAA+C;AAC/C;AACA;AACA;AACA;AACA,CAAC,EAAC;AACF,iBAAiB,mBAAO,CAAC,KAAqB;AAC9C,sBAAsB,mBAAO,CAAC,KAAiB;AAC/C,eAAe,mBAAO,CAAC,KAAa;AACpC;AACA;AACA;AACA,IAAI,KAAmC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,gBAAgB,mBAAmB;AACnC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/./lib/api/sse.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/./lib/agents/run-registry.ts","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?c745","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:url\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","// Shared response builder for Server-Sent Event streams. Centralises the\n// content-type / cache-control / connection / proxy-buffering headers so\n// every SSE endpoint behaves identically through nginx, tailscale-serve,\n// and Cloudflare. See ADR-0009 for the proxy story.\n\nexport interface SseResponseOptions {\n /**\n * Set `X-Accel-Buffering: no`. Required when intermediate proxies\n * (nginx, tailscale-serve) might coalesce small chunks and break SSE\n * framing. Default: true.\n */\n disableProxyBuffering?: boolean;\n}\n\nexport function sseResponse(\n stream: ReadableStream,\n opts: SseResponseOptions = {},\n): Response {\n const { disableProxyBuffering = true } = opts;\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n };\n if (disableProxyBuffering) headers[\"X-Accel-Buffering\"] = \"no\";\n return new Response(stream, { headers });\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","import type { StreamChunk } from \"./base\";\n\n// In-memory registry of in-flight agent runs, keyed by thread_id. When the user\n// switches agents mid-stream, the run keeps going server-side; if they return\n// (or open a second tab), they re-attach via subscribe() and see live deltas.\n//\n// Trade-offs:\n// - Single Node process only. Multi-instance deploys would need a shared\n// pubsub (Redis, NATS) — not in scope for a local app.\n// - Buffered events are capped to MAX_BUFFERED so a 100k-token response\n// doesn't pin GBs of memory if every chunk lingers. Late attachers see the\n// most recent slice plus all subsequent events.\n\ntype Subscriber = (chunk: StreamChunk) => void;\n\nconst MAX_BUFFERED = 4000; // text_delta chunks accumulate fast; cap them\nconst RECENT_TTL_MS = 5 * 60_000; // keep finished runs visible for 5 min\n// Idle (no-progress) ceiling: if no chunk has been broadcast for this\n// long the registry assumes the LLM/tool call wedged and force-finishes\n// the run. This is the user-perceived \"stream is dead\" signal and is\n// short by design — long legitimate turns keep streaming text/tool\n// chunks, so they reset the idle clock on every broadcast(). The\n// wall-clock ceiling (runMaxMs) is the absolute safety net for the\n// degenerate case where broadcast() is never called at all (or fires\n// faster than the idle window forever).\n// Override with JARELA_RUN_IDLE_MS / JARELA_RUN_MAX_MS.\nfunction runIdleMs(): number {\n const raw = Number(process.env.JARELA_RUN_IDLE_MS);\n return Number.isFinite(raw) && raw > 0 ? raw : 90_000;\n}\nfunction runMaxMs(): number {\n const raw = Number(process.env.JARELA_RUN_MAX_MS);\n return Number.isFinite(raw) && raw > 0 ? raw : 15 * 60_000;\n}\n\nexport interface ActiveRun {\n thread_id: string;\n agent_id: string | null;\n started_at: number;\n finished_at: number | null;\n status: \"running\" | \"done\" | \"error\";\n events: StreamChunk[];\n subscribers: Set<Subscriber>;\n // Final assistant text — useful for notification body without replaying every event.\n final_text: string;\n // Server-side abort: when the user clicks Stop (or the last client\n // disconnects), we signal this controller so the LangGraph stream cancels\n // itself instead of running to completion in the background.\n abort: AbortController;\n // Last activity timestamp — bumped on every broadcast() so the idle\n // watchdog can tell live progress from a wedged stream.\n last_chunk_at: number;\n}\n\nconst runs = new Map<string, ActiveRun>();\n\nexport function startRun(thread_id: string, agent_id: string | null): ActiveRun {\n // If a stale completed run exists, drop it before starting a new one.\n const existing = runs.get(thread_id);\n if (existing && existing.status === \"running\") {\n throw new Error(`A run is already active for thread ${thread_id}`);\n }\n const now = Date.now();\n const run: ActiveRun = {\n thread_id,\n agent_id,\n started_at: now,\n finished_at: null,\n status: \"running\",\n events: [],\n subscribers: new Set(),\n final_text: \"\",\n abort: new AbortController(),\n last_chunk_at: now,\n };\n runs.set(thread_id, run);\n scheduleIdleWatchdog(run);\n scheduleMaxWatchdog(run);\n return run;\n}\n\n// Self-rearming idle watchdog. Fires when no chunk has arrived for\n// `idleMs`; otherwise reschedules itself for `(last_chunk_at + idleMs) -\n// now`. We never carry a handle on the run — the closure just bails if\n// the run is no longer the registry's entry or no longer running.\nfunction scheduleIdleWatchdog(run: ActiveRun): void {\n const idleMs = runIdleMs();\n const fireIn = Math.max(0, (run.last_chunk_at + idleMs) - Date.now());\n setTimeout(() => {\n const cur = runs.get(run.thread_id);\n if (cur !== run) return;\n if (run.status !== \"running\") return;\n const idle = Date.now() - run.last_chunk_at;\n if (idle < idleMs) {\n scheduleIdleWatchdog(run);\n return;\n }\n console.warn(`[run-registry] idle watchdog: force-finishing stalled run for thread ${run.thread_id} after ${idle}ms of no progress`);\n try { run.abort.abort(\"run_idle_timeout\"); } catch { /* */ }\n finishRun(run, \"error\");\n }, fireIn).unref?.();\n}\n\nfunction scheduleMaxWatchdog(run: ActiveRun): void {\n const max = runMaxMs();\n setTimeout(() => {\n const cur = runs.get(run.thread_id);\n if (cur !== run) return;\n if (run.status !== \"running\") return;\n console.warn(`[run-registry] wall-clock watchdog: force-finishing run for thread ${run.thread_id} after ${max}ms`);\n try { run.abort.abort(\"run_watchdog_timeout\"); } catch { /* */ }\n finishRun(run, \"error\");\n }, max).unref?.();\n}\n\nexport function broadcast(run: ActiveRun, chunk: StreamChunk): void {\n // Identity-check: a superseded run must not smear trailing chunks onto\n // the replacement entry in the registry.\n if (runs.get(run.thread_id) !== run) return;\n run.last_chunk_at = Date.now();\n if (chunk.type === \"text_delta\") {\n run.final_text += (chunk.data.delta as string) ?? \"\";\n }\n if (run.events.length < MAX_BUFFERED) {\n run.events.push(chunk);\n }\n for (const fn of run.subscribers) {\n try { fn(chunk); } catch { /* subscriber errored, ignore */ }\n }\n}\n\nexport function finishRun(run: ActiveRun, status: \"done\" | \"error\"): void {\n // Identity-check: a stale run finishing late must not flip the\n // replacement's status or evict it from the registry.\n if (runs.get(run.thread_id) !== run) return;\n run.status = status;\n run.finished_at = Date.now();\n // Drop subscribers — late attachers should NOT keep getting events on a\n // dead run. They'll get the buffered events on subscribe and that's it.\n run.subscribers.clear();\n // Auto-evict after TTL so memory doesn't grow with every conversation.\n setTimeout(() => {\n const cur = runs.get(run.thread_id);\n if (cur === run) runs.delete(run.thread_id);\n }, RECENT_TTL_MS).unref?.();\n}\n\nexport function getRun(thread_id: string): ActiveRun | null {\n return runs.get(thread_id) ?? null;\n}\n\n// Signal the agent stream to cancel. The stream loop in the route is wired\n// to listen on the AbortController and exit early, emitting an error chunk\n// the client (and the queue-drain hook) can react to. Idempotent.\nexport function abortRun(thread_id: string, reason = \"user_interrupted\"): boolean {\n const run = runs.get(thread_id);\n if (!run || run.status !== \"running\") return false;\n if (!run.abort.signal.aborted) {\n try { run.abort.abort(reason); } catch { /* */ }\n }\n return true;\n}\n\n// Abort every currently-running run. Used by the graceful-shutdown path so\n// LangGraph stream loops bail out instead of continuing past process exit.\n// Returns the number of runs that were signalled.\nexport function abortAllRuns(reason = \"server_shutdown\"): number {\n let count = 0;\n for (const run of runs.values()) {\n if (run.status !== \"running\") continue;\n if (run.abort.signal.aborted) continue;\n try { run.abort.abort(reason); count++; } catch { /* */ }\n }\n return count;\n}\n\n// Poll until every run has transitioned out of \"running\" (or until the\n// caller-supplied deadline elapses). Used during graceful shutdown after\n// `abortAllRuns()` so the stream `finally` blocks have a chance to flush\n// the trailing error chunk and call `finishRun()`. Resolves to the count\n// of runs still stuck in \"running\" when the deadline hit (0 = clean).\nexport async function waitForRunsToSettle(timeoutMs: number): Promise<number> {\n const deadline = Date.now() + Math.max(0, timeoutMs);\n while (Date.now() < deadline) {\n let stillRunning = 0;\n for (const run of runs.values()) if (run.status === \"running\") stillRunning++;\n if (stillRunning === 0) return 0;\n await new Promise<void>((resolve) => setTimeout(resolve, 50));\n }\n let stillRunning = 0;\n for (const run of runs.values()) if (run.status === \"running\") stillRunning++;\n return stillRunning;\n}\n\n// Replays buffered events synchronously, then subscribes for live ones.\n// Returns an unsubscribe fn. Caller is responsible for calling it.\nexport function subscribe(\n thread_id: string,\n onEvent: Subscriber,\n): { run: ActiveRun | null; unsubscribe: () => void } {\n const run = runs.get(thread_id);\n if (!run) return { run: null, unsubscribe: () => {} };\n // Replay buffered events first (so the new subscriber catches up).\n for (const ev of run.events) {\n try { onEvent(ev); } catch { /* */ }\n }\n if (run.status !== \"running\") {\n return { run, unsubscribe: () => {} };\n }\n run.subscribers.add(onEvent);\n return {\n run,\n unsubscribe: () => { run.subscribers.delete(onEvent); },\n };\n}\n","import { NextRequest } from \"next/server\";\nimport type { StreamOptions, StreamChunk } from \"@/lib/agents/base\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport {\n prepareThreadRun,\n persistAssistantMessage,\n RunThreadError,\n shouldEmitChunk,\n} from \"@/lib/agents/run-thread\";\nimport { broadcast, finishRun, startRun, subscribe, abortRun, getRun } from \"@/lib/agents/run-registry\";\nimport { collectStream } from \"@/lib/agents/stream-collector\";\nimport { getThread } from \"@/lib/stores/threads\";\nimport { publish as publishNotification } from \"@/lib/notifications/bus\";\nimport { sseResponse } from \"@/lib/api/sse\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst enc = new TextEncoder();\nconst sse = (obj: Record<string, unknown>) => enc.encode(`data: ${JSON.stringify(obj)}\\n\\n`);\n\n// POST is the *command* half of the run lifecycle (ADR-0008). It accepts the\n// new user message, registers a run in the in-memory registry, kicks the\n// agent loop off in a detached async task, and returns 202 immediately. The\n// caller must follow up with a GET on this same path (as an `EventSource`)\n// to subscribe to the chunk stream — see GET below.\n//\n// Splitting submit from subscribe gives us a single reliable streaming\n// primitive across all browsers (EventSource is the only WebKit-native\n// streaming API that survives iOS Safari + Tailscale HTTP/2 proxies). It\n// also collapses what was previously a WS sidecar + SSE-over-POST +\n// SSE-GET-reattach trio into one transport.\nexport async function POST(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const { message, attachments, stream_options, hot_since } = (await req.json()) as {\n message: string;\n attachments?: ContentPart[];\n stream_options?: StreamOptions;\n // ADR-0042 — explicit context boundary the chat picked. ISO timestamp,\n // null to clear the pin, omitted to leave whatever's already persisted\n // on the thread.\n hot_since?: string | null;\n };\n\n // Connection-level handoff (NOT a kill). If a run is already in flight\n // for this thread — second tab, another device, a flaky-mobile retry —\n // refuse the new submission with 409. The caller is expected to:\n // 1) roll back any optimistic user bubble it added,\n // 2) re-queue the message locally to resubmit after the current turn\n // finishes,\n // 3) open the GET subscription so the user still sees the in-flight\n // turn's deltas render.\n const existing = getRun(thread_id);\n if (existing && existing.status === \"running\") {\n return new Response(\n JSON.stringify({ accepted: false, code: \"run_in_flight\", thread_id }),\n { status: 409, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n\n const thread = getThread(thread_id);\n const active = startRun(thread_id, thread?.agent_id ?? null);\n let prepared;\n try {\n prepared = await prepareThreadRun({\n thread_id,\n message,\n options: stream_options,\n attachments,\n signal: active.abort.signal,\n hot_since,\n });\n } catch (err) {\n // Prep failure (unknown agent, model misconfig, …) — drop the run we\n // just registered and surface a synchronous error to the caller.\n finishRun(active, \"error\");\n if (err instanceof RunThreadError) {\n return new Response(\n JSON.stringify({ accepted: false, error: err.message, code: err.code }),\n { status: err.status, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n return new Response(\n JSON.stringify({ accepted: false, error: String(err), code: \"run_prepare_error\" }),\n { status: 500, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n\n // Drive the agent to completion regardless of client connection. Events\n // go to the registry; the GET subscriber (and any reattaching clients)\n // receive them via subscribe().\n //\n // CRITICAL: finishRun() MUST run no matter what — if it doesn't, the\n // run is pinned as \"running\" forever, every subsequent POST returns\n // 409 run_in_flight, and the user sees a silently-dead chat. The TTL\n // eviction is scheduled inside finishRun(), so a leaked entry never\n // self-heals. Wrap the whole body in try/finally.\n void (async () => {\n let terminal: \"done\" | \"error\" = \"error\";\n let assistantContent = \"\";\n try {\n const collected = await collectStream(prepared.stream as AsyncIterable<StreamChunk>, {\n onChunk: (chunk) => broadcast(active, chunk),\n });\n assistantContent = collected.assistantContent;\n terminal = collected.terminal;\n // If the stream threw mid-iteration, collectStream returns terminal=\"error\"\n // but no `error` chunk was broadcast — surface one to subscribers.\n if (collected.terminal === \"error\" && collected.errorMessage) {\n broadcast(active, {\n type: \"error\",\n data: { message: collected.errorMessage, code: \"stream_error\" },\n });\n }\n try {\n persistAssistantMessage(thread_id, collected.assistantContent, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null);\n } catch (persistErr) {\n // Persistence failure must not strand the run — surface and continue\n // to finishRun in the finally block.\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: `persist failed: ${(persistErr as Error).message}`, code: \"persist_error\" },\n });\n }\n } catch (err) {\n // Unhandled throw from collectStream / the underlying stream. Without\n // this catch, finishRun would never run and the registry entry would\n // stick as \"running\" indefinitely (see CRITICAL note above).\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: (err as Error).message ?? String(err), code: \"run_crashed\" },\n });\n } finally {\n finishRun(active, terminal);\n publishNotification({\n type: \"run_completed\",\n thread_id,\n agent_id: thread?.agent_id ?? null,\n status: terminal,\n preview: assistantContent.replace(/\\s+/g, \" \").trim().slice(0, 120),\n ts: Date.now(),\n });\n }\n })();\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, started_at: active.started_at }),\n { status: 202, headers: { \"Content-Type\": \"application/json\" } },\n );\n}\n\n// GET is the *query* half of the run lifecycle (ADR-0008). Attaches to an\n// active (or recently-finished, within the registry TTL) run and streams\n// chunks as Server-Sent Events. Always consumed client-side via\n// `EventSource` — never `fetch().body.getReader()`, which is unreliable on\n// iOS Safari for long-lived streaming responses.\n//\n// Emits a single synthetic `done` event and closes when there's no run to\n// attach to (run never existed, or it finished + TTL-evicted before the GET\n// arrived). We deliberately do NOT return 404 here: browsers map a 404 SSE\n// response onto `EventSource.onerror` with no terminal event, which trips\n// EventSource's auto-reconnect logic and leaves the client in a \"stream\n// open but silent\" state — UIs gating on a `done` event hang forever\n// showing the Stop/Reconnecting affordances. A 200 with `data: {\"type\":\n// \"done\"}\\n\\n` makes the iterator drain cleanly on every transport.\n//\n// `show_tools` / `show_thinking` query params let the caller suppress\n// chunk types it doesn't want to render. Defaults: both on. The full\n// `StreamOptions` shape is only meaningful on the POST (tool policy &\n// agent run config are run-wide settings, not per-subscriber filters).\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const showTools = req.nextUrl.searchParams.get(\"show_tools\") !== \"false\";\n const showThinking = req.nextUrl.searchParams.get(\"show_thinking\") !== \"false\";\n const stream_options: StreamOptions = {\n filters: { include_tools: showTools, include_thinking: showThinking },\n };\n\n const run = getRun(thread_id);\n if (!run) {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(sse({ type: \"done\" }));\n controller.close();\n },\n });\n return sseResponse(stream);\n }\n\n return attachStream(thread_id, stream_options);\n}\n\n// DELETE aborts the currently-running agent for this thread. The agent stream\n// loop in llm.ts catches the resulting AbortError and emits a synthetic\n// `error` + `done` event pair so subscribers (and the client's queue-drain\n// hook) finish cleanly.\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const aborted = abortRun(thread_id, \"user_interrupted\");\n return new Response(JSON.stringify({ aborted }), {\n status: aborted ? 200 : 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction attachStream(\n thread_id: string,\n stream_options?: StreamOptions,\n): Response {\n const stream = new ReadableStream({\n start(controller) {\n let clientGone = false;\n const safeEnqueue = (chunk: Uint8Array): void => {\n if (clientGone) return;\n try { controller.enqueue(chunk); } catch { clientGone = true; }\n };\n\n const onEvent = (ev: StreamChunk) => {\n if (!shouldEmitChunk(ev.type, stream_options)) return;\n safeEnqueue(sse({ type: ev.type, ...ev.data }));\n };\n\n const { run, unsubscribe } = subscribe(thread_id, onEvent);\n if (!run) {\n controller.close();\n return;\n }\n\n // If run already terminal, close after replay.\n if (run.status !== \"running\") {\n try { controller.close(); } catch { /* */ }\n return;\n }\n\n // When the run finishes (status changes), close our response. We\n // poll lightly because the run might finish due to other subscribers'\n // signals; simpler than wiring a second listener channel.\n const poll = setInterval(() => {\n const r = getRun(thread_id);\n if (!r || r.status !== \"running\") {\n clearInterval(poll);\n unsubscribe();\n if (!clientGone) {\n try { controller.close(); } catch { /* */ }\n }\n }\n }, 500);\n poll.unref?.();\n },\n cancel() {\n // Client navigated away — agent run keeps going in registry.\n },\n });\n\n return sseResponse(stream);\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/threads/[thread_id]/run/route\",\n pathname: \"/api/v1/threads/[thread_id]/run\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/run/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/threads/[thread_id]/run/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:url\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["sseResponse","stream","opts","disableProxyBuffering","headers","Connection","Response","MAX_BUFFERED","RECENT_TTL_MS","runIdleMs","raw","Number","process","env","JARELA_RUN_IDLE_MS","isFinite","runMaxMs","JARELA_RUN_MAX_MS","runs","Map","startRun","thread_id","agent_id","existing","get","status","Error","now","Date","run","started_at","finished_at","events","subscribers","Set","final_text","abort","AbortController","last_chunk_at","set","scheduleIdleWatchdog","scheduleMaxWatchdog","idleMs","fireIn","Math","max","setTimeout","cur","idle","console","warn","finishRun","unref","broadcast","chunk","type","data","delta","length","push","fn","clear","delete","getRun","abortRun","reason","signal","aborted","abortAllRuns","count","values","waitForRunsToSettle","timeoutMs","deadline","stillRunning","Promise","resolve","subscribe","onEvent","unsubscribe","ev","add","prepareThreadRun","persistAssistantMessage","RunThreadError","shouldEmitChunk","collectStream","getThread","publish","publishNotification","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","message","attachments","stream_options","hot_since","json","accepted","code","thread","active","prepared","options","err","error","String","terminal","assistantContent","collected","onChunk","errorMessage","usedTools","toolEvents","usage","context_snapshot","persistErr","preview","replace","trim","slice","ts","GET","showTools","nextUrl","searchParams","showThinking","filters","include_tools","include_thinking","ReadableStream","start","controller","enqueue","close","attachStream","DELETE","_req","clientGone","safeEnqueue","poll","setInterval","r","clearInterval","cancel"],"sourceRoot":"","ignoreList":[0,4,6,10,16,27,38,40]}
@@ -113,8 +113,8 @@ var no_fallback_error_external_ = __webpack_require__(86439);
113
113
  var response_cache = __webpack_require__(37527);
114
114
  // EXTERNAL MODULE: ./node_modules/next/dist/api/server.js
115
115
  var server = __webpack_require__(23211);
116
- // EXTERNAL MODULE: ./lib/tools/index.ts + 18 modules
117
- var tools = __webpack_require__(33934);
116
+ // EXTERNAL MODULE: ./lib/tools/index.ts + 19 modules
117
+ var tools = __webpack_require__(23696);
118
118
  // EXTERNAL MODULE: ./lib/api/responses.ts
119
119
  var responses = __webpack_require__(39947);
120
120
  // EXTERNAL MODULE: ./lib/stores/tool-stats.ts