@circuitwall/jarela 0.14.0 → 1.0.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.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
- package/.next/standalone/.next/build-manifest.json +2 -2
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +2 -2
- package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/agents/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/agents/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +36 -29
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js +3 -3
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +4 -4
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/health/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/health/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/models/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/models/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +14 -7
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js +28 -0
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/providers/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/providers/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js +16 -2
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/threads/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/tools/route.js +10 -3
- package/.next/standalone/.next/server/app/api/v1/tools/route.js.map +1 -1
- package/.next/standalone/.next/server/app/index.html +2 -2
- package/.next/standalone/.next/server/app/index.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page.js +56 -0
- package/.next/standalone/.next/server/app/page.js.map +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup.html +1 -1
- package/.next/standalone/.next/server/app/setup.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/setup.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/setup/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/setup.segments/setup.segment.rsc +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +1 -1
- package/.next/standalone/.next/server/chunks/1683.js +2 -2
- package/.next/standalone/.next/server/chunks/2082.js +122 -13
- package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
- package/.next/standalone/.next/server/chunks/210.js +3 -3
- package/.next/standalone/.next/server/chunks/210.js.map +1 -1
- package/.next/standalone/.next/server/chunks/239.js +1902 -1487
- package/.next/standalone/.next/server/chunks/239.js.map +1 -1
- package/.next/standalone/.next/server/chunks/2447.js +9 -1
- package/.next/standalone/.next/server/chunks/2447.js.map +1 -1
- package/.next/standalone/.next/server/chunks/423.js +125 -16
- package/.next/standalone/.next/server/chunks/423.js.map +1 -1
- package/.next/standalone/.next/server/chunks/4631.js +36 -29
- package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
- package/.next/standalone/.next/server/chunks/5937.js +3 -2
- package/.next/standalone/.next/server/chunks/5937.js.map +1 -1
- package/.next/standalone/.next/server/chunks/{947.js → 8866.js} +11321 -10883
- package/.next/standalone/.next/server/chunks/8866.js.map +1 -0
- package/.next/standalone/.next/server/chunks/9032.js +3 -3
- package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
- package/.next/standalone/.next/server/middleware.js +122 -13
- package/.next/standalone/.next/server/pages/404.html +2 -2
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/proxy.js.map +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/static/chunks/app/{page-473b39ec30c7f569.js → page-a7cae65f235e2942.js} +57 -1
- package/.next/standalone/.next/static/chunks/app/page-a7cae65f235e2942.js.map +1 -0
- package/.next/standalone/.next/static/css/{6f8b1a84bcbcd467.css → e57bdbbbb5a05779.css} +2 -2
- package/.next/standalone/.next/static/css/e57bdbbbb5a05779.css.map +1 -0
- package/.next/standalone/package.json +9 -1
- package/CHANGELOG.md +90 -0
- package/README.md +30 -2
- package/api/types.ts +8 -0
- package/app/api/v1/agents/[id]/route.ts +7 -0
- package/app/api/v1/agents/route.ts +7 -0
- package/app/api/v1/events/route.ts +8 -0
- package/app/api/v1/extensions/route.ts +2 -2
- package/app/api/v1/extensions/tools/[name]/secrets/route.ts +3 -3
- package/app/api/v1/health/route.ts +8 -0
- package/app/api/v1/models/route.ts +7 -0
- package/app/api/v1/page-capture/route.ts +8 -0
- package/app/api/v1/providers/route.ts +8 -0
- package/app/api/v1/threads/[thread_id]/route.ts +8 -0
- package/app/api/v1/threads/[thread_id]/run/route.ts +9 -0
- package/app/api/v1/threads/route.ts +7 -0
- package/app/api/v1/tools/route.ts +9 -0
- package/components/chat/ContextUsageBar.tsx +44 -0
- package/lib/agents/llm.ts +25 -2
- package/lib/agents/run-thread.ts +13 -1
- package/lib/agents/stream-collector.ts +9 -1
- package/lib/api/serializers.test.ts +15 -0
- package/lib/api/serializers.ts +8 -0
- package/lib/db/migrations.ts +15 -0
- package/lib/health/runner.test.ts +24 -2
- package/lib/mcp/registry.ts +14 -6
- package/lib/providers/anthropic.test.ts +95 -0
- package/lib/providers/anthropic.ts +106 -10
- package/lib/providers/jarela-chat-model.ts +9 -1
- package/lib/providers/known-context-windows.ts +21 -0
- package/lib/providers/types.ts +21 -1
- package/lib/stores/message-usage.test.ts +34 -0
- package/lib/stores/message-usage.ts +15 -3
- package/lib/stores/pricing.test.ts +52 -0
- package/lib/stores/pricing.ts +26 -1
- package/lib/tools/builtins.ts +4 -0
- package/lib/tools/extension-surfaces.test.ts +79 -0
- package/lib/tools/extension-surfaces.ts +153 -0
- package/lib/tools/index.ts +27 -8
- package/lib/tools/list-tools.test.ts +76 -0
- package/lib/tools/list-tools.ts +84 -0
- package/lib/tools/mcp-servers-info.test.ts +73 -0
- package/lib/tools/mcp-servers-info.ts +71 -0
- package/lib/tools/providers-info.test.ts +73 -0
- package/lib/tools/providers-info.ts +106 -0
- package/lib/tools/registry.ts +36 -25
- package/lib/tools/types.ts +13 -0
- package/package.json +9 -1
- package/.next/standalone/.next/server/chunks/947.js.map +0 -1
- package/.next/standalone/.next/static/chunks/app/page-473b39ec30c7f569.js.map +0 -1
- package/.next/standalone/.next/static/css/6f8b1a84bcbcd467.css.map +0 -1
- /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_ssgManifest.js +0 -0
|
@@ -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,OAAO,CAAC,oBAAoB,GAAG;IAC1D,OAAO,IAAIE,SAASL,QAAQ;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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;;;;;;;;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/./lib/agents/run-registry.ts","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?2d5f","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","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\");","import type { StreamChunk } from \"./base\";\nimport { getConfig } from \"@/lib/env/config\";\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\n// Read once at module init. JARELA_RUN_BUFFER_SIZE / JARELA_RUN_REGISTRY_TTL_MS\n// override the defaults.\nconst MAX_BUFFERED = getConfig().runBufferSize;\nconst RECENT_TTL_MS = getConfig().runRegistryTtlMs;\n// Idle (no-progress) ceiling and wall-clock ceiling: read fresh per-run\n// from getConfig() so non-restart-required env reloads take effect.\nfunction runIdleMs(): number { return getConfig().runIdleMs; }\nfunction runMaxMs(): number { return getConfig().runMaxMs; }\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 // Tool-call ids that have been announced (tool_call) but not yet\n // resolved (tool_result). The idle watchdog pauses while this is\n // non-empty: silence between a tool_call and its tool_result is the\n // tool executing, not a wedged provider stream, and tools have their\n // own per-tool timeouts. The wall-clock watchdog is still the backstop.\n inflight_tools: Set<string>;\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 inflight_tools: new Set<string>(),\n };\n runs.set(thread_id, run);\n scheduleIdleWatchdog(run);\n scheduleMaxWatchdog(run);\n return run;\n}\n\n// Synthesise a typed error chunk for the watchdog termination paths and\n// fan it out to subscribers BEFORE flipping `status` to \"error\". The order\n// matters: `broadcast()`'s status guard drops any chunk delivered after\n// `finishRun()` has run, so calling finishRun first would silently swallow\n// the error and the client's EventSource would just see the connection\n// close with no terminal event — bubble keeps spinning, no toast. Doing\n// it the other way around lets the client receive a real error event,\n// render a \"Run timed out\" toast, and (if the consumer wires it up)\n// trigger an auto-retry path. Followed by `done` so the consumer's\n// for-await loop can break cleanly without waiting for an EOF.\nfunction emitWatchdogTermination(\n run: ActiveRun,\n code: \"run_idle_timeout\" | \"run_max_timeout\",\n message: string,\n): void {\n if (run.status !== \"running\") return;\n // Direct registry mutation so the broadcast goes through the regular\n // path (subscribers + buffer + seq stamp) without re-entering any of\n // the watchdog scheduling. Mirrors broadcast() but bypasses the\n // status check we'd otherwise be racing against.\n run.last_chunk_at = Date.now();\n const errChunk: StreamChunk = { type: \"error\", data: { message, code } };\n if (run.events.length < MAX_BUFFERED) run.events.push(errChunk);\n for (const fn of run.subscribers) {\n try { fn(errChunk); } catch { /* subscriber errored, ignore */ }\n }\n // Pair with a synthetic `done` so the client's consume() loop breaks\n // on a terminal event rather than waiting for the EventSource to close.\n const doneChunk: StreamChunk = { type: \"done\", data: {} };\n if (run.events.length < MAX_BUFFERED) run.events.push(doneChunk);\n for (const fn of run.subscribers) {\n try { fn(doneChunk); } catch { /* */ }\n }\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 if (run.inflight_tools.size > 0) {\n // Tool execution in progress — silence here is the tool working, not a\n // wedged provider stream. Skip the kill, re-check in idleMs. The\n // tool_result will bump last_chunk_at when it lands; the wall-clock\n // watchdog (runMaxMs) is still the backstop for a tool that never\n // resolves.\n setTimeout(() => scheduleIdleWatchdog(run), idleMs).unref?.();\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 emitWatchdogTermination(\n run,\n \"run_idle_timeout\",\n `Run timed out — no progress for ${Math.round(idle / 1000)}s. The provider stream went silent before the agent finished. Try again, or split the request into smaller steps.`,\n );\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 emitWatchdogTermination(\n run,\n \"run_max_timeout\",\n `Run exceeded the wall-clock limit (${Math.round(max / 1000)}s). The agent was force-stopped. Try a smaller scope or raise JARELA_RUN_MAX_MS if this is expected.`,\n );\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 } else if (chunk.type === \"tool_call\") {\n const id = (chunk.data as { id?: string }).id;\n if (id) run.inflight_tools.add(id);\n } else if (chunk.type === \"tool_result\") {\n const id = (chunk.data as { id?: string }).id;\n if (id) run.inflight_tools.delete(id);\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 { enqueueThreadRun, QueueFullError } from \"@/lib/agents/run-queue\";\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 // Per-thread FIFO queue (lib/agents/run-queue.ts). Every entry point\n // that drives an agent on a thread goes through this — HTTP POST,\n // scheduler, watcher, trigger, bridge — so concurrent fires on the same\n // thread_id serialise instead of racing the LangGraph checkpoint store.\n // If the queue is already at the soft cap, reject with 503 so the\n // caller can back off rather than pin yet more work in memory.\n const thread = getThread(thread_id);\n let position: number;\n try {\n ({ position } = enqueueThreadRun(thread_id, \"user\", async () => {\n // startRun is called once it's our turn so the registry only ever\n // holds one active entry per thread at a time. Subscribers that\n // attach via GET before our turn comes will see no run yet and the\n // SSE handler emits a synthetic done — the client reopens the\n // EventSource and picks up the stream once we're running.\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, …). With queueing\n // the HTTP request has already returned 202, so the error has to\n // surface as an SSE chunk to any attached subscriber. There may\n // be no subscriber if the GET hasn't connected yet — the chunk\n // is buffered on the ActiveRun for the next attach.\n const message_ = err instanceof RunThreadError ? err.message : String(err);\n const code = err instanceof RunThreadError ? err.code : \"run_prepare_error\";\n broadcast(active, { type: \"error\", data: { message: message_, code } });\n finishRun(active, \"error\");\n return;\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 and the TTL eviction (scheduled\n // inside finishRun()) never fires, so a leaked entry never self-heals.\n // Wrap the whole body in try/finally.\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, prepared.source_manifest ?? null);\n } catch (persistErr) {\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 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 } catch (err) {\n if (err instanceof QueueFullError) {\n return new Response(\n JSON.stringify({ accepted: false, code: \"queue_full\", thread_id, error: err.message }),\n { status: 503, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n throw err;\n }\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, queue_position: position }),\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(\"node:util\");","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","getConfig","MAX_BUFFERED","runBufferSize","RECENT_TTL_MS","runRegistryTtlMs","runIdleMs","runMaxMs","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","inflight_tools","set","scheduleIdleWatchdog","scheduleMaxWatchdog","emitWatchdogTermination","code","message","errChunk","type","data","length","push","fn","doneChunk","idleMs","fireIn","Math","max","setTimeout","cur","idle","size","unref","console","warn","round","finishRun","broadcast","chunk","delta","id","add","delete","clear","getRun","abortRun","reason","signal","aborted","abortAllRuns","count","values","waitForRunsToSettle","timeoutMs","deadline","stillRunning","Promise","resolve","subscribe","onEvent","unsubscribe","ev","prepareThreadRun","persistAssistantMessage","RunThreadError","shouldEmitChunk","enqueueThreadRun","QueueFullError","collectStream","getThread","publish","publishNotification","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","attachments","stream_options","hot_since","json","thread","position","active","prepared","options","err","message_","String","terminal","assistantContent","collected","onChunk","errorMessage","usedTools","toolEvents","usage","context_snapshot","source_manifest","persistErr","preview","replace","trim","slice","ts","accepted","error","queue_position","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]}
|
|
1
|
+
{"version":3,"file":"../app/api/v1/threads/[thread_id]/run/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;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AY,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;;;;;;;;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/./lib/agents/run-registry.ts","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?2d5f","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","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\");","import type { StreamChunk } from \"./base\";\nimport { getConfig } from \"@/lib/env/config\";\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\n// Read once at module init. JARELA_RUN_BUFFER_SIZE / JARELA_RUN_REGISTRY_TTL_MS\n// override the defaults.\nconst MAX_BUFFERED = getConfig().runBufferSize;\nconst RECENT_TTL_MS = getConfig().runRegistryTtlMs;\n// Idle (no-progress) ceiling and wall-clock ceiling: read fresh per-run\n// from getConfig() so non-restart-required env reloads take effect.\nfunction runIdleMs(): number { return getConfig().runIdleMs; }\nfunction runMaxMs(): number { return getConfig().runMaxMs; }\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 // Tool-call ids that have been announced (tool_call) but not yet\n // resolved (tool_result). The idle watchdog pauses while this is\n // non-empty: silence between a tool_call and its tool_result is the\n // tool executing, not a wedged provider stream, and tools have their\n // own per-tool timeouts. The wall-clock watchdog is still the backstop.\n inflight_tools: Set<string>;\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 inflight_tools: new Set<string>(),\n };\n runs.set(thread_id, run);\n scheduleIdleWatchdog(run);\n scheduleMaxWatchdog(run);\n return run;\n}\n\n// Synthesise a typed error chunk for the watchdog termination paths and\n// fan it out to subscribers BEFORE flipping `status` to \"error\". The order\n// matters: `broadcast()`'s status guard drops any chunk delivered after\n// `finishRun()` has run, so calling finishRun first would silently swallow\n// the error and the client's EventSource would just see the connection\n// close with no terminal event — bubble keeps spinning, no toast. Doing\n// it the other way around lets the client receive a real error event,\n// render a \"Run timed out\" toast, and (if the consumer wires it up)\n// trigger an auto-retry path. Followed by `done` so the consumer's\n// for-await loop can break cleanly without waiting for an EOF.\nfunction emitWatchdogTermination(\n run: ActiveRun,\n code: \"run_idle_timeout\" | \"run_max_timeout\",\n message: string,\n): void {\n if (run.status !== \"running\") return;\n // Direct registry mutation so the broadcast goes through the regular\n // path (subscribers + buffer + seq stamp) without re-entering any of\n // the watchdog scheduling. Mirrors broadcast() but bypasses the\n // status check we'd otherwise be racing against.\n run.last_chunk_at = Date.now();\n const errChunk: StreamChunk = { type: \"error\", data: { message, code } };\n if (run.events.length < MAX_BUFFERED) run.events.push(errChunk);\n for (const fn of run.subscribers) {\n try { fn(errChunk); } catch { /* subscriber errored, ignore */ }\n }\n // Pair with a synthetic `done` so the client's consume() loop breaks\n // on a terminal event rather than waiting for the EventSource to close.\n const doneChunk: StreamChunk = { type: \"done\", data: {} };\n if (run.events.length < MAX_BUFFERED) run.events.push(doneChunk);\n for (const fn of run.subscribers) {\n try { fn(doneChunk); } catch { /* */ }\n }\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 if (run.inflight_tools.size > 0) {\n // Tool execution in progress — silence here is the tool working, not a\n // wedged provider stream. Skip the kill, re-check in idleMs. The\n // tool_result will bump last_chunk_at when it lands; the wall-clock\n // watchdog (runMaxMs) is still the backstop for a tool that never\n // resolves.\n setTimeout(() => scheduleIdleWatchdog(run), idleMs).unref?.();\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 emitWatchdogTermination(\n run,\n \"run_idle_timeout\",\n `Run timed out — no progress for ${Math.round(idle / 1000)}s. The provider stream went silent before the agent finished. Try again, or split the request into smaller steps.`,\n );\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 emitWatchdogTermination(\n run,\n \"run_max_timeout\",\n `Run exceeded the wall-clock limit (${Math.round(max / 1000)}s). The agent was force-stopped. Try a smaller scope or raise JARELA_RUN_MAX_MS if this is expected.`,\n );\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 } else if (chunk.type === \"tool_call\") {\n const id = (chunk.data as { id?: string }).id;\n if (id) run.inflight_tools.add(id);\n } else if (chunk.type === \"tool_result\") {\n const id = (chunk.data as { id?: string }).id;\n if (id) run.inflight_tools.delete(id);\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","/**\n * @public — `POST /api/v1/threads/[thread_id]/run` (submit run),\n * `GET /api/v1/threads/[thread_id]/run` (subscribe via SSE)\n *\n * Agent execution endpoint. Submit a run, then stream tokens, tool\n * calls, and final state. The split-and-subscribe shape lets reconnects\n * pick up an in-flight stream. See `docs/api.md`.\n */\n\nimport { 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 { enqueueThreadRun, QueueFullError } from \"@/lib/agents/run-queue\";\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 // Per-thread FIFO queue (lib/agents/run-queue.ts). Every entry point\n // that drives an agent on a thread goes through this — HTTP POST,\n // scheduler, watcher, trigger, bridge — so concurrent fires on the same\n // thread_id serialise instead of racing the LangGraph checkpoint store.\n // If the queue is already at the soft cap, reject with 503 so the\n // caller can back off rather than pin yet more work in memory.\n const thread = getThread(thread_id);\n let position: number;\n try {\n ({ position } = enqueueThreadRun(thread_id, \"user\", async () => {\n // startRun is called once it's our turn so the registry only ever\n // holds one active entry per thread at a time. Subscribers that\n // attach via GET before our turn comes will see no run yet and the\n // SSE handler emits a synthetic done — the client reopens the\n // EventSource and picks up the stream once we're running.\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, …). With queueing\n // the HTTP request has already returned 202, so the error has to\n // surface as an SSE chunk to any attached subscriber. There may\n // be no subscriber if the GET hasn't connected yet — the chunk\n // is buffered on the ActiveRun for the next attach.\n const message_ = err instanceof RunThreadError ? err.message : String(err);\n const code = err instanceof RunThreadError ? err.code : \"run_prepare_error\";\n broadcast(active, { type: \"error\", data: { message: message_, code } });\n finishRun(active, \"error\");\n return;\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 and the TTL eviction (scheduled\n // inside finishRun()) never fires, so a leaked entry never self-heals.\n // Wrap the whole body in try/finally.\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, prepared.source_manifest ?? null);\n } catch (persistErr) {\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 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 } catch (err) {\n if (err instanceof QueueFullError) {\n return new Response(\n JSON.stringify({ accepted: false, code: \"queue_full\", thread_id, error: err.message }),\n { status: 503, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n throw err;\n }\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, queue_position: position }),\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(\"node:util\");","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","getConfig","MAX_BUFFERED","runBufferSize","RECENT_TTL_MS","runRegistryTtlMs","runIdleMs","runMaxMs","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","inflight_tools","set","scheduleIdleWatchdog","scheduleMaxWatchdog","emitWatchdogTermination","code","message","errChunk","type","data","length","push","fn","doneChunk","idleMs","fireIn","Math","max","setTimeout","cur","idle","size","unref","console","warn","round","finishRun","broadcast","chunk","delta","id","add","delete","clear","getRun","abortRun","reason","signal","aborted","abortAllRuns","count","values","waitForRunsToSettle","timeoutMs","deadline","stillRunning","Promise","resolve","subscribe","onEvent","unsubscribe","ev","prepareThreadRun","persistAssistantMessage","RunThreadError","shouldEmitChunk","enqueueThreadRun","QueueFullError","collectStream","getThread","publish","publishNotification","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","attachments","stream_options","hot_since","json","thread","position","active","prepared","options","err","message_","String","terminal","assistantContent","collected","onChunk","errorMessage","usedTools","toolEvents","usage","context_snapshot","source_manifest","persistErr","preview","replace","trim","slice","ts","accepted","error","queue_position","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]}
|
|
@@ -121,7 +121,12 @@ var agent_configs = __webpack_require__(41720);
|
|
|
121
121
|
// EXTERNAL MODULE: ./lib/api/responses.ts
|
|
122
122
|
var responses = __webpack_require__(39947);
|
|
123
123
|
;// ./app/api/v1/threads/route.ts
|
|
124
|
-
|
|
124
|
+
/**
|
|
125
|
+
* @public — `GET /api/v1/threads` (list), `POST /api/v1/threads` (create)
|
|
126
|
+
*
|
|
127
|
+
* Thread lifecycle. Threads are the unit of conversation history; every
|
|
128
|
+
* agent run lives inside one. See `docs/api.md`.
|
|
129
|
+
*/
|
|
125
130
|
|
|
126
131
|
|
|
127
132
|
|