@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/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAwD;AACS;AACL;AAC2B;AAEhF,SAASO,IAAIC,GAAgB;IAClC,MAAM,EAAEC,YAAY,EAAE,GAAGD,IAAIE,OAAO;IACpC,MAAMC,QAAQC,OAAOH,aAAaI,GAAG,CAAC,YAAY;IAClD,MAAMC,SAASF,OAAOH,aAAaI,GAAG,CAAC,aAAa;IACpD,OAAOb,mBAAYA,CAACe,IAAI,CAACb,+BAAWA,CAACS,OAAOG;AAC9C;AAEO,eAAeE,KAAKR,GAAgB;IACzC,MAAM,EAAES,QAAQ,EAAEC,KAAK,EAAE,GAAG,MAAMV,IAAIO,IAAI;IAC1C,IAAI,CAACE,UAAU,OAAOb,mCAAaA,CAAC;IACpC,IAAI,CAACD,wCAAcA,CAACc,WAAW,OAAOZ,sCAAgBA,CAAC,CAAC,OAAO,EAAEY,SAAS,WAAW,CAAC;IACtF,MAAME,SAASlB,gCAAYA,CAACgB,UAAUC;IACtC,OAAOZ,qCAAeA,CAACa;AACzB;;;AClB+F;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACsB;AACxF;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,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AoD;AAC7C,SAAS2C,qBACd3C,SAAiB,EACjB4C,OAAe,EACfC,MAAqB;IAErBpK,wDAAKA,GACFiB,OAAO,CACN,0GAEDmC,GAAG,CAAC+G,SAASC,QAAQlK,OAAOqH;AACjC;;;;;;;;ACrOA;;;;;;;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/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/./app/api/v1/threads/route.ts","webpack://@circuitwall/jarela/?0774","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/api/responses.ts","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/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/stores/threads.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\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","import { NextRequest, NextResponse } from \"next/server\";\nimport { createThread, listThreads } from \"@/lib/stores/threads\";\nimport { getAgentConfig } from \"@/lib/stores/agent-configs\";\nimport { errorResponse, notFoundResponse, createdResponse } from \"@/lib/api/responses\";\n\nexport function GET(req: NextRequest) {\n const { searchParams } = req.nextUrl;\n const limit = Number(searchParams.get(\"limit\") ?? 50);\n const offset = Number(searchParams.get(\"offset\") ?? 0);\n return NextResponse.json(listThreads(limit, offset));\n}\n\nexport async function POST(req: NextRequest) {\n const { agent_id, title } = await req.json() as { agent_id: string; title?: string };\n if (!agent_id) return errorResponse(\"agent_id required\");\n if (!getAgentConfig(agent_id)) return notFoundResponse(`Agent \"${agent_id}\" not found`);\n const thread = createThread(agent_id, title);\n return createdResponse(thread);\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/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/route\",\n pathname: \"/api/v1/threads\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/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/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/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/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(\"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\");","// Shared HTTP response builders for app/api/v1/** route handlers.\n//\n// Goal: every error/success payload across the v1 surface has the same\n// shape. Before this lived inline, response bodies drifted —\n// `{error: \"x\"}` vs `{message: \"x\"}`, 400 vs 422 for the same condition,\n// some routes returned Zod's raw issue array, others stringified it.\n\nimport { NextResponse } from \"next/server\";\nimport type { z } from \"zod\";\nimport type { NextRequest } from \"next/server\";\n\nexport function errorResponse(message: string, status: number = 400): NextResponse {\n return NextResponse.json({ error: message }, { status });\n}\n\nexport function notFoundResponse(message: string = \"Not found\"): NextResponse {\n return errorResponse(message, 404);\n}\n\nexport function createdResponse<T>(data: T): NextResponse {\n return NextResponse.json(data, { status: 201 });\n}\n\n// Wrap a 200 JSON response with a private Cache-Control header. Use on safe\n// GET endpoints that serve user-scoped data the client refetches often (panel\n// mounts, navigation back/forward) but mutates rarely. The TTL is short\n// enough that explicit mutations — which patch the client-side ApiClient\n// cache in place — stay observably consistent without an extra roundtrip.\nexport function cachedJson<T>(data: T, maxAgeSeconds: number): NextResponse {\n return NextResponse.json(data, {\n headers: {\n \"Cache-Control\": `private, max-age=${maxAgeSeconds}`,\n },\n });\n}\n\n// Validate a JSON request body against a zod schema.\n// Returns either the parsed data or a 400 NextResponse explaining the issue.\n// Caller pattern:\n// const parsed = await validateBody(req, Schema);\n// if (parsed instanceof NextResponse) return parsed;\n// // use parsed.field\nexport async function validateBody<S extends z.ZodTypeAny>(\n req: NextRequest,\n schema: S,\n): Promise<z.infer<S> | NextResponse> {\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return errorResponse(\"Request body must be valid JSON\", 400);\n }\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n return errorResponse(parsed.error.issues[0]?.message ?? \"invalid body\", 400);\n }\n return parsed.data;\n}\n","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\");","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\");","import { randomUUID } from \"node:crypto\";\nimport { getDb } from \"@/lib/db\";\nimport { embedOne } from \"@/lib/embeddings\";\n\nconst now = () => new Date().toISOString();\n\n// Explicit column list for message reads — omits `embedding` (~20KB of\n// JSON-encoded float[] per row) which only the embeddings module reads.\n// Avoids dragging it through the chat-history result set on every call.\nconst MSG_COLS_SQL = \"SELECT msg_id, thread_id, role, content, created_at, tool_events, category, metadata FROM messages\";\n\nexport interface ThreadRow {\n thread_id: string; agent_id: string; title: string | null;\n created_at: string; updated_at: string; message_count: number;\n // ADR-0042 — explicit context pin + cached warm summary. NULL on threads\n // that haven't had the boundary moved away from the agent default. The\n // summary is fresh only when warm_summary_before === hot_since.\n hot_since?: string | null;\n warm_summary?: string | null;\n warm_summary_before?: string | null;\n warm_summary_computed_at?: string | null;\n}\nexport interface MessageRow {\n msg_id: string; thread_id: string; role: string; content: string; created_at: string;\n // JSON-encoded array of PersistedToolEvent. null when no tool work happened\n // on this turn or for user messages. Read back by the chat UI so historical\n // bubbles show the same expandable CALL/RESULT entries as live streaming.\n tool_events?: string | null;\n // Non-null tags classify the message into a filterable group in the chat\n // panel (e.g. 'scheduled_task', 'bridge', 'synthetic'). NULL = ordinary\n // user/assistant chat content.\n category?: string | null;\n // JSON-encoded auxiliary per-message data. NULL on legacy rows. Currently\n // carries the citation-checker verdict when `require_source_links` is on.\n metadata?: string | null;\n}\n\nexport interface PersistedToolEvent {\n id: string;\n phase: \"call\" | \"result\";\n name: string;\n payload: unknown;\n}\n\nexport function listThreads(limit = 50, offset = 0): ThreadRow[] {\n return getDb()\n .prepare(\"SELECT * FROM threads ORDER BY updated_at DESC LIMIT ? OFFSET ?\")\n .all(limit, offset) as unknown as ThreadRow[];\n}\n\nexport function listThreadsByAgent(agent_id: string, limit = 50): ThreadRow[] {\n return getDb()\n .prepare(\"SELECT * FROM threads WHERE agent_id=? ORDER BY updated_at DESC LIMIT ?\")\n .all(agent_id, limit) as unknown as ThreadRow[];\n}\n\nexport function getThread(thread_id: string): ThreadRow | null {\n return (getDb().prepare(\"SELECT * FROM threads WHERE thread_id=?\").get(thread_id) as unknown as ThreadRow) ?? null;\n}\n\nexport function createThread(agent_id: string, title?: string): ThreadRow {\n const t = now();\n const thread_id = randomUUID();\n getDb()\n .prepare(\"INSERT INTO threads (thread_id,agent_id,title,created_at,updated_at,message_count) VALUES (?,?,?,?,?,0)\")\n .run(thread_id, agent_id, title ?? null, t, t);\n return { thread_id, agent_id, title: title ?? null, created_at: t, updated_at: t, message_count: 0 };\n}\n\nexport function deleteThread(thread_id: string): boolean {\n const db = getDb();\n db.prepare(\"DELETE FROM messages WHERE thread_id=?\").run(thread_id);\n const r = db.prepare(\"DELETE FROM threads WHERE thread_id=?\").run(thread_id);\n return r.changes > 0;\n}\n\nexport function getMessages(thread_id: string): MessageRow[] {\n return getDb()\n .prepare(MSG_COLS_SQL + \" WHERE thread_id=? ORDER BY created_at ASC\")\n .all(thread_id) as unknown as MessageRow[];\n}\n\n// Pull the latest N messages within a time window. Used to build the LLM\n// context — keeps prompt size bounded as threads grow indefinitely.\n// limit: 0 or negative = unlimited\n// sinceISO: undefined = no time bound\n// Returns chronological order (oldest first) so it can be appended to the prompt directly.\nexport function getRecentMessagesWindow(\n thread_id: string,\n limit: number,\n sinceISO?: string,\n): MessageRow[] {\n const db = getDb();\n const params: (string | number)[] = [thread_id];\n let sql = MSG_COLS_SQL + \" WHERE thread_id=?\";\n if (sinceISO) {\n sql += \" AND created_at >= ?\";\n params.push(sinceISO);\n }\n sql += \" ORDER BY created_at DESC\";\n if (limit > 0) {\n sql += \" LIMIT ?\";\n params.push(limit);\n }\n const rows = db.prepare(sql).all(...params) as unknown as MessageRow[];\n return rows.reverse();\n}\n\n// Forward-fetch — return messages strictly newer than `afterISO`, oldest\n// first, capped at `limit`. Used by the chat view to pull only the\n// freshly-persisted user+assistant pair after a run completes, instead of\n// re-fetching the whole most-recent page.\nexport function getMessagesAfter(\n thread_id: string,\n afterISO: string,\n limit = 50,\n): MessageRow[] {\n return getDb()\n .prepare(\n MSG_COLS_SQL +\n \" WHERE thread_id=? AND created_at > ? ORDER BY created_at ASC LIMIT ?\",\n )\n .all(thread_id, afterISO, limit) as unknown as MessageRow[];\n}\n\n// Pagination for the chat UI. Returns the latest N messages strictly older\n// than `beforeISO` (cursor). Caller passes the oldest already-loaded message's\n// created_at as the cursor; first page omits beforeISO.\nexport function getMessagesPage(\n thread_id: string,\n limit: number,\n beforeISO?: string,\n): { messages: MessageRow[]; has_more: boolean } {\n const db = getDb();\n const params: (string | number)[] = [thread_id];\n let sql = MSG_COLS_SQL + \" WHERE thread_id=?\";\n if (beforeISO) {\n sql += \" AND created_at < ?\";\n params.push(beforeISO);\n }\n sql += \" ORDER BY created_at DESC LIMIT ?\";\n params.push(limit + 1); // fetch one extra to detect if there's more\n const rows = db.prepare(sql).all(...params) as unknown as MessageRow[];\n const has_more = rows.length > limit;\n return { messages: rows.slice(0, limit).reverse(), has_more };\n}\n\nexport function addMessage(\n thread_id: string,\n role: \"user\" | \"assistant\",\n content: string,\n toolEvents?: PersistedToolEvent[] | null,\n category: string | null = null,\n metadata?: Record<string, unknown> | null,\n): MessageRow {\n const msg_id = randomUUID();\n const t = now();\n const db = getDb();\n const toolEventsJson = toolEvents && toolEvents.length > 0 ? JSON.stringify(toolEvents) : null;\n const metadataJson = metadata && Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : null;\n db.prepare(\"INSERT INTO messages (msg_id,thread_id,role,content,created_at,tool_events,category,metadata) VALUES (?,?,?,?,?,?,?,?)\")\n .run(msg_id, thread_id, role, content, t, toolEventsJson, category, metadataJson);\n db.prepare(\"UPDATE threads SET message_count=message_count+1 WHERE thread_id=?\").run(thread_id);\n // Best-effort: embed the message so semantic recall can pull it back later.\n // Skip empty / very short content (greetings have no useful signal).\n if (content.trim().length >= 12) {\n embedOne(content).then((vec) => {\n if (vec) {\n getDb().prepare(\"UPDATE messages SET embedding=? WHERE msg_id=?\").run(JSON.stringify(vec), msg_id);\n }\n }).catch(() => { /* logged in embeddings module */ });\n }\n return { msg_id, thread_id, role, content, created_at: t, tool_events: toolEventsJson, category, metadata: metadataJson };\n}\n\n// Replace a single message's metadata blob. Used by the citation checker\n// to write its verdict back after the assistant turn has already been\n// persisted (the checker runs async post-insert so the chat UI sees the\n// content immediately and picks up the metadata on the next refresh).\nexport function setMessageMetadata(msg_id: string, metadata: Record<string, unknown> | null): void {\n const json = metadata && Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : null;\n getDb().prepare(\"UPDATE messages SET metadata=? WHERE msg_id=?\").run(json, msg_id);\n}\n\nexport function getOrCreateAgentThread(agentId: string): ThreadRow {\n const existing = getDb()\n .prepare(\"SELECT * FROM threads WHERE agent_id=? LIMIT 1\")\n .get(agentId) as ThreadRow | undefined;\n if (existing) return existing;\n return createThread(agentId);\n}\n\nexport function clearThreadMessages(threadId: string): void {\n const db = getDb();\n db.prepare(\"DELETE FROM messages WHERE thread_id=?\").run(threadId);\n db.prepare(\"UPDATE threads SET message_count=0, updated_at=? WHERE thread_id=?\")\n .run(new Date().toISOString(), threadId);\n}\n\nexport function touchThread(thread_id: string, firstMsg?: string): void {\n const t = now();\n getDb()\n .prepare(\"UPDATE threads SET updated_at=?, title=COALESCE(title,?) WHERE thread_id=?\")\n .run(t, firstMsg ? firstMsg.slice(0, 80) : null, thread_id);\n}\n\n// ADR-0042. Move the user's explicit boundary between hot and warm context.\n// Pass `null` to clear the pin and let the agent's default window apply\n// again. Persisting the pin here keeps it stable across reloads and devices.\nexport function setThreadContextPin(thread_id: string, hot_since: string | null): void {\n getDb()\n .prepare(\"UPDATE threads SET hot_since=? WHERE thread_id=?\")\n .run(hot_since, thread_id);\n}\n\n// Cache the latest warm-tier summary alongside the boundary it covers. The\n// chat UI considers the summary fresh only when `warm_summary_before` matches\n// the current `hot_since`; any boundary change triggers a re-summarise on the\n// next run rather than a synchronous LLM call here.\nexport function setThreadWarmSummary(\n thread_id: string,\n summary: string,\n before: string | null,\n): void {\n getDb()\n .prepare(\n \"UPDATE threads SET warm_summary=?, warm_summary_before=?, warm_summary_computed_at=? WHERE thread_id=?\",\n )\n .run(summary, before, now(), thread_id);\n}\n","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","createThread","listThreads","getAgentConfig","errorResponse","notFoundResponse","createdResponse","GET","req","searchParams","nextUrl","limit","Number","get","offset","json","POST","agent_id","title","thread","message","status","error","data","cachedJson","maxAgeSeconds","headers","validateBody","schema","raw","parsed","safeParse","success","issues","getDb","MBTI_PRESETS","now","Date","toISOString","getAgentTierProportions","row","context_tier_proportions","JSON","parse","hot","warm","facts","every","n","isFinite","listAgentConfigs","prepare","all","getDefaultAgentConfig","id","getAgentTools","cfg","tools","Array","isArray","filter","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","undefined","delegateTargets","delegate_targets","stringify","tierProportions","Math","max","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","trim","requireSourceLinks","require_source_links","name","icon","identity","instructions","model_config_name","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","min","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","randomUUID","embedOne","MSG_COLS_SQL","listThreadsByAgent","getThread","thread_id","updated_at","message_count","deleteThread","r","getMessages","getRecentMessagesWindow","sinceISO","params","sql","push","rows","reverse","getMessagesAfter","afterISO","getMessagesPage","beforeISO","has_more","messages","addMessage","role","content","toolEvents","category","metadata","msg_id","toolEventsJson","metadataJson","Object","keys","then","vec","catch","tool_events","setMessageMetadata","getOrCreateAgentThread","agentId","clearThreadMessages","threadId","touchThread","firstMsg","setThreadContextPin","hot_since","setThreadWarmSummary","summary","before"],"sourceRoot":"","ignoreList":[0,3,5,12,19,26,36]}
1
+ {"version":3,"file":"../app/api/v1/threads/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;CAKC,GAEuD;AACS;AACL;AAC2B;AAEhF,SAASO,IAAIC,GAAgB;IAClC,MAAM,EAAEC,YAAY,EAAE,GAAGD,IAAIE,OAAO;IACpC,MAAMC,QAAQC,OAAOH,aAAaI,GAAG,CAAC,YAAY;IAClD,MAAMC,SAASF,OAAOH,aAAaI,GAAG,CAAC,aAAa;IACpD,OAAOb,mBAAYA,CAACe,IAAI,CAACb,+BAAWA,CAACS,OAAOG;AAC9C;AAEO,eAAeE,KAAKR,GAAgB;IACzC,MAAM,EAAES,QAAQ,EAAEC,KAAK,EAAE,GAAG,MAAMV,IAAIO,IAAI;IAC1C,IAAI,CAACE,UAAU,OAAOb,mCAAaA,CAAC;IACpC,IAAI,CAACD,wCAAcA,CAACc,WAAW,OAAOZ,sCAAgBA,CAAC,CAAC,OAAO,EAAEY,SAAS,WAAW,CAAC;IACtF,MAAME,SAASlB,gCAAYA,CAACgB,UAAUC;IACtC,OAAOZ,qCAAeA,CAACa;AACzB;;;ACzB+F;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACsB;AACxF;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;A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;;;;;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/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/./app/api/v1/threads/route.ts","webpack://@circuitwall/jarela/?0774","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/api/responses.ts","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/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/stores/threads.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\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","/**\n * @public — `GET /api/v1/threads` (list), `POST /api/v1/threads` (create)\n *\n * Thread lifecycle. Threads are the unit of conversation history; every\n * agent run lives inside one. See `docs/api.md`.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { createThread, listThreads } from \"@/lib/stores/threads\";\nimport { getAgentConfig } from \"@/lib/stores/agent-configs\";\nimport { errorResponse, notFoundResponse, createdResponse } from \"@/lib/api/responses\";\n\nexport function GET(req: NextRequest) {\n const { searchParams } = req.nextUrl;\n const limit = Number(searchParams.get(\"limit\") ?? 50);\n const offset = Number(searchParams.get(\"offset\") ?? 0);\n return NextResponse.json(listThreads(limit, offset));\n}\n\nexport async function POST(req: NextRequest) {\n const { agent_id, title } = await req.json() as { agent_id: string; title?: string };\n if (!agent_id) return errorResponse(\"agent_id required\");\n if (!getAgentConfig(agent_id)) return notFoundResponse(`Agent \"${agent_id}\" not found`);\n const thread = createThread(agent_id, title);\n return createdResponse(thread);\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/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/route\",\n pathname: \"/api/v1/threads\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/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/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/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/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(\"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\");","// Shared HTTP response builders for app/api/v1/** route handlers.\n//\n// Goal: every error/success payload across the v1 surface has the same\n// shape. Before this lived inline, response bodies drifted —\n// `{error: \"x\"}` vs `{message: \"x\"}`, 400 vs 422 for the same condition,\n// some routes returned Zod's raw issue array, others stringified it.\n\nimport { NextResponse } from \"next/server\";\nimport type { z } from \"zod\";\nimport type { NextRequest } from \"next/server\";\n\nexport function errorResponse(message: string, status: number = 400): NextResponse {\n return NextResponse.json({ error: message }, { status });\n}\n\nexport function notFoundResponse(message: string = \"Not found\"): NextResponse {\n return errorResponse(message, 404);\n}\n\nexport function createdResponse<T>(data: T): NextResponse {\n return NextResponse.json(data, { status: 201 });\n}\n\n// Wrap a 200 JSON response with a private Cache-Control header. Use on safe\n// GET endpoints that serve user-scoped data the client refetches often (panel\n// mounts, navigation back/forward) but mutates rarely. The TTL is short\n// enough that explicit mutations — which patch the client-side ApiClient\n// cache in place — stay observably consistent without an extra roundtrip.\nexport function cachedJson<T>(data: T, maxAgeSeconds: number): NextResponse {\n return NextResponse.json(data, {\n headers: {\n \"Cache-Control\": `private, max-age=${maxAgeSeconds}`,\n },\n });\n}\n\n// Validate a JSON request body against a zod schema.\n// Returns either the parsed data or a 400 NextResponse explaining the issue.\n// Caller pattern:\n// const parsed = await validateBody(req, Schema);\n// if (parsed instanceof NextResponse) return parsed;\n// // use parsed.field\nexport async function validateBody<S extends z.ZodTypeAny>(\n req: NextRequest,\n schema: S,\n): Promise<z.infer<S> | NextResponse> {\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return errorResponse(\"Request body must be valid JSON\", 400);\n }\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n return errorResponse(parsed.error.issues[0]?.message ?? \"invalid body\", 400);\n }\n return parsed.data;\n}\n","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\");","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\");","import { randomUUID } from \"node:crypto\";\nimport { getDb } from \"@/lib/db\";\nimport { embedOne } from \"@/lib/embeddings\";\n\nconst now = () => new Date().toISOString();\n\n// Explicit column list for message reads — omits `embedding` (~20KB of\n// JSON-encoded float[] per row) which only the embeddings module reads.\n// Avoids dragging it through the chat-history result set on every call.\nconst MSG_COLS_SQL = \"SELECT msg_id, thread_id, role, content, created_at, tool_events, category, metadata FROM messages\";\n\nexport interface ThreadRow {\n thread_id: string; agent_id: string; title: string | null;\n created_at: string; updated_at: string; message_count: number;\n // ADR-0042 — explicit context pin + cached warm summary. NULL on threads\n // that haven't had the boundary moved away from the agent default. The\n // summary is fresh only when warm_summary_before === hot_since.\n hot_since?: string | null;\n warm_summary?: string | null;\n warm_summary_before?: string | null;\n warm_summary_computed_at?: string | null;\n}\nexport interface MessageRow {\n msg_id: string; thread_id: string; role: string; content: string; created_at: string;\n // JSON-encoded array of PersistedToolEvent. null when no tool work happened\n // on this turn or for user messages. Read back by the chat UI so historical\n // bubbles show the same expandable CALL/RESULT entries as live streaming.\n tool_events?: string | null;\n // Non-null tags classify the message into a filterable group in the chat\n // panel (e.g. 'scheduled_task', 'bridge', 'synthetic'). NULL = ordinary\n // user/assistant chat content.\n category?: string | null;\n // JSON-encoded auxiliary per-message data. NULL on legacy rows. Currently\n // carries the citation-checker verdict when `require_source_links` is on.\n metadata?: string | null;\n}\n\nexport interface PersistedToolEvent {\n id: string;\n phase: \"call\" | \"result\";\n name: string;\n payload: unknown;\n}\n\nexport function listThreads(limit = 50, offset = 0): ThreadRow[] {\n return getDb()\n .prepare(\"SELECT * FROM threads ORDER BY updated_at DESC LIMIT ? OFFSET ?\")\n .all(limit, offset) as unknown as ThreadRow[];\n}\n\nexport function listThreadsByAgent(agent_id: string, limit = 50): ThreadRow[] {\n return getDb()\n .prepare(\"SELECT * FROM threads WHERE agent_id=? ORDER BY updated_at DESC LIMIT ?\")\n .all(agent_id, limit) as unknown as ThreadRow[];\n}\n\nexport function getThread(thread_id: string): ThreadRow | null {\n return (getDb().prepare(\"SELECT * FROM threads WHERE thread_id=?\").get(thread_id) as unknown as ThreadRow) ?? null;\n}\n\nexport function createThread(agent_id: string, title?: string): ThreadRow {\n const t = now();\n const thread_id = randomUUID();\n getDb()\n .prepare(\"INSERT INTO threads (thread_id,agent_id,title,created_at,updated_at,message_count) VALUES (?,?,?,?,?,0)\")\n .run(thread_id, agent_id, title ?? null, t, t);\n return { thread_id, agent_id, title: title ?? null, created_at: t, updated_at: t, message_count: 0 };\n}\n\nexport function deleteThread(thread_id: string): boolean {\n const db = getDb();\n db.prepare(\"DELETE FROM messages WHERE thread_id=?\").run(thread_id);\n const r = db.prepare(\"DELETE FROM threads WHERE thread_id=?\").run(thread_id);\n return r.changes > 0;\n}\n\nexport function getMessages(thread_id: string): MessageRow[] {\n return getDb()\n .prepare(MSG_COLS_SQL + \" WHERE thread_id=? ORDER BY created_at ASC\")\n .all(thread_id) as unknown as MessageRow[];\n}\n\n// Pull the latest N messages within a time window. Used to build the LLM\n// context — keeps prompt size bounded as threads grow indefinitely.\n// limit: 0 or negative = unlimited\n// sinceISO: undefined = no time bound\n// Returns chronological order (oldest first) so it can be appended to the prompt directly.\nexport function getRecentMessagesWindow(\n thread_id: string,\n limit: number,\n sinceISO?: string,\n): MessageRow[] {\n const db = getDb();\n const params: (string | number)[] = [thread_id];\n let sql = MSG_COLS_SQL + \" WHERE thread_id=?\";\n if (sinceISO) {\n sql += \" AND created_at >= ?\";\n params.push(sinceISO);\n }\n sql += \" ORDER BY created_at DESC\";\n if (limit > 0) {\n sql += \" LIMIT ?\";\n params.push(limit);\n }\n const rows = db.prepare(sql).all(...params) as unknown as MessageRow[];\n return rows.reverse();\n}\n\n// Forward-fetch — return messages strictly newer than `afterISO`, oldest\n// first, capped at `limit`. Used by the chat view to pull only the\n// freshly-persisted user+assistant pair after a run completes, instead of\n// re-fetching the whole most-recent page.\nexport function getMessagesAfter(\n thread_id: string,\n afterISO: string,\n limit = 50,\n): MessageRow[] {\n return getDb()\n .prepare(\n MSG_COLS_SQL +\n \" WHERE thread_id=? AND created_at > ? ORDER BY created_at ASC LIMIT ?\",\n )\n .all(thread_id, afterISO, limit) as unknown as MessageRow[];\n}\n\n// Pagination for the chat UI. Returns the latest N messages strictly older\n// than `beforeISO` (cursor). Caller passes the oldest already-loaded message's\n// created_at as the cursor; first page omits beforeISO.\nexport function getMessagesPage(\n thread_id: string,\n limit: number,\n beforeISO?: string,\n): { messages: MessageRow[]; has_more: boolean } {\n const db = getDb();\n const params: (string | number)[] = [thread_id];\n let sql = MSG_COLS_SQL + \" WHERE thread_id=?\";\n if (beforeISO) {\n sql += \" AND created_at < ?\";\n params.push(beforeISO);\n }\n sql += \" ORDER BY created_at DESC LIMIT ?\";\n params.push(limit + 1); // fetch one extra to detect if there's more\n const rows = db.prepare(sql).all(...params) as unknown as MessageRow[];\n const has_more = rows.length > limit;\n return { messages: rows.slice(0, limit).reverse(), has_more };\n}\n\nexport function addMessage(\n thread_id: string,\n role: \"user\" | \"assistant\",\n content: string,\n toolEvents?: PersistedToolEvent[] | null,\n category: string | null = null,\n metadata?: Record<string, unknown> | null,\n): MessageRow {\n const msg_id = randomUUID();\n const t = now();\n const db = getDb();\n const toolEventsJson = toolEvents && toolEvents.length > 0 ? JSON.stringify(toolEvents) : null;\n const metadataJson = metadata && Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : null;\n db.prepare(\"INSERT INTO messages (msg_id,thread_id,role,content,created_at,tool_events,category,metadata) VALUES (?,?,?,?,?,?,?,?)\")\n .run(msg_id, thread_id, role, content, t, toolEventsJson, category, metadataJson);\n db.prepare(\"UPDATE threads SET message_count=message_count+1 WHERE thread_id=?\").run(thread_id);\n // Best-effort: embed the message so semantic recall can pull it back later.\n // Skip empty / very short content (greetings have no useful signal).\n if (content.trim().length >= 12) {\n embedOne(content).then((vec) => {\n if (vec) {\n getDb().prepare(\"UPDATE messages SET embedding=? WHERE msg_id=?\").run(JSON.stringify(vec), msg_id);\n }\n }).catch(() => { /* logged in embeddings module */ });\n }\n return { msg_id, thread_id, role, content, created_at: t, tool_events: toolEventsJson, category, metadata: metadataJson };\n}\n\n// Replace a single message's metadata blob. Used by the citation checker\n// to write its verdict back after the assistant turn has already been\n// persisted (the checker runs async post-insert so the chat UI sees the\n// content immediately and picks up the metadata on the next refresh).\nexport function setMessageMetadata(msg_id: string, metadata: Record<string, unknown> | null): void {\n const json = metadata && Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : null;\n getDb().prepare(\"UPDATE messages SET metadata=? WHERE msg_id=?\").run(json, msg_id);\n}\n\nexport function getOrCreateAgentThread(agentId: string): ThreadRow {\n const existing = getDb()\n .prepare(\"SELECT * FROM threads WHERE agent_id=? LIMIT 1\")\n .get(agentId) as ThreadRow | undefined;\n if (existing) return existing;\n return createThread(agentId);\n}\n\nexport function clearThreadMessages(threadId: string): void {\n const db = getDb();\n db.prepare(\"DELETE FROM messages WHERE thread_id=?\").run(threadId);\n db.prepare(\"UPDATE threads SET message_count=0, updated_at=? WHERE thread_id=?\")\n .run(new Date().toISOString(), threadId);\n}\n\nexport function touchThread(thread_id: string, firstMsg?: string): void {\n const t = now();\n getDb()\n .prepare(\"UPDATE threads SET updated_at=?, title=COALESCE(title,?) WHERE thread_id=?\")\n .run(t, firstMsg ? firstMsg.slice(0, 80) : null, thread_id);\n}\n\n// ADR-0042. Move the user's explicit boundary between hot and warm context.\n// Pass `null` to clear the pin and let the agent's default window apply\n// again. Persisting the pin here keeps it stable across reloads and devices.\nexport function setThreadContextPin(thread_id: string, hot_since: string | null): void {\n getDb()\n .prepare(\"UPDATE threads SET hot_since=? WHERE thread_id=?\")\n .run(hot_since, thread_id);\n}\n\n// Cache the latest warm-tier summary alongside the boundary it covers. The\n// chat UI considers the summary fresh only when `warm_summary_before` matches\n// the current `hot_since`; any boundary change triggers a re-summarise on the\n// next run rather than a synchronous LLM call here.\nexport function setThreadWarmSummary(\n thread_id: string,\n summary: string,\n before: string | null,\n): void {\n getDb()\n .prepare(\n \"UPDATE threads SET warm_summary=?, warm_summary_before=?, warm_summary_computed_at=? WHERE thread_id=?\",\n )\n .run(summary, before, now(), thread_id);\n}\n","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","createThread","listThreads","getAgentConfig","errorResponse","notFoundResponse","createdResponse","GET","req","searchParams","nextUrl","limit","Number","get","offset","json","POST","agent_id","title","thread","message","status","error","data","cachedJson","maxAgeSeconds","headers","validateBody","schema","raw","parsed","safeParse","success","issues","getDb","MBTI_PRESETS","now","Date","toISOString","getAgentTierProportions","row","context_tier_proportions","JSON","parse","hot","warm","facts","every","n","isFinite","listAgentConfigs","prepare","all","getDefaultAgentConfig","id","getAgentTools","cfg","tools","Array","isArray","filter","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","undefined","delegateTargets","delegate_targets","stringify","tierProportions","Math","max","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","trim","requireSourceLinks","require_source_links","name","icon","identity","instructions","model_config_name","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","min","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","randomUUID","embedOne","MSG_COLS_SQL","listThreadsByAgent","getThread","thread_id","updated_at","message_count","deleteThread","r","getMessages","getRecentMessagesWindow","sinceISO","params","sql","push","rows","reverse","getMessagesAfter","afterISO","getMessagesPage","beforeISO","has_more","messages","addMessage","role","content","toolEvents","category","metadata","msg_id","toolEventsJson","metadataJson","Object","keys","then","vec","catch","tool_events","setMessageMetadata","getOrCreateAgentThread","agentId","clearThreadMessages","threadId","touchThread","firstMsg","setThreadContextPin","hot_since","setThreadWarmSummary","summary","before"],"sourceRoot":"","ignoreList":[0,3,5,12,19,26,36]}
@@ -92,14 +92,21 @@ var no_fallback_error_external_ = __webpack_require__(86439);
92
92
  var response_cache = __webpack_require__(37527);
