@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.
Files changed (164) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  6. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  18. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  23. package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js +6 -1
  24. package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js.map +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/agents/route.js +6 -1
  26. package/.next/standalone/.next/server/app/api/v1/agents/route.js.map +1 -1
  27. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +9 -1
  28. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.map +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/bridges/route.js +9 -1
  30. package/.next/standalone/.next/server/app/api/v1/bridges/route.js.map +1 -1
  31. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +36 -29
  32. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
  33. package/.next/standalone/.next/server/app/api/v1/events/route.js +7 -1
  34. package/.next/standalone/.next/server/app/api/v1/events/route.js.map +1 -1
  35. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +3 -3
  36. package/.next/standalone/.next/server/app/api/v1/extensions/route.js.map +1 -1
  37. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +4 -4
  38. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.map +1 -1
  39. package/.next/standalone/.next/server/app/api/v1/health/route.js +7 -1
  40. package/.next/standalone/.next/server/app/api/v1/health/route.js.map +1 -1
  41. package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js +9 -1
  42. package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js.map +1 -1
  43. package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js +9 -1
  44. package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js.map +1 -1
  45. package/.next/standalone/.next/server/app/api/v1/models/route.js +6 -1
  46. package/.next/standalone/.next/server/app/api/v1/models/route.js.map +1 -1
  47. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +7 -1
  48. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
  49. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +14 -7
  50. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.map +1 -1
  51. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js +28 -0
  52. package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js.map +1 -1
  53. package/.next/standalone/.next/server/app/api/v1/providers/route.js +7 -1
  54. package/.next/standalone/.next/server/app/api/v1/providers/route.js.map +1 -1
  55. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js +16 -2
  56. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js.map +1 -1
  57. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +8 -1
  58. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
  59. package/.next/standalone/.next/server/app/api/v1/threads/route.js +6 -1
  60. package/.next/standalone/.next/server/app/api/v1/threads/route.js.map +1 -1
  61. package/.next/standalone/.next/server/app/api/v1/tools/route.js +10 -3
  62. package/.next/standalone/.next/server/app/api/v1/tools/route.js.map +1 -1
  63. package/.next/standalone/.next/server/app/index.html +2 -2
  64. package/.next/standalone/.next/server/app/index.rsc +3 -3
  65. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  66. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  67. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  68. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
  69. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  70. package/.next/standalone/.next/server/app/page.js +56 -0
  71. package/.next/standalone/.next/server/app/page.js.map +1 -1
  72. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  73. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  74. package/.next/standalone/.next/server/app/setup.html +1 -1
  75. package/.next/standalone/.next/server/app/setup.rsc +2 -2
  76. package/.next/standalone/.next/server/app/setup.segments/_full.segment.rsc +2 -2
  77. package/.next/standalone/.next/server/app/setup.segments/_head.segment.rsc +1 -1
  78. package/.next/standalone/.next/server/app/setup.segments/_index.segment.rsc +2 -2
  79. package/.next/standalone/.next/server/app/setup.segments/_tree.segment.rsc +2 -2
  80. package/.next/standalone/.next/server/app/setup.segments/setup/__PAGE__.segment.rsc +1 -1
  81. package/.next/standalone/.next/server/app/setup.segments/setup.segment.rsc +1 -1
  82. package/.next/standalone/.next/server/app-paths-manifest.json +1 -1
  83. package/.next/standalone/.next/server/chunks/1683.js +2 -2
  84. package/.next/standalone/.next/server/chunks/2082.js +122 -13
  85. package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
  86. package/.next/standalone/.next/server/chunks/210.js +3 -3
  87. package/.next/standalone/.next/server/chunks/210.js.map +1 -1
  88. package/.next/standalone/.next/server/chunks/239.js +1902 -1487
  89. package/.next/standalone/.next/server/chunks/239.js.map +1 -1
  90. package/.next/standalone/.next/server/chunks/2447.js +9 -1
  91. package/.next/standalone/.next/server/chunks/2447.js.map +1 -1
  92. package/.next/standalone/.next/server/chunks/423.js +125 -16
  93. package/.next/standalone/.next/server/chunks/423.js.map +1 -1
  94. package/.next/standalone/.next/server/chunks/4631.js +36 -29
  95. package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
  96. package/.next/standalone/.next/server/chunks/5937.js +3 -2
  97. package/.next/standalone/.next/server/chunks/5937.js.map +1 -1
  98. package/.next/standalone/.next/server/chunks/{947.js → 8866.js} +11321 -10883
  99. package/.next/standalone/.next/server/chunks/8866.js.map +1 -0
  100. package/.next/standalone/.next/server/chunks/9032.js +3 -3
  101. package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
  102. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  103. package/.next/standalone/.next/server/middleware.js +122 -13
  104. package/.next/standalone/.next/server/pages/404.html +2 -2
  105. package/.next/standalone/.next/server/pages/500.html +1 -1
  106. package/.next/standalone/.next/server/proxy.js.map +1 -1
  107. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  108. package/.next/standalone/.next/static/chunks/app/{page-473b39ec30c7f569.js → page-a7cae65f235e2942.js} +57 -1
  109. package/.next/standalone/.next/static/chunks/app/page-a7cae65f235e2942.js.map +1 -0
  110. package/.next/standalone/.next/static/css/{6f8b1a84bcbcd467.css → e57bdbbbb5a05779.css} +2 -2
  111. package/.next/standalone/.next/static/css/e57bdbbbb5a05779.css.map +1 -0
  112. package/.next/standalone/package.json +9 -1
  113. package/CHANGELOG.md +90 -0
  114. package/README.md +30 -2
  115. package/api/types.ts +8 -0
  116. package/app/api/v1/agents/[id]/route.ts +7 -0
  117. package/app/api/v1/agents/route.ts +7 -0
  118. package/app/api/v1/events/route.ts +8 -0
  119. package/app/api/v1/extensions/route.ts +2 -2
  120. package/app/api/v1/extensions/tools/[name]/secrets/route.ts +3 -3
  121. package/app/api/v1/health/route.ts +8 -0
  122. package/app/api/v1/models/route.ts +7 -0
  123. package/app/api/v1/page-capture/route.ts +8 -0
  124. package/app/api/v1/providers/route.ts +8 -0
  125. package/app/api/v1/threads/[thread_id]/route.ts +8 -0
  126. package/app/api/v1/threads/[thread_id]/run/route.ts +9 -0
  127. package/app/api/v1/threads/route.ts +7 -0
  128. package/app/api/v1/tools/route.ts +9 -0
  129. package/components/chat/ContextUsageBar.tsx +44 -0
  130. package/lib/agents/llm.ts +25 -2
  131. package/lib/agents/run-thread.ts +13 -1
  132. package/lib/agents/stream-collector.ts +9 -1
  133. package/lib/api/serializers.test.ts +15 -0
  134. package/lib/api/serializers.ts +8 -0
  135. package/lib/db/migrations.ts +15 -0
  136. package/lib/health/runner.test.ts +24 -2
  137. package/lib/mcp/registry.ts +14 -6
  138. package/lib/providers/anthropic.test.ts +95 -0
  139. package/lib/providers/anthropic.ts +106 -10
  140. package/lib/providers/jarela-chat-model.ts +9 -1
  141. package/lib/providers/known-context-windows.ts +21 -0
  142. package/lib/providers/types.ts +21 -1
  143. package/lib/stores/message-usage.test.ts +34 -0
  144. package/lib/stores/message-usage.ts +15 -3
  145. package/lib/stores/pricing.test.ts +52 -0
  146. package/lib/stores/pricing.ts +26 -1
  147. package/lib/tools/builtins.ts +4 -0
  148. package/lib/tools/extension-surfaces.test.ts +79 -0
  149. package/lib/tools/extension-surfaces.ts +153 -0
  150. package/lib/tools/index.ts +27 -8
  151. package/lib/tools/list-tools.test.ts +76 -0
  152. package/lib/tools/list-tools.ts +84 -0
  153. package/lib/tools/mcp-servers-info.test.ts +73 -0
  154. package/lib/tools/mcp-servers-info.ts +71 -0
  155. package/lib/tools/providers-info.test.ts +73 -0
  156. package/lib/tools/providers-info.ts +106 -0
  157. package/lib/tools/registry.ts +36 -25
  158. package/lib/tools/types.ts +13 -0
  159. package/package.json +9 -1
  160. package/.next/standalone/.next/server/chunks/947.js.map +0 -1
  161. package/.next/standalone/.next/static/chunks/app/page-473b39ec30c7f569.js.map +0 -1
  162. package/.next/standalone/.next/static/css/6f8b1a84bcbcd467.css.map +0 -1
  163. /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_buildManifest.js +0 -0
  164. /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]/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAwD;AAO1B;AACoC;AACN;AACe;AACW;AAC1B;AAI5D,MAAMY,eAAe;AACrB,MAAMC,gCAAgC;AAE/B,eAAeC,IAAIC,GAAgB,EAAE,EAAEC,MAAM,EAAU;IAC5D,MAAM,EAAEC,SAAS,EAAE,GAAG,MAAMD;IAC5B,MAAME,SAASd,6BAASA,CAACa;IACzB,IAAI,CAACC,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AAW;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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B;IAChD;AACF;AAEA;;;;;CAKC,GACM,SAASzC,kBACd8B,CAAa,EACbI,SAA+C;IAE/C,OAAO;QACLyC,IAAI7C,EAAEG,MAAM;QACZF,MAAMD,EAAEC,IAAI;QACZ6J,SAAS9J,EAAE8J,OAAO;QAClBhG,YAAY9D,EAAE8D,UAAU;QACxBiG,aAAaC,2BAA2BhK,EAAE+J,WAAW;QACrDE,UAAUjK,EAAEiK,QAAQ,IAAI;QACxBC,OAAOf,uBAAuB/I,UAAUb,GAAG,CAACS,EAAEG,MAAM;QACpDgK,UAAUC,gCAAgCpK,EAAEmK,QAAQ;IACtD;AACF;AAEA;;iDAEiD,GAC1C,SAASH,2BAA2BlI,GAA8B;IACvE,IAAI,CAACA,KAAK,OAAOrC;IACjB,IAAI;QACF,MAAMuC,SAASC,KAAKC,KAAK,CAACJ;QAC1B,OAAOmB,MAAMC,OAAO,CAAClB,UAAUA,SAASvC;IAC1C,EAAE,OAAM;QACN,OAAOA;IACT;AACF;AAEA;;sEAEsE,GAC/D,SAAS2K,gCAAgCtI,GAA8B;IAC5E,IAAI,CAACA,KAAK,OAAO;IACjB,IAAI;QACF,MAAME,SAASC,KAAKC,KAAK,CAACJ;QAC1B,IAAI,CAACE,UAAU,OAAOA,WAAW,YAAYiB,MAAMC,OAAO,CAAClB,SAAS,OAAO;QAC3E,OAAOA;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;CAMC,GACM,SAAS7D,2BACdkM,qBAAgD,EAChDC,aAAqB;IAErB,IAAI,OAAOD,0BAA0B,YAAYA,wBAAwB,GAAG;QAC1E,OAAOA;IACT;IACA,OAAOC;AACT;;;;;;;;ACjKA;;;;;;;ACAA","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 \"next/dist/server/app-render/after-task-async-storage.external.js\"","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/route.ts","webpack://@circuitwall/jarela/?3c22","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/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/./lib/stores/agent-configs.ts","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/utils/json.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/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:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/./lib/api/serializers.ts","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","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(\"next/dist/server/app-render/after-task-async-storage.external.js\");","import { NextRequest, NextResponse } from \"next/server\";\nimport {\n deleteThread,\n getMessagesAfter,\n getMessagesPage,\n getThread,\n type MessageRow,\n} from \"@/lib/stores/threads\";\nimport { getMessageUsageByIds } from \"@/lib/stores/message-usage\";\nimport { getAgentConfig } from \"@/lib/stores/agent-configs\";\nimport { getModelConfig, getModelParams } from \"@/lib/stores/model-config\";\nimport { messageToResponse, resolveContextWindowTokens } from \"@/lib/api/serializers\";\nimport { getCheckpointer } from \"@/lib/agents/checkpointer\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst DEFAULT_PAGE = 50;\nconst DEFAULT_CONTEXT_WINDOW_TOKENS = 8_192;\n\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const thread = getThread(thread_id);\n if (!thread) return NextResponse.json({ error: \"Thread not found\" }, { status: 404 });\n\n const url = new URL(req.url);\n const limit = Math.max(1, Math.min(200, Number(url.searchParams.get(\"limit\")) || DEFAULT_PAGE));\n const before = url.searchParams.get(\"before\") ?? undefined;\n const after = url.searchParams.get(\"after\") ?? undefined;\n\n // `after` is a forward-fetch shortcut: caller (typically ChatView's\n // run-completion handler) already has the recent messages and just wants\n // the freshly-persisted ones. has_more is fixed to false because the\n // forward window is not paginated — caller already has everything older.\n let messages: MessageRow[];\n let has_more: boolean;\n if (after) {\n messages = getMessagesAfter(thread_id, after, limit);\n has_more = false;\n } else {\n const page = getMessagesPage(thread_id, limit, before);\n messages = page.messages;\n has_more = page.has_more;\n }\n\n // Attach per-assistant-turn usage so the chat UI can render a context\n // utilisation bar without an extra round-trip per message. User turns\n // and legacy assistant rows (pre-message_usage table) simply omit the\n // field.\n const assistantIds = messages.filter((m) => m.role === \"assistant\").map((m) => m.msg_id);\n const usageById = getMessageUsageByIds(assistantIds);\n\n // Resolve the agent's effective context-window size once for the whole\n // thread. The bar scales against this cap so the visual matches the\n // budget the agent applies at run time.\n const agentCfg = getAgentConfig(thread.agent_id);\n const modelCfg = agentCfg?.model_config_name ? getModelConfig(agentCfg.model_config_name) : null;\n const modelParams = modelCfg ? getModelParams(modelCfg) : null;\n const rawCtx = modelParams?.context_window_tokens;\n const contextWindowTokens = resolveContextWindowTokens(\n typeof rawCtx === \"number\" ? rawCtx : null,\n DEFAULT_CONTEXT_WINDOW_TOKENS,\n );\n\n return NextResponse.json({\n ...thread,\n context_window_tokens: contextWindowTokens,\n // No server-side filtering: clients receive every message with its\n // `category` tag and apply the chat-panel filter toolbar on the\n // render side. Keeping the raw transcript over the wire means audit\n // history is reachable from any client without round-trip params.\n messages: messages.map((m) => messageToResponse(m, usageById)),\n has_more,\n });\n}\n\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const deleted = deleteThread(thread_id);\n if (!deleted) return NextResponse.json({ error: \"Thread not found\" }, { status: 404 });\n\n // Drop the thread's LangGraph checkpoint rows too. Without this the\n // checkpoints.db file grows forever as users delete threads — the rows\n // are orphaned because the per-turn wipe in lib/agents/llm.ts only\n // runs for active threads.\n try {\n await getCheckpointer().deleteThread(thread_id);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!/no such table:\\s*checkpoints/i.test(msg)) {\n console.error(\"[threads] checkpoint cleanup failed for thread\", thread_id, err);\n }\n }\n\n return NextResponse.json({ deleted: true });\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]/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]/route\",\n pathname: \"/api/v1/threads/[thread_id]\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/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]/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]/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]/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(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","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\");","import { getDb } from \"@/lib/db\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport interface AgentConfigRow {\n id: string;\n name: string;\n icon: string | null;\n identity: string;\n instructions: string;\n tools: string; // JSON string[]\n model_config_name: string | null;\n is_default: number;\n history_limit: number; // 0 = unlimited\n history_window_hours: number; // 0 = no time bound\n never_reply: number; // 1 = run the agent but don't auto-send replies via bridges\n adaptive_persona_enabled: number; // 1 = use runtime mood/tone adaptation hints\n adaptive_persona_strength: number; // 0..100, how strongly to adapt to cues\n adaptive_empathy: number; // 0..100, baseline empathetic tone\n adaptive_expressiveness: number; // 0..100, restrained -> energetic\n adaptive_verbosity: number; // 0..100, concise -> detailed\n adaptive_mbti: string; // one of 16 MBTI types\n voice_enabled: number; // 1 = expose mic/play UI for this agent\n voice_model: string; // Gemini TTS model id\n voice_name: string; // Gemini prebuilt voice name (Kore, Puck, …)\n voice_stt_model: string; // Gemini multimodal model used for transcription\n voice_auto_speak: number; // 1 = auto-play reply when user sent voice\n display_filters: string | null; // JSON: Partial<DisplayFilters>; NULL = inherit defaults (ADR-0022)\n harness_id: string | null; // ADR-0033: per-agent harness override; NULL = inherit global default\n delegate_targets: string | null; // JSON string[] of agent ids this agent may delegate to; NULL/'[]' = none\n // ADR-0043. JSON-encoded `{ hot, warm, facts }` — any positive numbers; the\n // backend divides by sum so the UI can ship raw weights and never has to\n // reconcile to 100. NULL = inherit the model config's value.\n context_tier_proportions: string | null;\n // Per-agent override of the anti-hallucination classifier mode/model.\n // NULL on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob.\n anti_hallucination_mode: string | null; // \"off\" | \"report\" | \"enforce\"\n anti_hallucination_model_config: string | null; // saved model config name\n // When 1, the system prompt is augmented with a citation-link directive\n // and the assistant turn is post-checked by `anti_hallucination_model_config`\n // for {source link present, source previously visited in this thread}.\n // Independent of `anti_hallucination_mode` — stall detection and citation\n // enforcement can be on/off in any combination.\n require_source_links: number;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentTierProportions {\n hot: number;\n warm: number;\n facts: number;\n}\n\n/**\n * Parse the JSON-encoded per-agent override of context tier proportions.\n * Returns `null` for NULL, blank, malformed JSON, or any payload that\n * doesn't have three finite non-negative numeric fields. Callers fall\n * back to the model config's value (or built-in defaults) on null.\n */\nexport function getAgentTierProportions(row: AgentConfigRow): AgentTierProportions | null {\n const raw = row.context_tier_proportions;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<AgentTierProportions>;\n const hot = Number(parsed.hot);\n const warm = Number(parsed.warm);\n const facts = Number(parsed.facts);\n if (![hot, warm, facts].every((n) => Number.isFinite(n) && n >= 0)) return null;\n if (hot + warm + facts <= 0) return null;\n return { hot, warm, facts };\n } catch {\n return null;\n }\n}\n\nexport function listAgentConfigs(): AgentConfigRow[] {\n return getDb()\n .prepare(\"SELECT * FROM agent_configs ORDER BY is_default DESC, created_at ASC\")\n .all() as unknown as AgentConfigRow[];\n}\n\nexport function getDefaultAgentConfig(): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE is_default=1 LIMIT 1\")\n .get() as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport function getAgentConfig(id: string): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE id=?\")\n .get(id) as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport interface UpsertAgentInput {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n model_config_name?: string | null;\n is_default?: boolean;\n history_limit?: number;\n history_window_hours?: number;\n never_reply?: boolean;\n adaptive_persona_enabled?: boolean;\n adaptive_persona_strength?: number;\n adaptive_empathy?: number;\n adaptive_expressiveness?: number;\n adaptive_verbosity?: number;\n adaptive_mbti?: MbtiType;\n voice_enabled?: boolean;\n voice_model?: string;\n voice_name?: string;\n voice_stt_model?: string;\n voice_auto_speak?: boolean;\n harness_id?: string | null;\n delegate_targets?: string[];\n // ADR-0043. Pass `null` to clear the override and inherit from the model.\n // Pass `undefined` to keep whatever's already on the row (PATCH semantics).\n context_tier_proportions?: AgentTierProportions | null;\n // Per-agent anti-hallucination classifier override. `null` = clear the\n // override (inherit env). `undefined` = keep existing.\n anti_hallucination_mode?: \"off\" | \"regex\" | \"model\" | null;\n anti_hallucination_model_config?: string | null;\n // Citation enforcement (independent of stall detector). `undefined` = keep\n // existing. `false` = disable.\n require_source_links?: boolean;\n}\n\n/**\n * Parse the JSON-encoded delegate whitelist into a deduped string[]. Returns\n * an empty array for NULL, blank, or malformed JSON (delegation is opt-in).\n */\n/**\n * Parse the agent's tool allowlist (`tools` column, stored as a JSON string).\n * Returns an empty array on NULL/blank/malformed JSON — same defensive shape\n * as parseDelegateTargets. Callers that previously did `JSON.parse(cfg.tools)`\n * inline should switch to this getter so the serialization contract stays\n * owned by this store.\n */\nexport function getAgentTools(cfg: Pick<AgentConfigRow, \"tools\"> | null | undefined): string[] {\n if (!cfg?.tools) return [];\n try {\n const parsed = JSON.parse(cfg.tools);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n } catch {\n return [];\n }\n}\n\nexport function parseDelegateTargets(raw: string | null | undefined): string[] {\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n const ids = parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n return Array.from(new Set(ids));\n } catch {\n return [];\n }\n}\n\nexport function upsertAgentConfig(input: UpsertAgentInput): AgentConfigRow {\n const t = now();\n const db = getDb();\n const existing = getAgentConfig(input.id);\n const created_at = existing?.created_at ?? t;\n const mbti = input.adaptive_mbti ?? toMbti(existing?.adaptive_mbti) ?? \"INTJ\";\n const preset = MBTI_PRESETS[mbti];\n const strength = input.adaptive_persona_strength ?? preset.strength;\n const empathy = input.adaptive_empathy ?? preset.empathy;\n const expressiveness = input.adaptive_expressiveness ?? preset.expressiveness;\n const verbosity = input.adaptive_verbosity ?? preset.verbosity;\n if (input.is_default) db.prepare(\"UPDATE agent_configs SET is_default=0\").run();\n // harness_id: explicit `undefined` means \"keep existing\"; explicit `null`\n // means \"use the global default\". Empty string is normalised to null too,\n // matching how the AgentEditor sends \"\" for the inherit option.\n const harnessId =\n input.harness_id === undefined\n ? (existing?.harness_id ?? null)\n : (input.harness_id && input.harness_id.length > 0 ? input.harness_id : null);\n // delegate_targets: undefined = keep existing; explicit empty array clears.\n const delegateTargets = input.delegate_targets === undefined\n ? (existing?.delegate_targets ?? null)\n : JSON.stringify(Array.from(new Set(input.delegate_targets.filter((id) => id && id !== input.id))));\n // context_tier_proportions: undefined = keep existing; null = clear and\n // inherit from the model; object = serialise as JSON. Negative values are\n // clamped to 0 so the upsert can't poison the column with bad data.\n const tierProportions =\n input.context_tier_proportions === undefined\n ? (existing?.context_tier_proportions ?? null)\n : input.context_tier_proportions === null\n ? null\n : JSON.stringify({\n hot: Math.max(0, Number(input.context_tier_proportions.hot) || 0),\n warm: Math.max(0, Number(input.context_tier_proportions.warm) || 0),\n facts: Math.max(0, Number(input.context_tier_proportions.facts) || 0),\n });\n // Anti-hallucination override: `undefined` keeps existing; `null` clears\n // the override (inherits env). Empty-string model is normalised to null\n // so the editor can ship \"\" for the inherit option.\n const antiHallucMode =\n input.anti_hallucination_mode === undefined\n ? (existing?.anti_hallucination_mode ?? null)\n : input.anti_hallucination_mode === null\n ? null\n : (input.anti_hallucination_mode === \"off\" || input.anti_hallucination_mode === \"regex\" || input.anti_hallucination_mode === \"model\")\n ? input.anti_hallucination_mode\n : null;\n const antiHallucModel =\n input.anti_hallucination_model_config === undefined\n ? (existing?.anti_hallucination_model_config ?? null)\n : input.anti_hallucination_model_config && input.anti_hallucination_model_config.trim().length > 0\n ? input.anti_hallucination_model_config.trim()\n : null;\n const requireSourceLinks =\n input.require_source_links === undefined\n ? (existing?.require_source_links ?? 0)\n : (input.require_source_links ? 1 : 0);\n db.prepare(\n `INSERT OR REPLACE INTO agent_configs\n (id, name, icon, identity, instructions, tools, model_config_name, is_default,\n history_limit, history_window_hours, never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n voice_enabled, voice_model, voice_name, voice_stt_model, voice_auto_speak,\n harness_id, delegate_targets, context_tier_proportions,\n anti_hallucination_mode, anti_hallucination_model_config, require_source_links,\n created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n input.id,\n input.name,\n input.icon ?? null,\n input.identity,\n input.instructions,\n JSON.stringify(input.tools),\n input.model_config_name ?? null,\n input.is_default ? 1 : (existing?.is_default ?? 0),\n input.history_limit ?? existing?.history_limit ?? 50,\n input.history_window_hours ?? existing?.history_window_hours ?? 8,\n // never_reply is a boolean toggle — explicit `undefined` means \"keep existing\"\n // (important for PATCH-style updates that omit the field).\n input.never_reply === undefined\n ? (existing?.never_reply ?? 0)\n : (input.never_reply ? 1 : 0),\n input.adaptive_persona_enabled === undefined\n ? (existing?.adaptive_persona_enabled ?? 0)\n : (input.adaptive_persona_enabled ? 1 : 0),\n clampPercent(strength, existing?.adaptive_persona_strength ?? 50),\n clampPercent(empathy, existing?.adaptive_empathy ?? 50),\n clampPercent(expressiveness, existing?.adaptive_expressiveness ?? 50),\n clampPercent(verbosity, existing?.adaptive_verbosity ?? 50),\n mbti,\n input.voice_enabled === undefined\n ? (existing?.voice_enabled ?? 0)\n : (input.voice_enabled ? 1 : 0),\n (input.voice_model ?? existing?.voice_model ?? \"gemini-2.5-flash-preview-tts\").trim() ||\n \"gemini-2.5-flash-preview-tts\",\n (input.voice_name ?? existing?.voice_name ?? \"Kore\").trim() || \"Kore\",\n (input.voice_stt_model ?? existing?.voice_stt_model ?? \"gemini-2.5-flash\").trim() ||\n \"gemini-2.5-flash\",\n input.voice_auto_speak === undefined\n ? (existing?.voice_auto_speak ?? 1)\n : (input.voice_auto_speak ? 1 : 0),\n harnessId,\n delegateTargets,\n tierProportions,\n antiHallucMode,\n antiHallucModel,\n requireSourceLinks,\n created_at,\n t,\n );\n return getAgentConfig(input.id)!;\n}\n\nfunction clampPercent(next: number | undefined, fallback: number): number {\n const n = Number.isFinite(next) ? Number(next) : fallback;\n return Math.max(0, Math.min(100, Math.round(n)));\n}\n\nfunction toMbti(v: string | null | undefined): MbtiType | null {\n if (!v) return null;\n return (v in MBTI_PRESETS ? v : null) as MbtiType | null;\n}\n\nexport function deleteAgentConfig(id: string): boolean {\n return (\n (getDb().prepare(\"DELETE FROM agent_configs WHERE id=?\").run(id) as { changes: number }).changes > 0\n );\n}\n\nexport function generateAgentId(name: string): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 40);\n const suffix = Math.random().toString(36).slice(2, 6);\n return slug ? `${slug}-${suffix}` : `agent-${suffix}`;\n}\n\n// ── ADR-0022: per-agent message-channel display filters ─────────────────\n// Canonical channel keys mirrored in `hooks/useMessageFilters.ts`. Kept\n// in sync there by importing this constant — single source of truth.\nexport const DISPLAY_FILTER_KEYS = [\n \"scheduled_task\",\n \"watcher\",\n \"bridge\",\n \"synthetic\",\n \"tool_use\",\n \"thinking\",\n] as const;\nexport type DisplayFilterKey = (typeof DISPLAY_FILTER_KEYS)[number];\nexport type DisplayFilters = Record<DisplayFilterKey, boolean>;\n\nexport const DISPLAY_FILTER_DEFAULTS: DisplayFilters = {\n scheduled_task: true,\n watcher: true,\n bridge: true,\n synthetic: true,\n tool_use: true,\n thinking: true,\n};\n\nfunction parseDisplayFilters(raw: string | null | undefined): DisplayFilters {\n if (!raw) return { ...DISPLAY_FILTER_DEFAULTS };\n try {\n const parsed = JSON.parse(raw) as Partial<DisplayFilters>;\n // Merge over defaults so newly-added channels stay visible on old rows.\n return { ...DISPLAY_FILTER_DEFAULTS, ...parsed };\n } catch {\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n}\n\nexport function getAgentDisplayFilters(id: string): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n return parseDisplayFilters(row.display_filters);\n}\n\n/**\n * Merge a partial filter map into the agent's stored prefs. Pass `null` to\n * reset to defaults (clears the column). Safe against concurrent toggles\n * from multiple browser tabs because the merge happens server-side.\n */\nexport function updateAgentDisplayFilters(\n id: string,\n patch: Partial<DisplayFilters> | null,\n): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n if (patch === null) {\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=NULL, updated_at=? WHERE id=?\")\n .run(now(), id);\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n const current = parseDisplayFilters(row.display_filters);\n const next: DisplayFilters = { ...current };\n for (const k of DISPLAY_FILTER_KEYS) {\n if (k in patch && typeof patch[k] === \"boolean\") next[k] = patch[k] as boolean;\n }\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=?, updated_at=? WHERE id=?\")\n .run(JSON.stringify(next), now(), id);\n return next;\n}\n","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\");","// JSON.parse with a fallback value when the input is malformed (or empty).\n// Used everywhere we read responses from external APIs — they're contractually\n// JSON but a transient 502 / proxy interstitial occasionally returns HTML.\nexport function parseJsonSafe<T>(text: string, fallback: T): T;\nexport function parseJsonSafe<T>(text: string): T | undefined;\nexport function parseJsonSafe<T>(text: string, fallback?: T): T | undefined {\n try {\n return JSON.parse(text) as T;\n } catch {\n return fallback;\n }\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","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:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","// Row → JSON-response serializers shared between list (`route.ts`) and\n// item (`[id]/route.ts`) handlers. Keeping these in one place stops the\n// list and item shapes from drifting (they were copy-pasted before).\n\nimport type { AgentConfigRow } from \"@/lib/stores/agent-configs\";\nimport { getAgentTierProportions, parseDelegateTargets } from \"@/lib/stores/agent-configs\";\nimport type { BridgeRow } from \"@/lib/stores/bridges\";\nimport type { McpServerRow } from \"@/lib/stores/mcp-servers\";\nimport type { MessageRow } from \"@/lib/stores/threads\";\nimport type { MessageUsageRow } from \"@/lib/stores/message-usage\";\nimport { parseJsonSafe } from \"@/lib/utils/json\";\n\nexport function agentToResponse(a: AgentConfigRow) {\n return {\n id: a.id,\n name: a.name,\n icon: a.icon,\n identity: a.identity,\n instructions: a.instructions,\n tools: parseJsonSafe<string[]>(a.tools, []),\n model_config_name: a.model_config_name,\n is_default: !!a.is_default,\n history_limit: a.history_limit,\n history_window_hours: a.history_window_hours,\n never_reply: !!a.never_reply,\n adaptive_persona_enabled: !!a.adaptive_persona_enabled,\n adaptive_persona_strength: a.adaptive_persona_strength,\n adaptive_empathy: a.adaptive_empathy,\n adaptive_expressiveness: a.adaptive_expressiveness,\n adaptive_verbosity: a.adaptive_verbosity,\n adaptive_mbti: a.adaptive_mbti,\n voice_enabled: !!a.voice_enabled,\n voice_model: a.voice_model,\n voice_name: a.voice_name,\n voice_stt_model: a.voice_stt_model,\n voice_auto_speak: !!a.voice_auto_speak,\n harness_id: a.harness_id,\n delegate_targets: parseDelegateTargets(a.delegate_targets),\n context_tier_proportions: getAgentTierProportions(a),\n anti_hallucination_mode: (a.anti_hallucination_mode === \"off\" || a.anti_hallucination_mode === \"regex\" || a.anti_hallucination_mode === \"model\")\n ? a.anti_hallucination_mode\n : null,\n anti_hallucination_model_config: a.anti_hallucination_model_config,\n require_source_links: !!a.require_source_links,\n created_at: a.created_at,\n updated_at: a.updated_at,\n };\n}\n\nexport function bridgeToResponse(r: BridgeRow) {\n return {\n id: r.id,\n kind: r.kind,\n name: r.name,\n status: r.status,\n last_error: r.last_error,\n paired_id: r.paired_id,\n enabled: r.enabled === 1,\n created_at: r.created_at,\n updated_at: r.updated_at,\n };\n}\n\nexport function mcpServerToResponse(r: McpServerRow) {\n return {\n name: r.name,\n transport: r.transport,\n spec: parseJsonSafe<unknown>(r.spec, null),\n enabled: r.enabled === 1,\n last_error: r.last_error,\n created_at: r.created_at,\n updated_at: r.updated_at,\n };\n}\n\n/**\n * Shape a `message_usage` row into the over-the-wire `usage` object the\n * chat panel's `ContextUsageBar` consumes. Returns `null` for messages\n * that have no snapshot (user turns and legacy assistant rows recorded\n * before the per-turn snapshot landed in ADR-0041).\n */\nexport function messageUsageToResponse(u: MessageUsageRow | undefined | null) {\n if (!u) return null;\n return {\n input_tokens: u.input_tokens,\n output_tokens: u.output_tokens,\n hot_tokens: u.hot_tokens,\n warm_tokens: u.warm_tokens,\n facts_tokens: u.facts_tokens,\n overhead_tokens: u.overhead_tokens,\n hot_budget_tokens: u.hot_budget_tokens,\n warm_budget_tokens: u.warm_budget_tokens,\n facts_budget_tokens: u.facts_budget_tokens,\n context_window_tokens: u.context_window_tokens,\n };\n}\n\n/**\n * Shape one message row into its over-the-wire form, attaching its\n * per-turn `usage` snapshot when one exists. Pure data-shaping helper\n * extracted from the threads GET route so the wire contract has unit\n * coverage.\n */\nexport function messageToResponse(\n m: MessageRow,\n usageById: ReadonlyMap<string, MessageUsageRow>,\n) {\n return {\n id: m.msg_id,\n role: m.role,\n content: m.content,\n created_at: m.created_at,\n tool_events: parseToolEventsForResponse(m.tool_events),\n category: m.category ?? null,\n usage: messageUsageToResponse(usageById.get(m.msg_id)),\n metadata: parseMessageMetadataForResponse(m.metadata),\n };\n}\n\n/** Tolerant `tool_events` JSON parser shared with the route. Bad JSON\n * and non-array payloads collapse to `undefined` so the wire shape\n * always matches the typed client expectation. */\nexport function parseToolEventsForResponse(raw: string | null | undefined): unknown[] | undefined {\n if (!raw) return undefined;\n try {\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Tolerant `metadata` JSON parser. Returns `null` for missing/blank/\n * malformed/non-object payloads so the wire shape stays a plain object\n * or null — readers can rely on `metadata?.citations?...` chaining. */\nexport function parseMessageMetadataForResponse(raw: string | null | undefined): Record<string, unknown> | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n return parsed as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the bar's 100% baseline. Per-row `context_window_tokens`\n * (snapshotted at run time) wins so the bar matches the cap the agent\n * actually applied; legacy rows fall back to the model-config value;\n * unconfigured agents fall back to the default. Centralised so the\n * route and the UI share the same precedence rule.\n */\nexport function resolveContextWindowTokens(\n modelConfiguredTokens: number | null | undefined,\n defaultTokens: number,\n): number {\n if (typeof modelConfiguredTokens === \"number\" && modelConfiguredTokens > 0) {\n return modelConfiguredTokens;\n }\n return defaultTokens;\n}\n","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","deleteThread","getMessagesAfter","getMessagesPage","getThread","getMessageUsageByIds","getAgentConfig","getModelConfig","getModelParams","messageToResponse","resolveContextWindowTokens","getCheckpointer","DEFAULT_PAGE","DEFAULT_CONTEXT_WINDOW_TOKENS","GET","req","params","thread_id","thread","json","error","status","url","URL","limit","Math","max","min","Number","searchParams","get","before","undefined","after","messages","has_more","page","assistantIds","filter","m","role","map","msg_id","usageById","agentCfg","agent_id","modelCfg","model_config_name","modelParams","rawCtx","context_window_tokens","contextWindowTokens","DELETE","_req","deleted","err","msg","Error","message","String","test","console","getDb","MBTI_PRESETS","now","Date","toISOString","getAgentTierProportions","row","raw","context_tier_proportions","parsed","JSON","parse","hot","warm","facts","every","n","isFinite","listAgentConfigs","prepare","all","getDefaultAgentConfig","id","getAgentTools","cfg","tools","Array","isArray","x","length","parseDelegateTargets","ids","from","Set","upsertAgentConfig","input","t","db","existing","created_at","mbti","adaptive_mbti","toMbti","preset","strength","adaptive_persona_strength","empathy","adaptive_empathy","expressiveness","adaptive_expressiveness","verbosity","adaptive_verbosity","is_default","run","harnessId","harness_id","delegateTargets","delegate_targets","stringify","tierProportions","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","trim","requireSourceLinks","require_source_links","name","icon","identity","instructions","history_limit","history_window_hours","never_reply","adaptive_persona_enabled","clampPercent","voice_enabled","voice_model","voice_name","voice_stt_model","voice_auto_speak","next","fallback","round","v","deleteAgentConfig","changes","generateAgentId","slug","toLowerCase","replace","slice","suffix","random","toString","DISPLAY_FILTER_KEYS","DISPLAY_FILTER_DEFAULTS","scheduled_task","watcher","bridge","synthetic","tool_use","thinking","parseDisplayFilters","getAgentDisplayFilters","display_filters","updateAgentDisplayFilters","patch","current","k","parseJsonSafe","text","agentToResponse","a","updated_at","bridgeToResponse","r","kind","last_error","paired_id","enabled","mcpServerToResponse","transport","spec","messageUsageToResponse","u","input_tokens","output_tokens","hot_tokens","warm_tokens","facts_tokens","overhead_tokens","hot_budget_tokens","warm_budget_tokens","facts_budget_tokens","content","tool_events","parseToolEventsForResponse","category","usage","metadata","parseMessageMetadataForResponse","modelConfiguredTokens","defaultTokens"],"sourceRoot":"","ignoreList":[0,3,7,12,18,26,36]}
1
+ {"version":3,"file":"../app/api/v1/threads/[thread_id]/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;CAMC,GAEuD;AAO1B;AACoC;AACN;AACe;AACW;AAC1B;AAI5D,MAAMY,eAAe;AACrB,MAAMC,gCAAgC;AAE/B,eAAeC,IAAIC,GAAgB,EAAE,EAAEC,MAAM,EAAU;IAC5D,MAAM,EAAEC,SAAS,EAAE,GAAG,MAAMD;IAC5B,MAAME,SAASd,6BAASA,CAACa;IACzB,IAAI,CAACC,QAAQ,OAAOlB,mBAAYA,CAACmB,IAAI,CAAC;QAAEC,OAAO;IAAmB,GAAG;QAAEC,QAAQ;IAAI;IAEnF,MAAMC,MAAM,IAAIC,IAAIR,IAAIO,GAAG;IAC3B,MAAME,QAAQC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,GAAG,CAAC,KAAKC,OAAON,IAAIO,YAAY,CAACC,GAAG,CAAC,aAAalB;IACjF,MAAMmB,SAAST,IAAIO,YAAY,CAACC,GAAG,CAAC,aAAaE;IACjD,MAAMC,QAASX,IAAIO,YAAY,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ACA;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,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,IAAI;QACxBC,OAAOjB,uBAAuB/I,UAAUb,GAAG,CAACS,EAAEG,MAAM;QACpDkK,UAAUC,gCAAgCtK,EAAEqK,QAAQ;IACtD;AACF;AAEA;;iDAEiD,GAC1C,SAASH,2BAA2BpI,GAA8B;IACvE,IAAI,CAACA,KAAK,OAAOrC;IACjB,IAAI;QACF,MAAMuC,SAASC,KAAKC,KAAK,CAACJ;QAC1B,OAAOmB,MAAMC,OAAO,CAAClB,UAAUA,SAASvC;IAC1C,EAAE,OAAM;QACN,OAAOA;IACT;AACF;AAEA;;sEAEsE,GAC/D,SAAS6K,gCAAgCxI,GAA8B;IAC5E,IAAI,CAACA,KAAK,OAAO;IACjB,IAAI;QACF,MAAME,SAASC,KAAKC,KAAK,CAACJ;QAC1B,IAAI,CAACE,UAAU,OAAOA,WAAW,YAAYiB,MAAMC,OAAO,CAAClB,SAAS,OAAO;QAC3E,OAAOA;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;;;CAMC,GACM,SAAS7D,2BACdoM,qBAAgD,EAChDC,aAAqB;IAErB,IAAI,OAAOD,0BAA0B,YAAYA,wBAAwB,GAAG;QAC1E,OAAOA;IACT;IACA,OAAOC;AACT;;;;;;;;ACzKA;;;;;;;ACAA","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 \"next/dist/server/app-render/after-task-async-storage.external.js\"","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/route.ts","webpack://@circuitwall/jarela/?3c22","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/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/./lib/stores/agent-configs.ts","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/utils/json.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/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:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/./lib/api/serializers.ts","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","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(\"next/dist/server/app-render/after-task-async-storage.external.js\");","/**\n * @public — `GET /api/v1/threads/[thread_id]` (read messages),\n * `PATCH /api/v1/threads/[thread_id]` (rename / set agent),\n * `DELETE /api/v1/threads/[thread_id]` (drop thread)\n *\n * Thread-level CRUD. See `docs/api.md`.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport {\n deleteThread,\n getMessagesAfter,\n getMessagesPage,\n getThread,\n type MessageRow,\n} from \"@/lib/stores/threads\";\nimport { getMessageUsageByIds } from \"@/lib/stores/message-usage\";\nimport { getAgentConfig } from \"@/lib/stores/agent-configs\";\nimport { getModelConfig, getModelParams } from \"@/lib/stores/model-config\";\nimport { messageToResponse, resolveContextWindowTokens } from \"@/lib/api/serializers\";\nimport { getCheckpointer } from \"@/lib/agents/checkpointer\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst DEFAULT_PAGE = 50;\nconst DEFAULT_CONTEXT_WINDOW_TOKENS = 8_192;\n\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const thread = getThread(thread_id);\n if (!thread) return NextResponse.json({ error: \"Thread not found\" }, { status: 404 });\n\n const url = new URL(req.url);\n const limit = Math.max(1, Math.min(200, Number(url.searchParams.get(\"limit\")) || DEFAULT_PAGE));\n const before = url.searchParams.get(\"before\") ?? undefined;\n const after = url.searchParams.get(\"after\") ?? undefined;\n\n // `after` is a forward-fetch shortcut: caller (typically ChatView's\n // run-completion handler) already has the recent messages and just wants\n // the freshly-persisted ones. has_more is fixed to false because the\n // forward window is not paginated — caller already has everything older.\n let messages: MessageRow[];\n let has_more: boolean;\n if (after) {\n messages = getMessagesAfter(thread_id, after, limit);\n has_more = false;\n } else {\n const page = getMessagesPage(thread_id, limit, before);\n messages = page.messages;\n has_more = page.has_more;\n }\n\n // Attach per-assistant-turn usage so the chat UI can render a context\n // utilisation bar without an extra round-trip per message. User turns\n // and legacy assistant rows (pre-message_usage table) simply omit the\n // field.\n const assistantIds = messages.filter((m) => m.role === \"assistant\").map((m) => m.msg_id);\n const usageById = getMessageUsageByIds(assistantIds);\n\n // Resolve the agent's effective context-window size once for the whole\n // thread. The bar scales against this cap so the visual matches the\n // budget the agent applies at run time.\n const agentCfg = getAgentConfig(thread.agent_id);\n const modelCfg = agentCfg?.model_config_name ? getModelConfig(agentCfg.model_config_name) : null;\n const modelParams = modelCfg ? getModelParams(modelCfg) : null;\n const rawCtx = modelParams?.context_window_tokens;\n const contextWindowTokens = resolveContextWindowTokens(\n typeof rawCtx === \"number\" ? rawCtx : null,\n DEFAULT_CONTEXT_WINDOW_TOKENS,\n );\n\n return NextResponse.json({\n ...thread,\n context_window_tokens: contextWindowTokens,\n // No server-side filtering: clients receive every message with its\n // `category` tag and apply the chat-panel filter toolbar on the\n // render side. Keeping the raw transcript over the wire means audit\n // history is reachable from any client without round-trip params.\n messages: messages.map((m) => messageToResponse(m, usageById)),\n has_more,\n });\n}\n\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const deleted = deleteThread(thread_id);\n if (!deleted) return NextResponse.json({ error: \"Thread not found\" }, { status: 404 });\n\n // Drop the thread's LangGraph checkpoint rows too. Without this the\n // checkpoints.db file grows forever as users delete threads — the rows\n // are orphaned because the per-turn wipe in lib/agents/llm.ts only\n // runs for active threads.\n try {\n await getCheckpointer().deleteThread(thread_id);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!/no such table:\\s*checkpoints/i.test(msg)) {\n console.error(\"[threads] checkpoint cleanup failed for thread\", thread_id, err);\n }\n }\n\n return NextResponse.json({ deleted: true });\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]/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]/route\",\n pathname: \"/api/v1/threads/[thread_id]\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/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]/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]/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]/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(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","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\");","import { getDb } from \"@/lib/db\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport interface AgentConfigRow {\n id: string;\n name: string;\n icon: string | null;\n identity: string;\n instructions: string;\n tools: string; // JSON string[]\n model_config_name: string | null;\n is_default: number;\n history_limit: number; // 0 = unlimited\n history_window_hours: number; // 0 = no time bound\n never_reply: number; // 1 = run the agent but don't auto-send replies via bridges\n adaptive_persona_enabled: number; // 1 = use runtime mood/tone adaptation hints\n adaptive_persona_strength: number; // 0..100, how strongly to adapt to cues\n adaptive_empathy: number; // 0..100, baseline empathetic tone\n adaptive_expressiveness: number; // 0..100, restrained -> energetic\n adaptive_verbosity: number; // 0..100, concise -> detailed\n adaptive_mbti: string; // one of 16 MBTI types\n voice_enabled: number; // 1 = expose mic/play UI for this agent\n voice_model: string; // Gemini TTS model id\n voice_name: string; // Gemini prebuilt voice name (Kore, Puck, …)\n voice_stt_model: string; // Gemini multimodal model used for transcription\n voice_auto_speak: number; // 1 = auto-play reply when user sent voice\n display_filters: string | null; // JSON: Partial<DisplayFilters>; NULL = inherit defaults (ADR-0022)\n harness_id: string | null; // ADR-0033: per-agent harness override; NULL = inherit global default\n delegate_targets: string | null; // JSON string[] of agent ids this agent may delegate to; NULL/'[]' = none\n // ADR-0043. JSON-encoded `{ hot, warm, facts }` — any positive numbers; the\n // backend divides by sum so the UI can ship raw weights and never has to\n // reconcile to 100. NULL = inherit the model config's value.\n context_tier_proportions: string | null;\n // Per-agent override of the anti-hallucination classifier mode/model.\n // NULL on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob.\n anti_hallucination_mode: string | null; // \"off\" | \"report\" | \"enforce\"\n anti_hallucination_model_config: string | null; // saved model config name\n // When 1, the system prompt is augmented with a citation-link directive\n // and the assistant turn is post-checked by `anti_hallucination_model_config`\n // for {source link present, source previously visited in this thread}.\n // Independent of `anti_hallucination_mode` — stall detection and citation\n // enforcement can be on/off in any combination.\n require_source_links: number;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentTierProportions {\n hot: number;\n warm: number;\n facts: number;\n}\n\n/**\n * Parse the JSON-encoded per-agent override of context tier proportions.\n * Returns `null` for NULL, blank, malformed JSON, or any payload that\n * doesn't have three finite non-negative numeric fields. Callers fall\n * back to the model config's value (or built-in defaults) on null.\n */\nexport function getAgentTierProportions(row: AgentConfigRow): AgentTierProportions | null {\n const raw = row.context_tier_proportions;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<AgentTierProportions>;\n const hot = Number(parsed.hot);\n const warm = Number(parsed.warm);\n const facts = Number(parsed.facts);\n if (![hot, warm, facts].every((n) => Number.isFinite(n) && n >= 0)) return null;\n if (hot + warm + facts <= 0) return null;\n return { hot, warm, facts };\n } catch {\n return null;\n }\n}\n\nexport function listAgentConfigs(): AgentConfigRow[] {\n return getDb()\n .prepare(\"SELECT * FROM agent_configs ORDER BY is_default DESC, created_at ASC\")\n .all() as unknown as AgentConfigRow[];\n}\n\nexport function getDefaultAgentConfig(): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE is_default=1 LIMIT 1\")\n .get() as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport function getAgentConfig(id: string): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE id=?\")\n .get(id) as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport interface UpsertAgentInput {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n model_config_name?: string | null;\n is_default?: boolean;\n history_limit?: number;\n history_window_hours?: number;\n never_reply?: boolean;\n adaptive_persona_enabled?: boolean;\n adaptive_persona_strength?: number;\n adaptive_empathy?: number;\n adaptive_expressiveness?: number;\n adaptive_verbosity?: number;\n adaptive_mbti?: MbtiType;\n voice_enabled?: boolean;\n voice_model?: string;\n voice_name?: string;\n voice_stt_model?: string;\n voice_auto_speak?: boolean;\n harness_id?: string | null;\n delegate_targets?: string[];\n // ADR-0043. Pass `null` to clear the override and inherit from the model.\n // Pass `undefined` to keep whatever's already on the row (PATCH semantics).\n context_tier_proportions?: AgentTierProportions | null;\n // Per-agent anti-hallucination classifier override. `null` = clear the\n // override (inherit env). `undefined` = keep existing.\n anti_hallucination_mode?: \"off\" | \"regex\" | \"model\" | null;\n anti_hallucination_model_config?: string | null;\n // Citation enforcement (independent of stall detector). `undefined` = keep\n // existing. `false` = disable.\n require_source_links?: boolean;\n}\n\n/**\n * Parse the JSON-encoded delegate whitelist into a deduped string[]. Returns\n * an empty array for NULL, blank, or malformed JSON (delegation is opt-in).\n */\n/**\n * Parse the agent's tool allowlist (`tools` column, stored as a JSON string).\n * Returns an empty array on NULL/blank/malformed JSON — same defensive shape\n * as parseDelegateTargets. Callers that previously did `JSON.parse(cfg.tools)`\n * inline should switch to this getter so the serialization contract stays\n * owned by this store.\n */\nexport function getAgentTools(cfg: Pick<AgentConfigRow, \"tools\"> | null | undefined): string[] {\n if (!cfg?.tools) return [];\n try {\n const parsed = JSON.parse(cfg.tools);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n } catch {\n return [];\n }\n}\n\nexport function parseDelegateTargets(raw: string | null | undefined): string[] {\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n const ids = parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n return Array.from(new Set(ids));\n } catch {\n return [];\n }\n}\n\nexport function upsertAgentConfig(input: UpsertAgentInput): AgentConfigRow {\n const t = now();\n const db = getDb();\n const existing = getAgentConfig(input.id);\n const created_at = existing?.created_at ?? t;\n const mbti = input.adaptive_mbti ?? toMbti(existing?.adaptive_mbti) ?? \"INTJ\";\n const preset = MBTI_PRESETS[mbti];\n const strength = input.adaptive_persona_strength ?? preset.strength;\n const empathy = input.adaptive_empathy ?? preset.empathy;\n const expressiveness = input.adaptive_expressiveness ?? preset.expressiveness;\n const verbosity = input.adaptive_verbosity ?? preset.verbosity;\n if (input.is_default) db.prepare(\"UPDATE agent_configs SET is_default=0\").run();\n // harness_id: explicit `undefined` means \"keep existing\"; explicit `null`\n // means \"use the global default\". Empty string is normalised to null too,\n // matching how the AgentEditor sends \"\" for the inherit option.\n const harnessId =\n input.harness_id === undefined\n ? (existing?.harness_id ?? null)\n : (input.harness_id && input.harness_id.length > 0 ? input.harness_id : null);\n // delegate_targets: undefined = keep existing; explicit empty array clears.\n const delegateTargets = input.delegate_targets === undefined\n ? (existing?.delegate_targets ?? null)\n : JSON.stringify(Array.from(new Set(input.delegate_targets.filter((id) => id && id !== input.id))));\n // context_tier_proportions: undefined = keep existing; null = clear and\n // inherit from the model; object = serialise as JSON. Negative values are\n // clamped to 0 so the upsert can't poison the column with bad data.\n const tierProportions =\n input.context_tier_proportions === undefined\n ? (existing?.context_tier_proportions ?? null)\n : input.context_tier_proportions === null\n ? null\n : JSON.stringify({\n hot: Math.max(0, Number(input.context_tier_proportions.hot) || 0),\n warm: Math.max(0, Number(input.context_tier_proportions.warm) || 0),\n facts: Math.max(0, Number(input.context_tier_proportions.facts) || 0),\n });\n // Anti-hallucination override: `undefined` keeps existing; `null` clears\n // the override (inherits env). Empty-string model is normalised to null\n // so the editor can ship \"\" for the inherit option.\n const antiHallucMode =\n input.anti_hallucination_mode === undefined\n ? (existing?.anti_hallucination_mode ?? null)\n : input.anti_hallucination_mode === null\n ? null\n : (input.anti_hallucination_mode === \"off\" || input.anti_hallucination_mode === \"regex\" || input.anti_hallucination_mode === \"model\")\n ? input.anti_hallucination_mode\n : null;\n const antiHallucModel =\n input.anti_hallucination_model_config === undefined\n ? (existing?.anti_hallucination_model_config ?? null)\n : input.anti_hallucination_model_config && input.anti_hallucination_model_config.trim().length > 0\n ? input.anti_hallucination_model_config.trim()\n : null;\n const requireSourceLinks =\n input.require_source_links === undefined\n ? (existing?.require_source_links ?? 0)\n : (input.require_source_links ? 1 : 0);\n db.prepare(\n `INSERT OR REPLACE INTO agent_configs\n (id, name, icon, identity, instructions, tools, model_config_name, is_default,\n history_limit, history_window_hours, never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n voice_enabled, voice_model, voice_name, voice_stt_model, voice_auto_speak,\n harness_id, delegate_targets, context_tier_proportions,\n anti_hallucination_mode, anti_hallucination_model_config, require_source_links,\n created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n input.id,\n input.name,\n input.icon ?? null,\n input.identity,\n input.instructions,\n JSON.stringify(input.tools),\n input.model_config_name ?? null,\n input.is_default ? 1 : (existing?.is_default ?? 0),\n input.history_limit ?? existing?.history_limit ?? 50,\n input.history_window_hours ?? existing?.history_window_hours ?? 8,\n // never_reply is a boolean toggle — explicit `undefined` means \"keep existing\"\n // (important for PATCH-style updates that omit the field).\n input.never_reply === undefined\n ? (existing?.never_reply ?? 0)\n : (input.never_reply ? 1 : 0),\n input.adaptive_persona_enabled === undefined\n ? (existing?.adaptive_persona_enabled ?? 0)\n : (input.adaptive_persona_enabled ? 1 : 0),\n clampPercent(strength, existing?.adaptive_persona_strength ?? 50),\n clampPercent(empathy, existing?.adaptive_empathy ?? 50),\n clampPercent(expressiveness, existing?.adaptive_expressiveness ?? 50),\n clampPercent(verbosity, existing?.adaptive_verbosity ?? 50),\n mbti,\n input.voice_enabled === undefined\n ? (existing?.voice_enabled ?? 0)\n : (input.voice_enabled ? 1 : 0),\n (input.voice_model ?? existing?.voice_model ?? \"gemini-2.5-flash-preview-tts\").trim() ||\n \"gemini-2.5-flash-preview-tts\",\n (input.voice_name ?? existing?.voice_name ?? \"Kore\").trim() || \"Kore\",\n (input.voice_stt_model ?? existing?.voice_stt_model ?? \"gemini-2.5-flash\").trim() ||\n \"gemini-2.5-flash\",\n input.voice_auto_speak === undefined\n ? (existing?.voice_auto_speak ?? 1)\n : (input.voice_auto_speak ? 1 : 0),\n harnessId,\n delegateTargets,\n tierProportions,\n antiHallucMode,\n antiHallucModel,\n requireSourceLinks,\n created_at,\n t,\n );\n return getAgentConfig(input.id)!;\n}\n\nfunction clampPercent(next: number | undefined, fallback: number): number {\n const n = Number.isFinite(next) ? Number(next) : fallback;\n return Math.max(0, Math.min(100, Math.round(n)));\n}\n\nfunction toMbti(v: string | null | undefined): MbtiType | null {\n if (!v) return null;\n return (v in MBTI_PRESETS ? v : null) as MbtiType | null;\n}\n\nexport function deleteAgentConfig(id: string): boolean {\n return (\n (getDb().prepare(\"DELETE FROM agent_configs WHERE id=?\").run(id) as { changes: number }).changes > 0\n );\n}\n\nexport function generateAgentId(name: string): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 40);\n const suffix = Math.random().toString(36).slice(2, 6);\n return slug ? `${slug}-${suffix}` : `agent-${suffix}`;\n}\n\n// ── ADR-0022: per-agent message-channel display filters ─────────────────\n// Canonical channel keys mirrored in `hooks/useMessageFilters.ts`. Kept\n// in sync there by importing this constant — single source of truth.\nexport const DISPLAY_FILTER_KEYS = [\n \"scheduled_task\",\n \"watcher\",\n \"bridge\",\n \"synthetic\",\n \"tool_use\",\n \"thinking\",\n] as const;\nexport type DisplayFilterKey = (typeof DISPLAY_FILTER_KEYS)[number];\nexport type DisplayFilters = Record<DisplayFilterKey, boolean>;\n\nexport const DISPLAY_FILTER_DEFAULTS: DisplayFilters = {\n scheduled_task: true,\n watcher: true,\n bridge: true,\n synthetic: true,\n tool_use: true,\n thinking: true,\n};\n\nfunction parseDisplayFilters(raw: string | null | undefined): DisplayFilters {\n if (!raw) return { ...DISPLAY_FILTER_DEFAULTS };\n try {\n const parsed = JSON.parse(raw) as Partial<DisplayFilters>;\n // Merge over defaults so newly-added channels stay visible on old rows.\n return { ...DISPLAY_FILTER_DEFAULTS, ...parsed };\n } catch {\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n}\n\nexport function getAgentDisplayFilters(id: string): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n return parseDisplayFilters(row.display_filters);\n}\n\n/**\n * Merge a partial filter map into the agent's stored prefs. Pass `null` to\n * reset to defaults (clears the column). Safe against concurrent toggles\n * from multiple browser tabs because the merge happens server-side.\n */\nexport function updateAgentDisplayFilters(\n id: string,\n patch: Partial<DisplayFilters> | null,\n): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n if (patch === null) {\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=NULL, updated_at=? WHERE id=?\")\n .run(now(), id);\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n const current = parseDisplayFilters(row.display_filters);\n const next: DisplayFilters = { ...current };\n for (const k of DISPLAY_FILTER_KEYS) {\n if (k in patch && typeof patch[k] === \"boolean\") next[k] = patch[k] as boolean;\n }\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=?, updated_at=? WHERE id=?\")\n .run(JSON.stringify(next), now(), id);\n return next;\n}\n","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\");","// JSON.parse with a fallback value when the input is malformed (or empty).\n// Used everywhere we read responses from external APIs — they're contractually\n// JSON but a transient 502 / proxy interstitial occasionally returns HTML.\nexport function parseJsonSafe<T>(text: string, fallback: T): T;\nexport function parseJsonSafe<T>(text: string): T | undefined;\nexport function parseJsonSafe<T>(text: string, fallback?: T): T | undefined {\n try {\n return JSON.parse(text) as T;\n } catch {\n return fallback;\n }\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","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:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","// Row → JSON-response serializers shared between list (`route.ts`) and\n// item (`[id]/route.ts`) handlers. Keeping these in one place stops the\n// list and item shapes from drifting (they were copy-pasted before).\n\nimport type { AgentConfigRow } from \"@/lib/stores/agent-configs\";\nimport { getAgentTierProportions, parseDelegateTargets } from \"@/lib/stores/agent-configs\";\nimport type { BridgeRow } from \"@/lib/stores/bridges\";\nimport type { McpServerRow } from \"@/lib/stores/mcp-servers\";\nimport type { MessageRow } from \"@/lib/stores/threads\";\nimport type { MessageUsageRow } from \"@/lib/stores/message-usage\";\nimport { parseJsonSafe } from \"@/lib/utils/json\";\n\nexport function agentToResponse(a: AgentConfigRow) {\n return {\n id: a.id,\n name: a.name,\n icon: a.icon,\n identity: a.identity,\n instructions: a.instructions,\n tools: parseJsonSafe<string[]>(a.tools, []),\n model_config_name: a.model_config_name,\n is_default: !!a.is_default,\n history_limit: a.history_limit,\n history_window_hours: a.history_window_hours,\n never_reply: !!a.never_reply,\n adaptive_persona_enabled: !!a.adaptive_persona_enabled,\n adaptive_persona_strength: a.adaptive_persona_strength,\n adaptive_empathy: a.adaptive_empathy,\n adaptive_expressiveness: a.adaptive_expressiveness,\n adaptive_verbosity: a.adaptive_verbosity,\n adaptive_mbti: a.adaptive_mbti,\n voice_enabled: !!a.voice_enabled,\n voice_model: a.voice_model,\n voice_name: a.voice_name,\n voice_stt_model: a.voice_stt_model,\n voice_auto_speak: !!a.voice_auto_speak,\n harness_id: a.harness_id,\n delegate_targets: parseDelegateTargets(a.delegate_targets),\n context_tier_proportions: getAgentTierProportions(a),\n anti_hallucination_mode: (a.anti_hallucination_mode === \"off\" || a.anti_hallucination_mode === \"regex\" || a.anti_hallucination_mode === \"model\")\n ? a.anti_hallucination_mode\n : null,\n anti_hallucination_model_config: a.anti_hallucination_model_config,\n require_source_links: !!a.require_source_links,\n created_at: a.created_at,\n updated_at: a.updated_at,\n };\n}\n\nexport function bridgeToResponse(r: BridgeRow) {\n return {\n id: r.id,\n kind: r.kind,\n name: r.name,\n status: r.status,\n last_error: r.last_error,\n paired_id: r.paired_id,\n enabled: r.enabled === 1,\n created_at: r.created_at,\n updated_at: r.updated_at,\n };\n}\n\nexport function mcpServerToResponse(r: McpServerRow) {\n return {\n name: r.name,\n transport: r.transport,\n spec: parseJsonSafe<unknown>(r.spec, null),\n enabled: r.enabled === 1,\n last_error: r.last_error,\n created_at: r.created_at,\n updated_at: r.updated_at,\n };\n}\n\n/**\n * Shape a `message_usage` row into the over-the-wire `usage` object the\n * chat panel's `ContextUsageBar` consumes. Returns `null` for messages\n * that have no snapshot (user turns and legacy assistant rows recorded\n * before the per-turn snapshot landed in ADR-0041).\n *\n * Anthropic prompt-cache tokens (PR #181 + the cache-fidelity follow-up)\n * are surfaced as additive fields so future UI work can render a\n * \"served from cache\" badge without another wire change. Both are\n * `null` for rows that predate cache plumbing or for providers that\n * don't expose a cache breakdown.\n */\nexport function messageUsageToResponse(u: MessageUsageRow | undefined | null) {\n if (!u) return null;\n return {\n input_tokens: u.input_tokens,\n output_tokens: u.output_tokens,\n hot_tokens: u.hot_tokens,\n warm_tokens: u.warm_tokens,\n facts_tokens: u.facts_tokens,\n overhead_tokens: u.overhead_tokens,\n hot_budget_tokens: u.hot_budget_tokens,\n warm_budget_tokens: u.warm_budget_tokens,\n facts_budget_tokens: u.facts_budget_tokens,\n context_window_tokens: u.context_window_tokens,\n cache_creation_input_tokens: u.cache_creation_input_tokens,\n cache_read_input_tokens: u.cache_read_input_tokens,\n };\n}\n\n/**\n * Shape one message row into its over-the-wire form, attaching its\n * per-turn `usage` snapshot when one exists. Pure data-shaping helper\n * extracted from the threads GET route so the wire contract has unit\n * coverage.\n */\nexport function messageToResponse(\n m: MessageRow,\n usageById: ReadonlyMap<string, MessageUsageRow>,\n) {\n return {\n id: m.msg_id,\n role: m.role,\n content: m.content,\n created_at: m.created_at,\n tool_events: parseToolEventsForResponse(m.tool_events),\n category: m.category ?? null,\n usage: messageUsageToResponse(usageById.get(m.msg_id)),\n metadata: parseMessageMetadataForResponse(m.metadata),\n };\n}\n\n/** Tolerant `tool_events` JSON parser shared with the route. Bad JSON\n * and non-array payloads collapse to `undefined` so the wire shape\n * always matches the typed client expectation. */\nexport function parseToolEventsForResponse(raw: string | null | undefined): unknown[] | undefined {\n if (!raw) return undefined;\n try {\n const parsed = JSON.parse(raw);\n return Array.isArray(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Tolerant `metadata` JSON parser. Returns `null` for missing/blank/\n * malformed/non-object payloads so the wire shape stays a plain object\n * or null — readers can rely on `metadata?.citations?...` chaining. */\nexport function parseMessageMetadataForResponse(raw: string | null | undefined): Record<string, unknown> | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n return parsed as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the bar's 100% baseline. Per-row `context_window_tokens`\n * (snapshotted at run time) wins so the bar matches the cap the agent\n * actually applied; legacy rows fall back to the model-config value;\n * unconfigured agents fall back to the default. Centralised so the\n * route and the UI share the same precedence rule.\n */\nexport function resolveContextWindowTokens(\n modelConfiguredTokens: number | null | undefined,\n defaultTokens: number,\n): number {\n if (typeof modelConfiguredTokens === \"number\" && modelConfiguredTokens > 0) {\n return modelConfiguredTokens;\n }\n return defaultTokens;\n}\n","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","deleteThread","getMessagesAfter","getMessagesPage","getThread","getMessageUsageByIds","getAgentConfig","getModelConfig","getModelParams","messageToResponse","resolveContextWindowTokens","getCheckpointer","DEFAULT_PAGE","DEFAULT_CONTEXT_WINDOW_TOKENS","GET","req","params","thread_id","thread","json","error","status","url","URL","limit","Math","max","min","Number","searchParams","get","before","undefined","after","messages","has_more","page","assistantIds","filter","m","role","map","msg_id","usageById","agentCfg","agent_id","modelCfg","model_config_name","modelParams","rawCtx","context_window_tokens","contextWindowTokens","DELETE","_req","deleted","err","msg","Error","message","String","test","console","getDb","MBTI_PRESETS","now","Date","toISOString","getAgentTierProportions","row","raw","context_tier_proportions","parsed","JSON","parse","hot","warm","facts","every","n","isFinite","listAgentConfigs","prepare","all","getDefaultAgentConfig","id","getAgentTools","cfg","tools","Array","isArray","x","length","parseDelegateTargets","ids","from","Set","upsertAgentConfig","input","t","db","existing","created_at","mbti","adaptive_mbti","toMbti","preset","strength","adaptive_persona_strength","empathy","adaptive_empathy","expressiveness","adaptive_expressiveness","verbosity","adaptive_verbosity","is_default","run","harnessId","harness_id","delegateTargets","delegate_targets","stringify","tierProportions","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","trim","requireSourceLinks","require_source_links","name","icon","identity","instructions","history_limit","history_window_hours","never_reply","adaptive_persona_enabled","clampPercent","voice_enabled","voice_model","voice_name","voice_stt_model","voice_auto_speak","next","fallback","round","v","deleteAgentConfig","changes","generateAgentId","slug","toLowerCase","replace","slice","suffix","random","toString","DISPLAY_FILTER_KEYS","DISPLAY_FILTER_DEFAULTS","scheduled_task","watcher","bridge","synthetic","tool_use","thinking","parseDisplayFilters","getAgentDisplayFilters","display_filters","updateAgentDisplayFilters","patch","current","k","parseJsonSafe","text","agentToResponse","a","updated_at","bridgeToResponse","r","kind","last_error","paired_id","enabled","mcpServerToResponse","transport","spec","messageUsageToResponse","u","input_tokens","output_tokens","hot_tokens","warm_tokens","facts_tokens","overhead_tokens","hot_budget_tokens","warm_budget_tokens","facts_budget_tokens","cache_creation_input_tokens","cache_read_input_tokens","content","tool_events","parseToolEventsForResponse","category","usage","metadata","parseMessageMetadataForResponse","modelConfiguredTokens","defaultTokens"],"sourceRoot":"","ignoreList":[0,3,7,12,18,26,36]}
@@ -515,7 +515,14 @@ var bus = __webpack_require__(76445);
515
515
  // EXTERNAL MODULE: ./lib/api/sse.ts
516
516
  var sse = __webpack_require__(53854);
517
517
  ;// ./app/api/v1/threads/[thread_id]/run/route.ts
518
-
518
+ /**
519
+ * @public — `POST /api/v1/threads/[thread_id]/run` (submit run),
520
+ * `GET /api/v1/threads/[thread_id]/run` (subscribe via SSE)
521
+ *
522
+ * Agent execution endpoint. Submit a run, then stream tokens, tool
523
+ * calls, and final state. The split-and-subscribe shape lets reconnects
524
+ * pick up an in-flight stream. See `docs/api.md`.
525
+ */
519
526
 
520
527
 
521
528