93
93
  // EXTERNAL MODULE: ./node_modules/next/dist/api/server.js
94
94
  var server = __webpack_require__(23211);
95
- // EXTERNAL MODULE: ./lib/tools/index.ts + 23 modules
96
- var tools = __webpack_require__(64011);
95
+ // EXTERNAL MODULE: ./lib/tools/index.ts + 27 modules
96
+ var tools = __webpack_require__(36141);
97
97
  // EXTERNAL MODULE: ./lib/api/responses.ts
98
98
  var responses = __webpack_require__(39947);
99
99
  // EXTERNAL MODULE: ./lib/stores/tool-stats.ts
100
100
  var tool_stats = __webpack_require__(49899);
101
101
  ;// ./app/api/v1/tools/route.ts
102
-
102
+ /**
103
+ * @public — `GET /api/v1/tools`
104
+ *
105
+ * Lists every tool in the agent's pool — built-in, external (loaded from
106
+ * `~/.jarela/tools/*.cjs`), and MCP — with category, capability, source,
107
+ * and per-tool stats. The agent-callable equivalent is the `list_tools`
108
+ * tool. See `docs/api.md`.
109
+ */
103
110
 
104
111
 
105
112
 
@@ -1 +1 @@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AAEK,QAAQ;QAAI;IAElB;AACF;;;ACpC+F;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACoB;AACtF;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AAC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tD;IACF;AACF;AAEA,qDAAqD;AACrD,6EAA6E;AAC7E,kBAAkB;AAClB,oDAAoD;AACpD,uDAAuD;AACvD,wBAAwB;AACjB,eAAeE,aACpBC,GAAgB,EAChBC,MAAS;IAET,IAAIC;IACJ,IAAI;QACFA,MAAM,MAAMF,IAAIb,IAAI;IACtB,EAAE,OAAM;QACN,OAAOK,cAAc,mCAAmC;IAC1D;IACA,MAAMW,SAASF,OAAOG,SAAS,CAACF;IAChC,IAAI,CAACC,OAAOE,OAAO,EAAE;QACnB,OAAOb,cAAcW,OAAOf,KAAK,CAACkB,MAAM,CAAC,EAAE,EAAEb,WAAW,gBAAgB;IAC1E;IACA,OAAOU,OAAOP,IAAI;AACpB;;;;;;;;ACzDA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;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/tools/route.ts","webpack://@circuitwall/jarela/?79c4","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/api/responses.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/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:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/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 { NextResponse } from \"next/server\";\nimport { getAllToolsAsync, getToolCategory, getToolCapability, getToolGroup, getToolSource } from \"@/lib/tools\";\nimport { cachedJson } from \"@/lib/api/responses\";\nimport { defaultToolStats, getToolStatsMap } from \"@/lib/stores/tool-stats\";\n\nexport async function GET() {\n try {\n // Use the async path so MCP-provided tools show up in the agent config UI.\n // Source (\"builtin\" | \"external\" | \"mcp\") is derived inside lib/tools so\n // callers can't conflate external tools with MCP tools.\n const all = await getAllToolsAsync();\n const stats = getToolStatsMap(all.map((t) => t.name));\n return cachedJson(\n all.map((t) => ({\n name: t.name,\n description: t.description,\n source: getToolSource(t.name),\n category: getToolCategory(t.name),\n capability: getToolCapability(t.name),\n group: getToolGroup(t.name),\n stats: stats.get(t.name) ?? defaultToolStats(),\n })).sort((a, b) => {\n const scoreDiff = (b.stats?.score ?? 0) - (a.stats?.score ?? 0);\n if (scoreDiff !== 0) return scoreDiff;\n const usedDiff = (b.stats?.used_count ?? 0) - (a.stats?.used_count ?? 0);\n if (usedDiff !== 0) return usedDiff;\n return a.name.localeCompare(b.name);\n }),\n 60,\n );\n } catch (err) {\n return NextResponse.json(\n { error: \"Failed to list tools\", detail: String(err) },\n { status: 500 },\n );\n }\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/tools/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/tools/route\",\n pathname: \"/api/v1/tools\",\n filename: \"route\",\n bundlePath: \"app/api/v1/tools/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/tools/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/tools/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/tools/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\");","// Shared HTTP response builders for app/api/v1/** route handlers.\n//\n// Goal: every error/success payload across the v1 surface has the same\n// shape. Before this lived inline, response bodies drifted —\n// `{error: \"x\"}` vs `{message: \"x\"}`, 400 vs 422 for the same condition,\n// some routes returned Zod's raw issue array, others stringified it.\n\nimport { NextResponse } from \"next/server\";\nimport type { z } from \"zod\";\nimport type { NextRequest } from \"next/server\";\n\nexport function errorResponse(message: string, status: number = 400): NextResponse {\n return NextResponse.json({ error: message }, { status });\n}\n\nexport function notFoundResponse(message: string = \"Not found\"): NextResponse {\n return errorResponse(message, 404);\n}\n\nexport function createdResponse<T>(data: T): NextResponse {\n return NextResponse.json(data, { status: 201 });\n}\n\n// Wrap a 200 JSON response with a private Cache-Control header. Use on safe\n// GET endpoints that serve user-scoped data the client refetches often (panel\n// mounts, navigation back/forward) but mutates rarely. The TTL is short\n// enough that explicit mutations — which patch the client-side ApiClient\n// cache in place — stay observably consistent without an extra roundtrip.\nexport function cachedJson<T>(data: T, maxAgeSeconds: number): NextResponse {\n return NextResponse.json(data, {\n headers: {\n \"Cache-Control\": `private, max-age=${maxAgeSeconds}`,\n },\n });\n}\n\n// Validate a JSON request body against a zod schema.\n// Returns either the parsed data or a 400 NextResponse explaining the issue.\n// Caller pattern:\n// const parsed = await validateBody(req, Schema);\n// if (parsed instanceof NextResponse) return parsed;\n// // use parsed.field\nexport async function validateBody<S extends z.ZodTypeAny>(\n req: NextRequest,\n schema: S,\n): Promise<z.infer<S> | NextResponse> {\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return errorResponse(\"Request body must be valid JSON\", 400);\n }\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n return errorResponse(parsed.error.issues[0]?.message ?? \"invalid body\", 400);\n }\n return parsed.data;\n}\n","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","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:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","module.exports = require(\"events\");"],"names":["NextResponse","getAllToolsAsync","getToolCategory","getToolCapability","getToolGroup","getToolSource","cachedJson","defaultToolStats","getToolStatsMap","GET","all","stats","map","t","name","description","source","category","capability","group","get","sort","a","b","scoreDiff","score","usedDiff","used_count","localeCompare","err","json","error","detail","String","status","errorResponse","message","notFoundResponse","createdResponse","data","maxAgeSeconds","headers","validateBody","req","schema","raw","parsed","safeParse","success","issues"],"sourceRoot":"","ignoreList":[0,3,7,12,19,26,37]}
1
+ {"version":3,"file":"../app/api/v1/tools/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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B,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC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AI;QACFA,MAAM,MAAMF,IAAIb,IAAI;IACtB,EAAE,OAAM;QACN,OAAOK,cAAc,mCAAmC;IAC1D;IACA,MAAMW,SAASF,OAAOG,SAAS,CAACF;IAChC,IAAI,CAACC,OAAOE,OAAO,EAAE;QACnB,OAAOb,cAAcW,OAAOf,KAAK,CAACkB,MAAM,CAAC,EAAE,EAAEb,WAAW,gBAAgB;IAC1E;IACA,OAAOU,OAAOP,IAAI;AACpB;;;;;;;;ACzDA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;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/tools/route.ts","webpack://@circuitwall/jarela/?79c4","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/api/responses.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/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:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/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/tools`\n *\n * Lists every tool in the agent's pool — built-in, external (loaded from\n * `~/.jarela/tools/*.cjs`), and MCP — with category, capability, source,\n * and per-tool stats. The agent-callable equivalent is the `list_tools`\n * tool. See `docs/api.md`.\n */\n\nimport { NextResponse } from \"next/server\";\nimport { getAllToolsAsync, getToolCategory, getToolCapability, getToolGroup, getToolSource } from \"@/lib/tools\";\nimport { cachedJson } from \"@/lib/api/responses\";\nimport { defaultToolStats, getToolStatsMap } from \"@/lib/stores/tool-stats\";\n\nexport async function GET() {\n try {\n // Use the async path so MCP-provided tools show up in the agent config UI.\n // Source (\"builtin\" | \"external\" | \"mcp\") is derived inside lib/tools so\n // callers can't conflate external tools with MCP tools.\n const all = await getAllToolsAsync();\n const stats = getToolStatsMap(all.map((t) => t.name));\n return cachedJson(\n all.map((t) => ({\n name: t.name,\n description: t.description,\n source: getToolSource(t.name),\n category: getToolCategory(t.name),\n capability: getToolCapability(t.name),\n group: getToolGroup(t.name),\n stats: stats.get(t.name) ?? defaultToolStats(),\n })).sort((a, b) => {\n const scoreDiff = (b.stats?.score ?? 0) - (a.stats?.score ?? 0);\n if (scoreDiff !== 0) return scoreDiff;\n const usedDiff = (b.stats?.used_count ?? 0) - (a.stats?.used_count ?? 0);\n if (usedDiff !== 0) return usedDiff;\n return a.name.localeCompare(b.name);\n }),\n 60,\n );\n } catch (err) {\n return NextResponse.json(\n { error: \"Failed to list tools\", detail: String(err) },\n { status: 500 },\n );\n }\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/tools/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/tools/route\",\n pathname: \"/api/v1/tools\",\n filename: \"route\",\n bundlePath: \"app/api/v1/tools/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/tools/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/tools/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/tools/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\");","// Shared HTTP response builders for app/api/v1/** route handlers.\n//\n// Goal: every error/success payload across the v1 surface has the same\n// shape. Before this lived inline, response bodies drifted —\n// `{error: \"x\"}` vs `{message: \"x\"}`, 400 vs 422 for the same condition,\n// some routes returned Zod's raw issue array, others stringified it.\n\nimport { NextResponse } from \"next/server\";\nimport type { z } from \"zod\";\nimport type { NextRequest } from \"next/server\";\n\nexport function errorResponse(message: string, status: number = 400): NextResponse {\n return NextResponse.json({ error: message }, { status });\n}\n\nexport function notFoundResponse(message: string = \"Not found\"): NextResponse {\n return errorResponse(message, 404);\n}\n\nexport function createdResponse<T>(data: T): NextResponse {\n return NextResponse.json(data, { status: 201 });\n}\n\n// Wrap a 200 JSON response with a private Cache-Control header. Use on safe\n// GET endpoints that serve user-scoped data the client refetches often (panel\n// mounts, navigation back/forward) but mutates rarely. The TTL is short\n// enough that explicit mutations — which patch the client-side ApiClient\n// cache in place — stay observably consistent without an extra roundtrip.\nexport function cachedJson<T>(data: T, maxAgeSeconds: number): NextResponse {\n return NextResponse.json(data, {\n headers: {\n \"Cache-Control\": `private, max-age=${maxAgeSeconds}`,\n },\n });\n}\n\n// Validate a JSON request body against a zod schema.\n// Returns either the parsed data or a 400 NextResponse explaining the issue.\n// Caller pattern:\n// const parsed = await validateBody(req, Schema);\n// if (parsed instanceof NextResponse) return parsed;\n// // use parsed.field\nexport async function validateBody<S extends z.ZodTypeAny>(\n req: NextRequest,\n schema: S,\n): Promise<z.infer<S> | NextResponse> {\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return errorResponse(\"Request body must be valid JSON\", 400);\n }\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n return errorResponse(parsed.error.issues[0]?.message ?? \"invalid body\", 400);\n }\n return parsed.data;\n}\n","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","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:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","module.exports = require(\"events\");"],"names":["NextResponse","getAllToolsAsync","getToolCategory","getToolCapability","getToolGroup","getToolSource","cachedJson","defaultToolStats","getToolStatsMap","GET","all","stats","map","t","name","description","source","category","capability","group","get","sort","a","b","scoreDiff","score","usedDiff","used_count","localeCompare","err","json","error","detail","String","status","errorResponse","message","notFoundResponse","createdResponse","data","maxAgeSeconds","headers","validateBody","req","schema","raw","parsed","safeParse","success","issues"],"sourceRoot":"","ignoreList":[0,3,7,12,19,26,37]}