@circuitwall/jarela 0.14.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
- package/.next/standalone/.next/build-manifest.json +2 -2
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +2 -2
- package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/agents/[id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/agents/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/agents/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +36 -29
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js +3 -3
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +4 -4
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/health/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/health/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/[name]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/mcp-servers/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/models/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/models/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +14 -7
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js +28 -0
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/models/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/providers/route.js +7 -1
- package/.next/standalone/.next/server/app/api/v1/providers/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js +16 -2
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/route.js +6 -1
- package/.next/standalone/.next/server/app/api/v1/threads/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/tools/route.js +10 -3
- package/.next/standalone/.next/server/app/api/v1/tools/route.js.map +1 -1
- package/.next/standalone/.next/server/app/index.html +2 -2
- package/.next/standalone/.next/server/app/index.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page.js +56 -0
- package/.next/standalone/.next/server/app/page.js.map +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup.html +1 -1
- package/.next/standalone/.next/server/app/setup.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/setup.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/setup.segments/setup/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/setup.segments/setup.segment.rsc +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +1 -1
- package/.next/standalone/.next/server/chunks/1683.js +2 -2
- package/.next/standalone/.next/server/chunks/2082.js +122 -13
- package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
- package/.next/standalone/.next/server/chunks/210.js +3 -3
- package/.next/standalone/.next/server/chunks/210.js.map +1 -1
- package/.next/standalone/.next/server/chunks/239.js +1902 -1487
- package/.next/standalone/.next/server/chunks/239.js.map +1 -1
- package/.next/standalone/.next/server/chunks/2447.js +9 -1
- package/.next/standalone/.next/server/chunks/2447.js.map +1 -1
- package/.next/standalone/.next/server/chunks/423.js +125 -16
- package/.next/standalone/.next/server/chunks/423.js.map +1 -1
- package/.next/standalone/.next/server/chunks/4631.js +36 -29
- package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
- package/.next/standalone/.next/server/chunks/5937.js +3 -2
- package/.next/standalone/.next/server/chunks/5937.js.map +1 -1
- package/.next/standalone/.next/server/chunks/{947.js → 8866.js} +11321 -10883
- package/.next/standalone/.next/server/chunks/8866.js.map +1 -0
- package/.next/standalone/.next/server/chunks/9032.js +3 -3
- package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
- package/.next/standalone/.next/server/middleware.js +122 -13
- package/.next/standalone/.next/server/pages/404.html +2 -2
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/proxy.js.map +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/static/chunks/app/{page-473b39ec30c7f569.js → page-a7cae65f235e2942.js} +57 -1
- package/.next/standalone/.next/static/chunks/app/page-a7cae65f235e2942.js.map +1 -0
- package/.next/standalone/.next/static/css/{6f8b1a84bcbcd467.css → e57bdbbbb5a05779.css} +2 -2
- package/.next/standalone/.next/static/css/e57bdbbbb5a05779.css.map +1 -0
- package/.next/standalone/package.json +9 -1
- package/CHANGELOG.md +90 -0
- package/README.md +30 -2
- package/api/types.ts +8 -0
- package/app/api/v1/agents/[id]/route.ts +7 -0
- package/app/api/v1/agents/route.ts +7 -0
- package/app/api/v1/events/route.ts +8 -0
- package/app/api/v1/extensions/route.ts +2 -2
- package/app/api/v1/extensions/tools/[name]/secrets/route.ts +3 -3
- package/app/api/v1/health/route.ts +8 -0
- package/app/api/v1/models/route.ts +7 -0
- package/app/api/v1/page-capture/route.ts +8 -0
- package/app/api/v1/providers/route.ts +8 -0
- package/app/api/v1/threads/[thread_id]/route.ts +8 -0
- package/app/api/v1/threads/[thread_id]/run/route.ts +9 -0
- package/app/api/v1/threads/route.ts +7 -0
- package/app/api/v1/tools/route.ts +9 -0
- package/components/chat/ContextUsageBar.tsx +44 -0
- package/lib/agents/llm.ts +25 -2
- package/lib/agents/run-thread.ts +13 -1
- package/lib/agents/stream-collector.ts +9 -1
- package/lib/api/serializers.test.ts +15 -0
- package/lib/api/serializers.ts +8 -0
- package/lib/db/migrations.ts +15 -0
- package/lib/health/runner.test.ts +24 -2
- package/lib/mcp/registry.ts +14 -6
- package/lib/providers/anthropic.test.ts +95 -0
- package/lib/providers/anthropic.ts +106 -10
- package/lib/providers/jarela-chat-model.ts +9 -1
- package/lib/providers/known-context-windows.ts +21 -0
- package/lib/providers/types.ts +21 -1
- package/lib/stores/message-usage.test.ts +34 -0
- package/lib/stores/message-usage.ts +15 -3
- package/lib/stores/pricing.test.ts +52 -0
- package/lib/stores/pricing.ts +26 -1
- package/lib/tools/builtins.ts +4 -0
- package/lib/tools/extension-surfaces.test.ts +79 -0
- package/lib/tools/extension-surfaces.ts +153 -0
- package/lib/tools/index.ts +27 -8
- package/lib/tools/list-tools.test.ts +76 -0
- package/lib/tools/list-tools.ts +84 -0
- package/lib/tools/mcp-servers-info.test.ts +73 -0
- package/lib/tools/mcp-servers-info.ts +71 -0
- package/lib/tools/providers-info.test.ts +73 -0
- package/lib/tools/providers-info.ts +106 -0
- package/lib/tools/registry.ts +36 -25
- package/lib/tools/types.ts +13 -0
- package/package.json +9 -1
- package/.next/standalone/.next/server/chunks/947.js.map +0 -1
- package/.next/standalone/.next/static/chunks/app/page-473b39ec30c7f569.js.map +0 -1
- package/.next/standalone/.next/static/css/6f8b1a84bcbcd467.css.map +0 -1
- /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{T0p2VVPsJPj44rwbmjaFb → d_vhp-lJqfdjRFpnLVIqZ}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"../app/api/v1/page-capture/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;ACAA,4EAA4E;AAC5E,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,qEAAqE;AACrE,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,uDAAuD;AAChD,SAASA,kBAAqBC,GAAW,EAAEC,OAAgB;IAChE,MAAMC,IAAIC;IACV,IAAID,CAAC,CAACF,IAAI,KAAKI,WAAWF,CAAC,CAACF,IAAI,GAAGC;IACnC,OAAOC,CAAC,CAACF,IAAI;AACf;;;;;;;;ACbA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAwB;AAC8B;AAMxB;AAKM;AACc;AAElD,uEA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G,CAAC,aAAa;YAC5D,oCAAoC;YACpC,QAAQ;QACV;IACF;AAEJ;AAEO,SAASC,yBAAyB1B,GAAY;IACnD,OAAO,IAAIC,SAAS,MAAM;QACxBG,QAAQ;QACRC,SAAS;YACP,+BAA+BL,IAAIK,OAAO,CAACoB,GAAG,CAAC,aAAa;YAC5D,gCAAgC;YAChC,gCAAgC;YAChC,0BAA0B;YAC1B,QAAQ;QACV;IACF;AACF;;;ACpMqF;AAE9E,MAAME,OAAO5B,iBAAiBA,CAAC;AAC/B,MAAM6B,UAAUF,wBAAwBA,CAAC;;;ACH+C;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AAC2B;AAC7F;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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ACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,gBAAgB,mBAAmB;AACnC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/./lib/utils/global-state.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/./lib/api/page-capture.ts","webpack://@circuitwall/jarela/./app/api/v1/page-capture/route.ts","webpack://@circuitwall/jarela/?ce97","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/./lib/auth/access.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/./lib/stores/agent-configs.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/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/./lib/notifications/bus.ts","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/./lib/stores/access.ts","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","// Pin a piece of state to globalThis so it survives Next.js dev hot-reload.\n//\n// Without this, every code edit re-evaluates the module, replacing the\n// in-memory state with empty containers — but any active closure still\n// references the OLD set, so listeners/timers/maps go silently dead.\n// The globalThis trick is the standard Next pattern for singletons.\n//\n// `key` must be unique across the app (it lives on globalThis); pick a\n// \"__jarela_<name>\" prefix to keep the namespace tidy.\nexport function getOrCreateGlobal<T>(key: string, factory: () => T): T {\n const g = globalThis as unknown as Record<string, unknown>;\n if (g[key] === undefined) g[key] = factory();\n return g[key] as T;\n}\n","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","import { z } from \"zod\";\nimport { isLoopbackRequest } from \"@/lib/auth/access\";\nimport {\n listThreadsByAgent,\n createThread,\n addMessage,\n type ThreadRow,\n} from \"@/lib/stores/threads\";\nimport {\n getDefaultAgentConfig,\n listAgentConfigs,\n type AgentConfigRow,\n} from \"@/lib/stores/agent-configs\";\nimport { publish } from \"@/lib/notifications/bus\";\n\n// 100KB UTF-8 cap on captured text. The LLM context window is the real\n// constraint; this cap exists to keep a runaway \"<body>\" pick from\n// trashing the conversation. See ADR-0018.\nexport const MAX_TEXT_BYTES = 100_000;\n\nconst Body = z.object({\n url: z.string().url(),\n title: z.string().max(500).optional(),\n selector: z.string().max(2000).optional(),\n tagName: z.string().max(64).optional(),\n text: z.string(),\n capturedAt: z.string().datetime(),\n});\n\nfunction truncateUtf8(s: string, maxBytes: number): { text: string; truncated: boolean; originalBytes: number } {\n const original = Buffer.byteLength(s, \"utf8\");\n if (original <= maxBytes) {\n return { text: s, truncated: false, originalBytes: original };\n }\n // Trim to byte boundary by encoding then slicing then decoding without\n // splitting a multibyte sequence. Buffer.toString(\"utf8\") replaces an\n // incomplete trailing sequence with U+FFFD, which is acceptable here.\n const buf = Buffer.from(s, \"utf8\").subarray(0, maxBytes);\n return { text: buf.toString(\"utf8\"), truncated: true, originalBytes: original };\n}\n\n// Routing rule (per user ask): the capture lands in the most recent thread\n// of the *default agent* — i.e. \"the last agent session\" the user almost\n// certainly meant. If the default agent has never been chatted with, we\n// open a fresh thread under it. If there is no default agent at all\n// (fresh install), fall back to the first configured agent. With zero\n// agents configured we 503 — there is nowhere to put the message.\n//\n// Scoping to the default agent (rather than \"most recent thread of any\n// agent\") makes routing predictable. Otherwise a stray reply on agent B\n// silently retargets future captures away from the agent the user\n// actually thinks of as \"theirs\".\ninterface PickResult {\n thread_id: string;\n agent_id: string;\n agent_name: string;\n thread_title: string | null;\n created: boolean;\n}\n\nfunction pickThread(): PickResult | { error: \"no-agent\" } {\n const def: AgentConfigRow | null = getDefaultAgentConfig();\n const agent: AgentConfigRow | null = def ?? listAgentConfigs()[0] ?? null;\n if (!agent) return { error: \"no-agent\" };\n\n const recent: ThreadRow[] = listThreadsByAgent(agent.id, 1);\n if (recent.length > 0) {\n return {\n thread_id: recent[0].thread_id,\n agent_id: agent.id,\n agent_name: agent.name,\n thread_title: recent[0].title,\n created: false,\n };\n }\n const t = createThread(agent.id, \"Browser captures\");\n return {\n thread_id: t.thread_id,\n agent_id: agent.id,\n agent_name: agent.name,\n thread_title: t.title,\n created: true,\n };\n}\n\nfunction composeBody(args: {\n url: string;\n title?: string;\n selector?: string;\n text: string;\n truncated: boolean;\n originalBytes: number;\n}): string {\n const heading = args.title\n ? `📎 Captured from [${args.title}](${args.url})`\n : `📎 Captured from <${args.url}>`;\n const lines = [heading];\n if (args.selector) lines.push(`Element: \\`${args.selector}\\``);\n if (args.truncated) {\n lines.push(`> ⚠ Truncated to ${MAX_TEXT_BYTES.toLocaleString()} bytes (original was ${args.originalBytes.toLocaleString()} bytes)`);\n }\n lines.push(\"\", \"---\", \"\", args.text);\n return lines.join(\"\\n\");\n}\n\nexport async function handlePageCapture(req: Request): Promise<Response> {\n if (!isLoopbackRequest(req)) {\n return new Response(JSON.stringify({ error: \"loopback only\" }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return new Response(JSON.stringify({ error: \"Request body must be valid JSON\" }), {\n status: 400,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n const parsed = Body.safeParse(raw);\n if (!parsed.success) {\n return new Response(\n JSON.stringify({ error: parsed.error.issues[0]?.message ?? \"invalid body\" }),\n { status: 400, headers: { \"content-type\": \"application/json\" } },\n );\n }\n const input = parsed.data;\n\n const picked = pickThread();\n if (\"error\" in picked) {\n return new Response(JSON.stringify({ error: \"no agent configured\" }), {\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n const { thread_id, agent_id, agent_name, thread_title, created } = picked;\n\n const { text, truncated, originalBytes } = truncateUtf8(input.text, MAX_TEXT_BYTES);\n const messageBody = composeBody({\n url: input.url,\n title: input.title,\n selector: input.selector,\n text,\n truncated,\n originalBytes,\n });\n\n const msg = addMessage(thread_id, \"user\", messageBody, undefined, \"synthetic\");\n\n publish({\n type: \"thread_message_added\",\n thread_id,\n agent_id,\n source: \"page_capture\",\n ts: Date.now(),\n });\n\n return new Response(\n JSON.stringify({\n thread_id,\n msg_id: msg.msg_id,\n agent_id,\n agent_name,\n thread_title,\n created_thread: created,\n truncated,\n originalBytes,\n }),\n {\n status: 200,\n headers: {\n \"content-type\": \"application/json\",\n // Echo back so the extension's preflight succeeds. The actual\n // origin gate for this route is the loopback Host check above.\n \"access-control-allow-origin\": req.headers.get(\"origin\") ?? \"*\",\n \"access-control-allow-credentials\": \"false\",\n \"vary\": \"origin\",\n },\n },\n );\n}\n\nexport function handlePageCaptureOptions(req: Request): Response {\n return new Response(null, {\n status: 204,\n headers: {\n \"access-control-allow-origin\": req.headers.get(\"origin\") ?? \"*\",\n \"access-control-allow-methods\": \"POST, OPTIONS\",\n \"access-control-allow-headers\": \"content-type\",\n \"access-control-max-age\": \"600\",\n \"vary\": \"origin\",\n },\n });\n}\n","import { handlePageCapture, handlePageCaptureOptions } from \"@/lib/api/page-capture\";\n\nexport const POST = handlePageCapture;\nexport const OPTIONS = handlePageCaptureOptions;\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/page-capture/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/page-capture/route\",\n pathname: \"/api/v1/page-capture\",\n filename: \"route\",\n bundlePath: \"app/api/v1/page-capture/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/page-capture/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/page-capture/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/page-capture/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","import { isWhitelisted, touchLastSeen } from \"@/lib/stores/access\";\n\n// Loopback host header signal — only meaningful when the server is bound to\n// 127.0.0.1 (the default). When a reverse proxy fronts Jarela, the proxy is\n// expected to preserve the client's original Host header, so this still\n// distinguishes \"local user typed localhost\" from \"tailnet client\".\nconst LOOPBACK_HOST = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:|$)/;\nconst LOOPBACK_IP = /^(127\\.|::1$|::ffff:127\\.)/;\n\nexport type AccessReason = \"loopback\" | \"whitelisted\" | \"no-identity\" | \"not-whitelisted\";\n\nexport interface AccessResult {\n allowed: boolean;\n identity: string | null;\n reason: AccessReason;\n}\n\ninterface HeaderBag {\n get(name: string): string | null;\n}\n\ninterface NodeHeaders {\n [name: string]: string | string[] | undefined;\n}\n\nfunction readHeader(\n headers: HeaderBag | NodeHeaders,\n name: string,\n): string | null {\n if (typeof (headers as HeaderBag).get === \"function\") {\n return (headers as HeaderBag).get(name);\n }\n const lookup = name.toLowerCase();\n const v = (headers as NodeHeaders)[lookup] ?? (headers as NodeHeaders)[name];\n if (Array.isArray(v)) return v[0] ?? null;\n return v ?? null;\n}\n\nexport interface RequireAccessArgs {\n headers: HeaderBag | NodeHeaders;\n host: string | null;\n remoteAddress?: string | null;\n}\n\nexport function requireAccess({ headers, host, remoteAddress }: RequireAccessArgs): AccessResult {\n // If tailscaled is proxying this request through `tailscale serve` it\n // *always* injects the Tailscale-User-Login header. Whenever the header\n // is present, treat the request as a tailnet request and enforce the\n // whitelist, regardless of whether the source IP / Host header looks\n // like loopback. Otherwise a non-whitelisted tailnet user could chat\n // just because the proxy is local.\n const identity = readHeader(headers, \"tailscale-user-login\")?.trim() || null;\n if (identity) {\n if (isWhitelisted(identity)) {\n touchLastSeen(identity);\n return { allowed: true, identity, reason: \"whitelisted\" };\n }\n return { allowed: false, identity, reason: \"not-whitelisted\" };\n }\n\n // No tailscale identity → only loopback is allowed (the host machine's\n // own user typing http://localhost:4312).\n\n // 1. Actual TCP source available — most reliable loopback signal. Used\n // by callers that have the raw socket (e.g. raw Node handlers).\n if (remoteAddress && LOOPBACK_IP.test(remoteAddress)) {\n return { allowed: true, identity: null, reason: \"loopback\" };\n }\n\n // 2. HTTP middleware path: socket source not available, fall back to Host\n // header. Only trustworthy when the bind is 127.0.0.1 (default).\n if (!remoteAddress && host && LOOPBACK_HOST.test(host)) {\n return { allowed: true, identity: null, reason: \"loopback\" };\n }\n\n return { allowed: false, identity: null, reason: \"no-identity\" };\n}\n\n// Convenience wrapper for API route handlers — they only have `Request`.\nexport function isLoopbackRequest(req: Request): boolean {\n const host = req.headers.get(\"host\");\n return !!host && LOOPBACK_HOST.test(host);\n}\n\n// ---------------------------------------------------------------------------\n// CSRF / cross-origin / DNS-rebinding defense\n// ---------------------------------------------------------------------------\n//\n// The proxy auth above accepts any loopback request — but every page in the\n// user's browser can issue `fetch(\"http://127.0.0.1:4312/...\")`, and a\n// remote DNS-rebinding attacker can make `evil.com` resolve to `127.0.0.1`\n// so the request looks loopback to the kernel. We need to confirm the\n// request *originated* same-origin, not just that the socket terminated on\n// loopback.\n//\n// Defense in depth:\n// 1. `Sec-Fetch-Site` — sent by every modern browser. `same-origin` and\n// `none` (top-level nav, address-bar) are safe; `cross-site` and\n// `same-site` are not. Header absent = non-browser caller (curl,\n// installer scripts) — allow, since those can't be tricked into\n// attaching cookies/auth.\n// 2. `Origin` — when present, scheme+host+port must match `Host`. Blocks\n// DNS rebinding because the Origin reflects the URL the attacker's\n// page was loaded from (`https://evil.com`), not the resolved IP.\n//\n// Read-only methods (GET / HEAD / OPTIONS) skip the check: the legitimate\n// SSE attach uses GET and is intentionally cross-tab in some PWA flows,\n// and these methods shouldn't have side effects anyway.\n\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\nconst SAFE_FETCH_SITES = new Set([\"same-origin\", \"none\"]);\n\nexport type OriginCheckReason =\n | \"safe-method\"\n | \"no-headers\"\n | \"same-origin\"\n | \"cross-site\"\n | \"origin-mismatch\";\n\nexport interface OriginCheckResult {\n allowed: boolean;\n reason: OriginCheckReason;\n}\n\nexport interface ValidateRequestOriginArgs {\n method: string;\n headers: HeaderBag | NodeHeaders;\n host: string | null;\n}\n\nexport function validateRequestOrigin({\n method,\n headers,\n host,\n}: ValidateRequestOriginArgs): OriginCheckResult {\n if (SAFE_METHODS.has(method.toUpperCase())) {\n return { allowed: true, reason: \"safe-method\" };\n }\n\n const secFetchSite = readHeader(headers, \"sec-fetch-site\");\n const origin = readHeader(headers, \"origin\");\n\n // Neither header → non-browser caller. The loopback bind plus the\n // tailnet identity check already gate this.\n if (!secFetchSite && !origin) {\n return { allowed: true, reason: \"no-headers\" };\n }\n\n if (secFetchSite && !SAFE_FETCH_SITES.has(secFetchSite)) {\n return { allowed: false, reason: \"cross-site\" };\n }\n\n if (origin && host) {\n try {\n const originHost = new URL(origin).host;\n if (originHost !== host) {\n return { allowed: false, reason: \"origin-mismatch\" };\n }\n } catch {\n // Malformed Origin → reject.\n return { allowed: false, reason: \"origin-mismatch\" };\n }\n }\n\n return { allowed: true, reason: \"same-origin\" };\n}\n","module.exports = require(\"node:http\");","import { getDb } from \"@/lib/db\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport interface AgentConfigRow {\n id: string;\n name: string;\n icon: string | null;\n identity: string;\n instructions: string;\n tools: string; // JSON string[]\n model_config_name: string | null;\n is_default: number;\n history_limit: number; // 0 = unlimited\n history_window_hours: number; // 0 = no time bound\n never_reply: number; // 1 = run the agent but don't auto-send replies via bridges\n adaptive_persona_enabled: number; // 1 = use runtime mood/tone adaptation hints\n adaptive_persona_strength: number; // 0..100, how strongly to adapt to cues\n adaptive_empathy: number; // 0..100, baseline empathetic tone\n adaptive_expressiveness: number; // 0..100, restrained -> energetic\n adaptive_verbosity: number; // 0..100, concise -> detailed\n adaptive_mbti: string; // one of 16 MBTI types\n voice_enabled: number; // 1 = expose mic/play UI for this agent\n voice_model: string; // Gemini TTS model id\n voice_name: string; // Gemini prebuilt voice name (Kore, Puck, …)\n voice_stt_model: string; // Gemini multimodal model used for transcription\n voice_auto_speak: number; // 1 = auto-play reply when user sent voice\n display_filters: string | null; // JSON: Partial<DisplayFilters>; NULL = inherit defaults (ADR-0022)\n harness_id: string | null; // ADR-0033: per-agent harness override; NULL = inherit global default\n delegate_targets: string | null; // JSON string[] of agent ids this agent may delegate to; NULL/'[]' = none\n // ADR-0043. JSON-encoded `{ hot, warm, facts }` — any positive numbers; the\n // backend divides by sum so the UI can ship raw weights and never has to\n // reconcile to 100. NULL = inherit the model config's value.\n context_tier_proportions: string | null;\n // Per-agent override of the anti-hallucination classifier mode/model.\n // NULL on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob.\n anti_hallucination_mode: string | null; // \"off\" | \"report\" | \"enforce\"\n anti_hallucination_model_config: string | null; // saved model config name\n // When 1, the system prompt is augmented with a citation-link directive\n // and the assistant turn is post-checked by `anti_hallucination_model_config`\n // for {source link present, source previously visited in this thread}.\n // Independent of `anti_hallucination_mode` — stall detection and citation\n // enforcement can be on/off in any combination.\n require_source_links: number;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentTierProportions {\n hot: number;\n warm: number;\n facts: number;\n}\n\n/**\n * Parse the JSON-encoded per-agent override of context tier proportions.\n * Returns `null` for NULL, blank, malformed JSON, or any payload that\n * doesn't have three finite non-negative numeric fields. Callers fall\n * back to the model config's value (or built-in defaults) on null.\n */\nexport function getAgentTierProportions(row: AgentConfigRow): AgentTierProportions | null {\n const raw = row.context_tier_proportions;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<AgentTierProportions>;\n const hot = Number(parsed.hot);\n const warm = Number(parsed.warm);\n const facts = Number(parsed.facts);\n if (![hot, warm, facts].every((n) => Number.isFinite(n) && n >= 0)) return null;\n if (hot + warm + facts <= 0) return null;\n return { hot, warm, facts };\n } catch {\n return null;\n }\n}\n\nexport function listAgentConfigs(): AgentConfigRow[] {\n return getDb()\n .prepare(\"SELECT * FROM agent_configs ORDER BY is_default DESC, created_at ASC\")\n .all() as unknown as AgentConfigRow[];\n}\n\nexport function getDefaultAgentConfig(): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE is_default=1 LIMIT 1\")\n .get() as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport function getAgentConfig(id: string): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE id=?\")\n .get(id) as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport interface UpsertAgentInput {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n model_config_name?: string | null;\n is_default?: boolean;\n history_limit?: number;\n history_window_hours?: number;\n never_reply?: boolean;\n adaptive_persona_enabled?: boolean;\n adaptive_persona_strength?: number;\n adaptive_empathy?: number;\n adaptive_expressiveness?: number;\n adaptive_verbosity?: number;\n adaptive_mbti?: MbtiType;\n voice_enabled?: boolean;\n voice_model?: string;\n voice_name?: string;\n voice_stt_model?: string;\n voice_auto_speak?: boolean;\n harness_id?: string | null;\n delegate_targets?: string[];\n // ADR-0043. Pass `null` to clear the override and inherit from the model.\n // Pass `undefined` to keep whatever's already on the row (PATCH semantics).\n context_tier_proportions?: AgentTierProportions | null;\n // Per-agent anti-hallucination classifier override. `null` = clear the\n // override (inherit env). `undefined` = keep existing.\n anti_hallucination_mode?: \"off\" | \"regex\" | \"model\" | null;\n anti_hallucination_model_config?: string | null;\n // Citation enforcement (independent of stall detector). `undefined` = keep\n // existing. `false` = disable.\n require_source_links?: boolean;\n}\n\n/**\n * Parse the JSON-encoded delegate whitelist into a deduped string[]. Returns\n * an empty array for NULL, blank, or malformed JSON (delegation is opt-in).\n */\n/**\n * Parse the agent's tool allowlist (`tools` column, stored as a JSON string).\n * Returns an empty array on NULL/blank/malformed JSON — same defensive shape\n * as parseDelegateTargets. Callers that previously did `JSON.parse(cfg.tools)`\n * inline should switch to this getter so the serialization contract stays\n * owned by this store.\n */\nexport function getAgentTools(cfg: Pick<AgentConfigRow, \"tools\"> | null | undefined): string[] {\n if (!cfg?.tools) return [];\n try {\n const parsed = JSON.parse(cfg.tools);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n } catch {\n return [];\n }\n}\n\nexport function parseDelegateTargets(raw: string | null | undefined): string[] {\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n const ids = parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n return Array.from(new Set(ids));\n } catch {\n return [];\n }\n}\n\nexport function upsertAgentConfig(input: UpsertAgentInput): AgentConfigRow {\n const t = now();\n const db = getDb();\n const existing = getAgentConfig(input.id);\n const created_at = existing?.created_at ?? t;\n const mbti = input.adaptive_mbti ?? toMbti(existing?.adaptive_mbti) ?? \"INTJ\";\n const preset = MBTI_PRESETS[mbti];\n const strength = input.adaptive_persona_strength ?? preset.strength;\n const empathy = input.adaptive_empathy ?? preset.empathy;\n const expressiveness = input.adaptive_expressiveness ?? preset.expressiveness;\n const verbosity = input.adaptive_verbosity ?? preset.verbosity;\n if (input.is_default) db.prepare(\"UPDATE agent_configs SET is_default=0\").run();\n // harness_id: explicit `undefined` means \"keep existing\"; explicit `null`\n // means \"use the global default\". Empty string is normalised to null too,\n // matching how the AgentEditor sends \"\" for the inherit option.\n const harnessId =\n input.harness_id === undefined\n ? (existing?.harness_id ?? null)\n : (input.harness_id && input.harness_id.length > 0 ? input.harness_id : null);\n // delegate_targets: undefined = keep existing; explicit empty array clears.\n const delegateTargets = input.delegate_targets === undefined\n ? (existing?.delegate_targets ?? null)\n : JSON.stringify(Array.from(new Set(input.delegate_targets.filter((id) => id && id !== input.id))));\n // context_tier_proportions: undefined = keep existing; null = clear and\n // inherit from the model; object = serialise as JSON. Negative values are\n // clamped to 0 so the upsert can't poison the column with bad data.\n const tierProportions =\n input.context_tier_proportions === undefined\n ? (existing?.context_tier_proportions ?? null)\n : input.context_tier_proportions === null\n ? null\n : JSON.stringify({\n hot: Math.max(0, Number(input.context_tier_proportions.hot) || 0),\n warm: Math.max(0, Number(input.context_tier_proportions.warm) || 0),\n facts: Math.max(0, Number(input.context_tier_proportions.facts) || 0),\n });\n // Anti-hallucination override: `undefined` keeps existing; `null` clears\n // the override (inherits env). Empty-string model is normalised to null\n // so the editor can ship \"\" for the inherit option.\n const antiHallucMode =\n input.anti_hallucination_mode === undefined\n ? (existing?.anti_hallucination_mode ?? null)\n : input.anti_hallucination_mode === null\n ? null\n : (input.anti_hallucination_mode === \"off\" || input.anti_hallucination_mode === \"regex\" || input.anti_hallucination_mode === \"model\")\n ? input.anti_hallucination_mode\n : null;\n const antiHallucModel =\n input.anti_hallucination_model_config === undefined\n ? (existing?.anti_hallucination_model_config ?? null)\n : input.anti_hallucination_model_config && input.anti_hallucination_model_config.trim().length > 0\n ? input.anti_hallucination_model_config.trim()\n : null;\n const requireSourceLinks =\n input.require_source_links === undefined\n ? (existing?.require_source_links ?? 0)\n : (input.require_source_links ? 1 : 0);\n db.prepare(\n `INSERT OR REPLACE INTO agent_configs\n (id, name, icon, identity, instructions, tools, model_config_name, is_default,\n history_limit, history_window_hours, never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n voice_enabled, voice_model, voice_name, voice_stt_model, voice_auto_speak,\n harness_id, delegate_targets, context_tier_proportions,\n anti_hallucination_mode, anti_hallucination_model_config, require_source_links,\n created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n input.id,\n input.name,\n input.icon ?? null,\n input.identity,\n input.instructions,\n JSON.stringify(input.tools),\n input.model_config_name ?? null,\n input.is_default ? 1 : (existing?.is_default ?? 0),\n input.history_limit ?? existing?.history_limit ?? 50,\n input.history_window_hours ?? existing?.history_window_hours ?? 8,\n // never_reply is a boolean toggle — explicit `undefined` means \"keep existing\"\n // (important for PATCH-style updates that omit the field).\n input.never_reply === undefined\n ? (existing?.never_reply ?? 0)\n : (input.never_reply ? 1 : 0),\n input.adaptive_persona_enabled === undefined\n ? (existing?.adaptive_persona_enabled ?? 0)\n : (input.adaptive_persona_enabled ? 1 : 0),\n clampPercent(strength, existing?.adaptive_persona_strength ?? 50),\n clampPercent(empathy, existing?.adaptive_empathy ?? 50),\n clampPercent(expressiveness, existing?.adaptive_expressiveness ?? 50),\n clampPercent(verbosity, existing?.adaptive_verbosity ?? 50),\n mbti,\n input.voice_enabled === undefined\n ? (existing?.voice_enabled ?? 0)\n : (input.voice_enabled ? 1 : 0),\n (input.voice_model ?? existing?.voice_model ?? \"gemini-2.5-flash-preview-tts\").trim() ||\n \"gemini-2.5-flash-preview-tts\",\n (input.voice_name ?? existing?.voice_name ?? \"Kore\").trim() || \"Kore\",\n (input.voice_stt_model ?? existing?.voice_stt_model ?? \"gemini-2.5-flash\").trim() ||\n \"gemini-2.5-flash\",\n input.voice_auto_speak === undefined\n ? (existing?.voice_auto_speak ?? 1)\n : (input.voice_auto_speak ? 1 : 0),\n harnessId,\n delegateTargets,\n tierProportions,\n antiHallucMode,\n antiHallucModel,\n requireSourceLinks,\n created_at,\n t,\n );\n return getAgentConfig(input.id)!;\n}\n\nfunction clampPercent(next: number | undefined, fallback: number): number {\n const n = Number.isFinite(next) ? Number(next) : fallback;\n return Math.max(0, Math.min(100, Math.round(n)));\n}\n\nfunction toMbti(v: string | null | undefined): MbtiType | null {\n if (!v) return null;\n return (v in MBTI_PRESETS ? v : null) as MbtiType | null;\n}\n\nexport function deleteAgentConfig(id: string): boolean {\n return (\n (getDb().prepare(\"DELETE FROM agent_configs WHERE id=?\").run(id) as { changes: number }).changes > 0\n );\n}\n\nexport function generateAgentId(name: string): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 40);\n const suffix = Math.random().toString(36).slice(2, 6);\n return slug ? `${slug}-${suffix}` : `agent-${suffix}`;\n}\n\n// ── ADR-0022: per-agent message-channel display filters ─────────────────\n// Canonical channel keys mirrored in `hooks/useMessageFilters.ts`. Kept\n// in sync there by importing this constant — single source of truth.\nexport const DISPLAY_FILTER_KEYS = [\n \"scheduled_task\",\n \"watcher\",\n \"bridge\",\n \"synthetic\",\n \"tool_use\",\n \"thinking\",\n] as const;\nexport type DisplayFilterKey = (typeof DISPLAY_FILTER_KEYS)[number];\nexport type DisplayFilters = Record<DisplayFilterKey, boolean>;\n\nexport const DISPLAY_FILTER_DEFAULTS: DisplayFilters = {\n scheduled_task: true,\n watcher: true,\n bridge: true,\n synthetic: true,\n tool_use: true,\n thinking: true,\n};\n\nfunction parseDisplayFilters(raw: string | null | undefined): DisplayFilters {\n if (!raw) return { ...DISPLAY_FILTER_DEFAULTS };\n try {\n const parsed = JSON.parse(raw) as Partial<DisplayFilters>;\n // Merge over defaults so newly-added channels stay visible on old rows.\n return { ...DISPLAY_FILTER_DEFAULTS, ...parsed };\n } catch {\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n}\n\nexport function getAgentDisplayFilters(id: string): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n return parseDisplayFilters(row.display_filters);\n}\n\n/**\n * Merge a partial filter map into the agent's stored prefs. Pass `null` to\n * reset to defaults (clears the column). Safe against concurrent toggles\n * from multiple browser tabs because the merge happens server-side.\n */\nexport function updateAgentDisplayFilters(\n id: string,\n patch: Partial<DisplayFilters> | null,\n): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n if (patch === null) {\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=NULL, updated_at=? WHERE id=?\")\n .run(now(), id);\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n const current = parseDisplayFilters(row.display_filters);\n const next: DisplayFilters = { ...current };\n for (const k of DISPLAY_FILTER_KEYS) {\n if (k in patch && typeof patch[k] === \"boolean\") next[k] = patch[k] as boolean;\n }\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=?, updated_at=? WHERE id=?\")\n .run(JSON.stringify(next), now(), id);\n return next;\n}\n","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","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\");","// Tiny in-process pub/sub for app-level events the UI wants to surface as\n// browser notifications. Run completions and scheduled-task firings both\n// publish here; the frontend subscribes via a single SSE endpoint.\n\nimport { getConfig } from \"@/lib/env/config\";\n\nexport type NotificationEvent =\n | {\n type: \"run_completed\";\n thread_id: string;\n agent_id: string | null;\n status: \"done\" | \"error\";\n preview: string; // first ~100 chars of assistant reply\n ts: number;\n }\n | {\n type: \"task_completed\";\n task_id: string;\n agent_id: string;\n prompt: string;\n thread_id: string;\n // \"skipped\" is emitted when a silent scheduled task ran but the agent\n // chose not to surface a reply (NO_REPLY sentinel or empty). The chat\n // already stays quiet via messages.hidden; downstream notification\n // sinks can drop the ping too.\n status: \"done\" | \"error\" | \"skipped\";\n preview: string;\n error?: string;\n ts: number;\n }\n | {\n // Bridge replied to an inbound message on a configured route.\n type: \"bridge_message_received\";\n bridge_id: string;\n remote_jid: string;\n push_name: string | null;\n is_group: boolean;\n thread_id: string;\n agent_id: string;\n preview: string; // first ~120 chars of assistant reply\n ts: number;\n }\n | {\n // Bridge received a message from a chat that has no route configured.\n // Advisory only — surfaced in the UI as a \"Add route\" hint so the user\n // can copy the JID into a new route. The message itself is dropped.\n type: \"bridge_unrouted\";\n bridge_id: string;\n remote_jid: string;\n push_name: string | null;\n is_group: boolean;\n preview: string;\n ts: number;\n }\n | {\n // Bridge connection lifecycle: disconnected | pairing | connected | error.\n // Lets the UI flip status pills and surface QR data URLs live without\n // polling.\n type: \"bridge_status\";\n bridge_id: string;\n status: \"disconnected\" | \"pairing\" | \"connected\" | \"error\";\n error: string | null;\n paired_id: string | null;\n ts: number;\n }\n | {\n // A new message landed in a thread without an active LLM run firing —\n // currently published by the browser-extension page-capture route so\n // the open chat view re-fetches without waiting for the next run.\n type: \"thread_message_added\";\n thread_id: string;\n agent_id: string;\n source: \"page_capture\";\n ts: number;\n }\n | {\n // Background health probe detected a broken or recovered integration\n // / LLM key. The runner only publishes on state transitions or on\n // the long re-alert interval, so the UI can treat every alert as\n // worth surfacing. See lib/health/runner.ts.\n type: \"health_alert\";\n probe: string; // e.g. \"atlassian\", \"gmail\", \"anthropic\"\n label: string; // human label, e.g. \"Atlassian (Jira + Confluence)\"\n category: \"integration\" | \"llm\";\n status: \"auth_failed\" | \"transient\" | \"error\" | \"recovered\";\n error: string | null; // null when status=\"recovered\"\n ts: number;\n };\n\nimport { getOrCreateGlobal } from \"@/lib/utils/global-state\";\n\ntype Listener = (ev: NotificationEvent) => void;\n// JARELA_NOTIFICATION_RING_SIZE overrides this. Captured at module init —\n// changes require restart.\nconst RECENT_LIMIT = getConfig().notificationRingSize;\n\ninterface BusState {\n listeners: Set<Listener>;\n recent: NotificationEvent[];\n}\nconst busState = getOrCreateGlobal<BusState>(\"__jarela_notif_bus\", () => ({\n listeners: new Set<Listener>(),\n recent: [],\n}));\nconst listeners = busState.listeners;\nconst recent = busState.recent;\n\nexport function publish(ev: NotificationEvent): void {\n recent.push(ev);\n if (recent.length > RECENT_LIMIT) recent.shift();\n for (const l of listeners) {\n try { l(ev); } catch { /* listener errored, ignore */ }\n }\n}\n\nexport function subscribe(fn: Listener): () => void {\n listeners.add(fn);\n return () => { listeners.delete(fn); };\n}\n\n// Replay events newer than `sinceTs` (used when a client reconnects).\nexport function recentSince(sinceTs: number): NotificationEvent[] {\n return recent.filter((e) => e.ts > sinceTs);\n}\n","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\");","import { getDb } from \"@/lib/db\";\n\nconst now = () => new Date().toISOString();\n\nexport interface WhitelistEntry {\n identity: string;\n display_name: string | null;\n added_at: string;\n last_seen_at: string | null;\n}\n\nexport function listWhitelist(): WhitelistEntry[] {\n return getDb()\n .prepare(\"SELECT * FROM access_whitelist ORDER BY added_at ASC\")\n .all() as unknown as WhitelistEntry[];\n}\n\nexport function addToWhitelist(identity: string, displayName?: string | null): WhitelistEntry {\n const trimmed = identity.trim();\n if (!trimmed) throw new Error(\"identity is required\");\n getDb()\n .prepare(\n `INSERT INTO access_whitelist (identity, display_name, added_at, last_seen_at)\n VALUES (?, ?, ?, NULL)\n ON CONFLICT(identity) DO UPDATE SET display_name=excluded.display_name`,\n )\n .run(trimmed, displayName?.trim() || null, now());\n return getDb()\n .prepare(\"SELECT * FROM access_whitelist WHERE identity=?\")\n .get(trimmed) as unknown as WhitelistEntry;\n}\n\nexport function removeFromWhitelist(identity: string): void {\n getDb().prepare(\"DELETE FROM access_whitelist WHERE identity=?\").run(identity);\n}\n\nexport function isWhitelisted(identity: string): boolean {\n const row = getDb()\n .prepare(\"SELECT 1 FROM access_whitelist WHERE identity=?\")\n .get(identity);\n return !!row;\n}\n\nexport function touchLastSeen(identity: string): void {\n try {\n getDb()\n .prepare(\"UPDATE access_whitelist SET last_seen_at=? WHERE identity=?\")\n .run(now(), identity);\n } catch {\n // best-effort — never let this fail a request\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["getOrCreateGlobal","key","factory","g","globalThis","undefined","z","isLoopbackRequest","listThreadsByAgent","createThread","addMessage","getDefaultAgentConfig","listAgentConfigs","publish","MAX_TEXT_BYTES","Body","object","url","string","title","max","optional","selector","tagName","text","capturedAt","datetime","truncateUtf8","s","maxBytes","original","Buffer","byteLength","truncated","originalBytes","buf","from","subarray","toString","pickThread","def","agent","error","recent","id","length","thread_id","agent_id","agent_name","name","thread_title","created","t","composeBody","args","heading","lines","push","toLocaleString","join","handlePageCapture","req","Response","JSON","stringify","status","headers","raw","json","parsed","safeParse","success","issues","message","input","data","picked","messageBody","msg","type","source","ts","Date","now","msg_id","created_thread","get","handlePageCaptureOptions","POST","OPTIONS","isWhitelisted","touchLastSeen","LOOPBACK_HOST","LOOPBACK_IP","readHeader","lookup","toLowerCase","v","Array","isArray","requireAccess","host","remoteAddress","identity","trim","allowed","reason","test","SAFE_METHODS","Set","SAFE_FETCH_SITES","validateRequestOrigin","method","has","toUpperCase","secFetchSite","origin","originHost","URL","getDb","MBTI_PRESETS","toISOString","getAgentTierProportions","row","context_tier_proportions","parse","hot","Number","warm","facts","every","n","isFinite","prepare","all","getAgentConfig","getAgentTools","cfg","tools","filter","x","parseDelegateTargets","ids","upsertAgentConfig","db","existing","created_at","mbti","adaptive_mbti","toMbti","preset","strength","adaptive_persona_strength","empathy","adaptive_empathy","expressiveness","adaptive_expressiveness","verbosity","adaptive_verbosity","is_default","run","harnessId","harness_id","delegateTargets","delegate_targets","tierProportions","Math","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","requireSourceLinks","require_source_links","icon","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","deleteAgentConfig","changes","generateAgentId","slug","replace","slice","suffix","random","DISPLAY_FILTER_KEYS","DISPLAY_FILTER_DEFAULTS","scheduled_task","watcher","bridge","synthetic","tool_use","thinking","parseDisplayFilters","getAgentDisplayFilters","display_filters","updateAgentDisplayFilters","patch","current","k","getConfig","RECENT_LIMIT","notificationRingSize","busState","listeners","ev","shift","l","subscribe","fn","add","delete","recentSince","sinceTs","e","randomUUID","embedOne","MSG_COLS_SQL","listThreads","limit","offset","getThread","updated_at","message_count","deleteThread","r","getMessages","getRecentMessagesWindow","sinceISO","params","sql","rows","reverse","getMessagesAfter","afterISO","getMessagesPage","beforeISO","has_more","messages","role","content","toolEvents","category","metadata","toolEventsJson","metadataJson","Object","keys","then","vec","catch","tool_events","setMessageMetadata","getOrCreateAgentThread","agentId","clearThreadMessages","threadId","touchThread","firstMsg","setThreadContextPin","hot_since","setThreadWarmSummary","summary","before","listWhitelist","addToWhitelist","displayName","trimmed","Error","removeFromWhitelist"],"sourceRoot":"","ignoreList":[0,4,7,11,21,28,39,41]}
|
|
1
|
+
{"version":3,"file":"../app/api/v1/page-capture/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;ACAA,4EAA4E;AAC5E,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,qEAAqE;AACrE,oEAAoE;AACpE,EAAE;AACF,uEAAuE;AACvE,uDAAuD;AAChD,SAASA,kBAAqBC,GAAW,EAAEC,OAAgB;IAChE,MAAMC,IAAIC;IACV,IAAID,CAAC,CAACF,IAAI,KAAKI,WAAWF,CAAC,CAACF,IAAI,GAAGC;IACnC,OAAOC,CAAC,CAACF,IAAI;AACf;;;;;;;;ACbA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAwB;AAC8B;AAMxB;AAKM;AACc;AAElD,uEAAuE;AACvE,mEAAmE;AACnE,2CAA2C;AACpC,MAAMa,iBAAiB,OAAQ;AAEtC,MAAMC,OAAOT,sBAAQ,CAAC;IACpBW,KAAKX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S,MAAM;QACxBG,QAAQ;QACRC,SAAS;YACP,+BAA+BL,IAAIK,OAAO,CAACoB,GAAG,CAAC,aAAa;YAC5D,gCAAgC;YAChC,gCAAgC;YAChC,0BAA0B;YAC1B,QAAQ;QACV;IACF;AACF;;;ACpMA;;;;;;CAMC,GAEoF;AAE9E,MAAME,OAAO5B,iBAAiBA,CAAC;AAC/B,MAAM6B,UAAUF,wBAAwBA,CAAC;;;ACX+C;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AAC2B;AAC7F;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;AACp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U;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/./lib/utils/global-state.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/./lib/api/page-capture.ts","webpack://@circuitwall/jarela/./app/api/v1/page-capture/route.ts","webpack://@circuitwall/jarela/?ce97","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/./lib/auth/access.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/./lib/stores/agent-configs.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/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/./lib/notifications/bus.ts","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/./lib/stores/access.ts","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","// Pin a piece of state to globalThis so it survives Next.js dev hot-reload.\n//\n// Without this, every code edit re-evaluates the module, replacing the\n// in-memory state with empty containers — but any active closure still\n// references the OLD set, so listeners/timers/maps go silently dead.\n// The globalThis trick is the standard Next pattern for singletons.\n//\n// `key` must be unique across the app (it lives on globalThis); pick a\n// \"__jarela_<name>\" prefix to keep the namespace tidy.\nexport function getOrCreateGlobal<T>(key: string, factory: () => T): T {\n const g = globalThis as unknown as Record<string, unknown>;\n if (g[key] === undefined) g[key] = factory();\n return g[key] as T;\n}\n","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","import { z } from \"zod\";\nimport { isLoopbackRequest } from \"@/lib/auth/access\";\nimport {\n listThreadsByAgent,\n createThread,\n addMessage,\n type ThreadRow,\n} from \"@/lib/stores/threads\";\nimport {\n getDefaultAgentConfig,\n listAgentConfigs,\n type AgentConfigRow,\n} from \"@/lib/stores/agent-configs\";\nimport { publish } from \"@/lib/notifications/bus\";\n\n// 100KB UTF-8 cap on captured text. The LLM context window is the real\n// constraint; this cap exists to keep a runaway \"<body>\" pick from\n// trashing the conversation. See ADR-0018.\nexport const MAX_TEXT_BYTES = 100_000;\n\nconst Body = z.object({\n url: z.string().url(),\n title: z.string().max(500).optional(),\n selector: z.string().max(2000).optional(),\n tagName: z.string().max(64).optional(),\n text: z.string(),\n capturedAt: z.string().datetime(),\n});\n\nfunction truncateUtf8(s: string, maxBytes: number): { text: string; truncated: boolean; originalBytes: number } {\n const original = Buffer.byteLength(s, \"utf8\");\n if (original <= maxBytes) {\n return { text: s, truncated: false, originalBytes: original };\n }\n // Trim to byte boundary by encoding then slicing then decoding without\n // splitting a multibyte sequence. Buffer.toString(\"utf8\") replaces an\n // incomplete trailing sequence with U+FFFD, which is acceptable here.\n const buf = Buffer.from(s, \"utf8\").subarray(0, maxBytes);\n return { text: buf.toString(\"utf8\"), truncated: true, originalBytes: original };\n}\n\n// Routing rule (per user ask): the capture lands in the most recent thread\n// of the *default agent* — i.e. \"the last agent session\" the user almost\n// certainly meant. If the default agent has never been chatted with, we\n// open a fresh thread under it. If there is no default agent at all\n// (fresh install), fall back to the first configured agent. With zero\n// agents configured we 503 — there is nowhere to put the message.\n//\n// Scoping to the default agent (rather than \"most recent thread of any\n// agent\") makes routing predictable. Otherwise a stray reply on agent B\n// silently retargets future captures away from the agent the user\n// actually thinks of as \"theirs\".\ninterface PickResult {\n thread_id: string;\n agent_id: string;\n agent_name: string;\n thread_title: string | null;\n created: boolean;\n}\n\nfunction pickThread(): PickResult | { error: \"no-agent\" } {\n const def: AgentConfigRow | null = getDefaultAgentConfig();\n const agent: AgentConfigRow | null = def ?? listAgentConfigs()[0] ?? null;\n if (!agent) return { error: \"no-agent\" };\n\n const recent: ThreadRow[] = listThreadsByAgent(agent.id, 1);\n if (recent.length > 0) {\n return {\n thread_id: recent[0].thread_id,\n agent_id: agent.id,\n agent_name: agent.name,\n thread_title: recent[0].title,\n created: false,\n };\n }\n const t = createThread(agent.id, \"Browser captures\");\n return {\n thread_id: t.thread_id,\n agent_id: agent.id,\n agent_name: agent.name,\n thread_title: t.title,\n created: true,\n };\n}\n\nfunction composeBody(args: {\n url: string;\n title?: string;\n selector?: string;\n text: string;\n truncated: boolean;\n originalBytes: number;\n}): string {\n const heading = args.title\n ? `📎 Captured from [${args.title}](${args.url})`\n : `📎 Captured from <${args.url}>`;\n const lines = [heading];\n if (args.selector) lines.push(`Element: \\`${args.selector}\\``);\n if (args.truncated) {\n lines.push(`> ⚠ Truncated to ${MAX_TEXT_BYTES.toLocaleString()} bytes (original was ${args.originalBytes.toLocaleString()} bytes)`);\n }\n lines.push(\"\", \"---\", \"\", args.text);\n return lines.join(\"\\n\");\n}\n\nexport async function handlePageCapture(req: Request): Promise<Response> {\n if (!isLoopbackRequest(req)) {\n return new Response(JSON.stringify({ error: \"loopback only\" }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n let raw: unknown;\n try {\n raw = await req.json();\n } catch {\n return new Response(JSON.stringify({ error: \"Request body must be valid JSON\" }), {\n status: 400,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n const parsed = Body.safeParse(raw);\n if (!parsed.success) {\n return new Response(\n JSON.stringify({ error: parsed.error.issues[0]?.message ?? \"invalid body\" }),\n { status: 400, headers: { \"content-type\": \"application/json\" } },\n );\n }\n const input = parsed.data;\n\n const picked = pickThread();\n if (\"error\" in picked) {\n return new Response(JSON.stringify({ error: \"no agent configured\" }), {\n status: 503,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n const { thread_id, agent_id, agent_name, thread_title, created } = picked;\n\n const { text, truncated, originalBytes } = truncateUtf8(input.text, MAX_TEXT_BYTES);\n const messageBody = composeBody({\n url: input.url,\n title: input.title,\n selector: input.selector,\n text,\n truncated,\n originalBytes,\n });\n\n const msg = addMessage(thread_id, \"user\", messageBody, undefined, \"synthetic\");\n\n publish({\n type: \"thread_message_added\",\n thread_id,\n agent_id,\n source: \"page_capture\",\n ts: Date.now(),\n });\n\n return new Response(\n JSON.stringify({\n thread_id,\n msg_id: msg.msg_id,\n agent_id,\n agent_name,\n thread_title,\n created_thread: created,\n truncated,\n originalBytes,\n }),\n {\n status: 200,\n headers: {\n \"content-type\": \"application/json\",\n // Echo back so the extension's preflight succeeds. The actual\n // origin gate for this route is the loopback Host check above.\n \"access-control-allow-origin\": req.headers.get(\"origin\") ?? \"*\",\n \"access-control-allow-credentials\": \"false\",\n \"vary\": \"origin\",\n },\n },\n );\n}\n\nexport function handlePageCaptureOptions(req: Request): Response {\n return new Response(null, {\n status: 204,\n headers: {\n \"access-control-allow-origin\": req.headers.get(\"origin\") ?? \"*\",\n \"access-control-allow-methods\": \"POST, OPTIONS\",\n \"access-control-allow-headers\": \"content-type\",\n \"access-control-max-age\": \"600\",\n \"vary\": \"origin\",\n },\n });\n}\n","/**\n * @public — `POST /api/v1/page-capture` (with CORS `OPTIONS` preflight)\n *\n * Browser-extension upload endpoint: receives the active page's URL,\n * title, and selected/full text and routes it into the active thread.\n * See `docs/api.md`.\n */\n\nimport { handlePageCapture, handlePageCaptureOptions } from \"@/lib/api/page-capture\";\n\nexport const POST = handlePageCapture;\nexport const OPTIONS = handlePageCaptureOptions;\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/page-capture/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/page-capture/route\",\n pathname: \"/api/v1/page-capture\",\n filename: \"route\",\n bundlePath: \"app/api/v1/page-capture/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/page-capture/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/page-capture/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/page-capture/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","import { isWhitelisted, touchLastSeen } from \"@/lib/stores/access\";\n\n// Loopback host header signal — only meaningful when the server is bound to\n// 127.0.0.1 (the default). When a reverse proxy fronts Jarela, the proxy is\n// expected to preserve the client's original Host header, so this still\n// distinguishes \"local user typed localhost\" from \"tailnet client\".\nconst LOOPBACK_HOST = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:|$)/;\nconst LOOPBACK_IP = /^(127\\.|::1$|::ffff:127\\.)/;\n\nexport type AccessReason = \"loopback\" | \"whitelisted\" | \"no-identity\" | \"not-whitelisted\";\n\nexport interface AccessResult {\n allowed: boolean;\n identity: string | null;\n reason: AccessReason;\n}\n\ninterface HeaderBag {\n get(name: string): string | null;\n}\n\ninterface NodeHeaders {\n [name: string]: string | string[] | undefined;\n}\n\nfunction readHeader(\n headers: HeaderBag | NodeHeaders,\n name: string,\n): string | null {\n if (typeof (headers as HeaderBag).get === \"function\") {\n return (headers as HeaderBag).get(name);\n }\n const lookup = name.toLowerCase();\n const v = (headers as NodeHeaders)[lookup] ?? (headers as NodeHeaders)[name];\n if (Array.isArray(v)) return v[0] ?? null;\n return v ?? null;\n}\n\nexport interface RequireAccessArgs {\n headers: HeaderBag | NodeHeaders;\n host: string | null;\n remoteAddress?: string | null;\n}\n\nexport function requireAccess({ headers, host, remoteAddress }: RequireAccessArgs): AccessResult {\n // If tailscaled is proxying this request through `tailscale serve` it\n // *always* injects the Tailscale-User-Login header. Whenever the header\n // is present, treat the request as a tailnet request and enforce the\n // whitelist, regardless of whether the source IP / Host header looks\n // like loopback. Otherwise a non-whitelisted tailnet user could chat\n // just because the proxy is local.\n const identity = readHeader(headers, \"tailscale-user-login\")?.trim() || null;\n if (identity) {\n if (isWhitelisted(identity)) {\n touchLastSeen(identity);\n return { allowed: true, identity, reason: \"whitelisted\" };\n }\n return { allowed: false, identity, reason: \"not-whitelisted\" };\n }\n\n // No tailscale identity → only loopback is allowed (the host machine's\n // own user typing http://localhost:4312).\n\n // 1. Actual TCP source available — most reliable loopback signal. Used\n // by callers that have the raw socket (e.g. raw Node handlers).\n if (remoteAddress && LOOPBACK_IP.test(remoteAddress)) {\n return { allowed: true, identity: null, reason: \"loopback\" };\n }\n\n // 2. HTTP middleware path: socket source not available, fall back to Host\n // header. Only trustworthy when the bind is 127.0.0.1 (default).\n if (!remoteAddress && host && LOOPBACK_HOST.test(host)) {\n return { allowed: true, identity: null, reason: \"loopback\" };\n }\n\n return { allowed: false, identity: null, reason: \"no-identity\" };\n}\n\n// Convenience wrapper for API route handlers — they only have `Request`.\nexport function isLoopbackRequest(req: Request): boolean {\n const host = req.headers.get(\"host\");\n return !!host && LOOPBACK_HOST.test(host);\n}\n\n// ---------------------------------------------------------------------------\n// CSRF / cross-origin / DNS-rebinding defense\n// ---------------------------------------------------------------------------\n//\n// The proxy auth above accepts any loopback request — but every page in the\n// user's browser can issue `fetch(\"http://127.0.0.1:4312/...\")`, and a\n// remote DNS-rebinding attacker can make `evil.com` resolve to `127.0.0.1`\n// so the request looks loopback to the kernel. We need to confirm the\n// request *originated* same-origin, not just that the socket terminated on\n// loopback.\n//\n// Defense in depth:\n// 1. `Sec-Fetch-Site` — sent by every modern browser. `same-origin` and\n// `none` (top-level nav, address-bar) are safe; `cross-site` and\n// `same-site` are not. Header absent = non-browser caller (curl,\n// installer scripts) — allow, since those can't be tricked into\n// attaching cookies/auth.\n// 2. `Origin` — when present, scheme+host+port must match `Host`. Blocks\n// DNS rebinding because the Origin reflects the URL the attacker's\n// page was loaded from (`https://evil.com`), not the resolved IP.\n//\n// Read-only methods (GET / HEAD / OPTIONS) skip the check: the legitimate\n// SSE attach uses GET and is intentionally cross-tab in some PWA flows,\n// and these methods shouldn't have side effects anyway.\n\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\nconst SAFE_FETCH_SITES = new Set([\"same-origin\", \"none\"]);\n\nexport type OriginCheckReason =\n | \"safe-method\"\n | \"no-headers\"\n | \"same-origin\"\n | \"cross-site\"\n | \"origin-mismatch\";\n\nexport interface OriginCheckResult {\n allowed: boolean;\n reason: OriginCheckReason;\n}\n\nexport interface ValidateRequestOriginArgs {\n method: string;\n headers: HeaderBag | NodeHeaders;\n host: string | null;\n}\n\nexport function validateRequestOrigin({\n method,\n headers,\n host,\n}: ValidateRequestOriginArgs): OriginCheckResult {\n if (SAFE_METHODS.has(method.toUpperCase())) {\n return { allowed: true, reason: \"safe-method\" };\n }\n\n const secFetchSite = readHeader(headers, \"sec-fetch-site\");\n const origin = readHeader(headers, \"origin\");\n\n // Neither header → non-browser caller. The loopback bind plus the\n // tailnet identity check already gate this.\n if (!secFetchSite && !origin) {\n return { allowed: true, reason: \"no-headers\" };\n }\n\n if (secFetchSite && !SAFE_FETCH_SITES.has(secFetchSite)) {\n return { allowed: false, reason: \"cross-site\" };\n }\n\n if (origin && host) {\n try {\n const originHost = new URL(origin).host;\n if (originHost !== host) {\n return { allowed: false, reason: \"origin-mismatch\" };\n }\n } catch {\n // Malformed Origin → reject.\n return { allowed: false, reason: \"origin-mismatch\" };\n }\n }\n\n return { allowed: true, reason: \"same-origin\" };\n}\n","module.exports = require(\"node:http\");","import { getDb } from \"@/lib/db\";\nimport { MBTI_PRESETS, type MbtiType } from \"@/lib/agents/adaptive-persona-presets\";\n\nconst now = () => new Date().toISOString();\n\nexport interface AgentConfigRow {\n id: string;\n name: string;\n icon: string | null;\n identity: string;\n instructions: string;\n tools: string; // JSON string[]\n model_config_name: string | null;\n is_default: number;\n history_limit: number; // 0 = unlimited\n history_window_hours: number; // 0 = no time bound\n never_reply: number; // 1 = run the agent but don't auto-send replies via bridges\n adaptive_persona_enabled: number; // 1 = use runtime mood/tone adaptation hints\n adaptive_persona_strength: number; // 0..100, how strongly to adapt to cues\n adaptive_empathy: number; // 0..100, baseline empathetic tone\n adaptive_expressiveness: number; // 0..100, restrained -> energetic\n adaptive_verbosity: number; // 0..100, concise -> detailed\n adaptive_mbti: string; // one of 16 MBTI types\n voice_enabled: number; // 1 = expose mic/play UI for this agent\n voice_model: string; // Gemini TTS model id\n voice_name: string; // Gemini prebuilt voice name (Kore, Puck, …)\n voice_stt_model: string; // Gemini multimodal model used for transcription\n voice_auto_speak: number; // 1 = auto-play reply when user sent voice\n display_filters: string | null; // JSON: Partial<DisplayFilters>; NULL = inherit defaults (ADR-0022)\n harness_id: string | null; // ADR-0033: per-agent harness override; NULL = inherit global default\n delegate_targets: string | null; // JSON string[] of agent ids this agent may delegate to; NULL/'[]' = none\n // ADR-0043. JSON-encoded `{ hot, warm, facts }` — any positive numbers; the\n // backend divides by sum so the UI can ship raw weights and never has to\n // reconcile to 100. NULL = inherit the model config's value.\n context_tier_proportions: string | null;\n // Per-agent override of the anti-hallucination classifier mode/model.\n // NULL on either column = inherit the global JARELA_HALLUCINATION_DETECTOR_*\n // env knob.\n anti_hallucination_mode: string | null; // \"off\" | \"report\" | \"enforce\"\n anti_hallucination_model_config: string | null; // saved model config name\n // When 1, the system prompt is augmented with a citation-link directive\n // and the assistant turn is post-checked by `anti_hallucination_model_config`\n // for {source link present, source previously visited in this thread}.\n // Independent of `anti_hallucination_mode` — stall detection and citation\n // enforcement can be on/off in any combination.\n require_source_links: number;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AgentTierProportions {\n hot: number;\n warm: number;\n facts: number;\n}\n\n/**\n * Parse the JSON-encoded per-agent override of context tier proportions.\n * Returns `null` for NULL, blank, malformed JSON, or any payload that\n * doesn't have three finite non-negative numeric fields. Callers fall\n * back to the model config's value (or built-in defaults) on null.\n */\nexport function getAgentTierProportions(row: AgentConfigRow): AgentTierProportions | null {\n const raw = row.context_tier_proportions;\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<AgentTierProportions>;\n const hot = Number(parsed.hot);\n const warm = Number(parsed.warm);\n const facts = Number(parsed.facts);\n if (![hot, warm, facts].every((n) => Number.isFinite(n) && n >= 0)) return null;\n if (hot + warm + facts <= 0) return null;\n return { hot, warm, facts };\n } catch {\n return null;\n }\n}\n\nexport function listAgentConfigs(): AgentConfigRow[] {\n return getDb()\n .prepare(\"SELECT * FROM agent_configs ORDER BY is_default DESC, created_at ASC\")\n .all() as unknown as AgentConfigRow[];\n}\n\nexport function getDefaultAgentConfig(): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE is_default=1 LIMIT 1\")\n .get() as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport function getAgentConfig(id: string): AgentConfigRow | null {\n return (\n (getDb()\n .prepare(\"SELECT * FROM agent_configs WHERE id=?\")\n .get(id) as unknown as AgentConfigRow) ?? null\n );\n}\n\nexport interface UpsertAgentInput {\n id: string;\n name: string;\n icon?: string | null;\n identity: string;\n instructions: string;\n tools: string[];\n model_config_name?: string | null;\n is_default?: boolean;\n history_limit?: number;\n history_window_hours?: number;\n never_reply?: boolean;\n adaptive_persona_enabled?: boolean;\n adaptive_persona_strength?: number;\n adaptive_empathy?: number;\n adaptive_expressiveness?: number;\n adaptive_verbosity?: number;\n adaptive_mbti?: MbtiType;\n voice_enabled?: boolean;\n voice_model?: string;\n voice_name?: string;\n voice_stt_model?: string;\n voice_auto_speak?: boolean;\n harness_id?: string | null;\n delegate_targets?: string[];\n // ADR-0043. Pass `null` to clear the override and inherit from the model.\n // Pass `undefined` to keep whatever's already on the row (PATCH semantics).\n context_tier_proportions?: AgentTierProportions | null;\n // Per-agent anti-hallucination classifier override. `null` = clear the\n // override (inherit env). `undefined` = keep existing.\n anti_hallucination_mode?: \"off\" | \"regex\" | \"model\" | null;\n anti_hallucination_model_config?: string | null;\n // Citation enforcement (independent of stall detector). `undefined` = keep\n // existing. `false` = disable.\n require_source_links?: boolean;\n}\n\n/**\n * Parse the JSON-encoded delegate whitelist into a deduped string[]. Returns\n * an empty array for NULL, blank, or malformed JSON (delegation is opt-in).\n */\n/**\n * Parse the agent's tool allowlist (`tools` column, stored as a JSON string).\n * Returns an empty array on NULL/blank/malformed JSON — same defensive shape\n * as parseDelegateTargets. Callers that previously did `JSON.parse(cfg.tools)`\n * inline should switch to this getter so the serialization contract stays\n * owned by this store.\n */\nexport function getAgentTools(cfg: Pick<AgentConfigRow, \"tools\"> | null | undefined): string[] {\n if (!cfg?.tools) return [];\n try {\n const parsed = JSON.parse(cfg.tools);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n } catch {\n return [];\n }\n}\n\nexport function parseDelegateTargets(raw: string | null | undefined): string[] {\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n const ids = parsed.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n return Array.from(new Set(ids));\n } catch {\n return [];\n }\n}\n\nexport function upsertAgentConfig(input: UpsertAgentInput): AgentConfigRow {\n const t = now();\n const db = getDb();\n const existing = getAgentConfig(input.id);\n const created_at = existing?.created_at ?? t;\n const mbti = input.adaptive_mbti ?? toMbti(existing?.adaptive_mbti) ?? \"INTJ\";\n const preset = MBTI_PRESETS[mbti];\n const strength = input.adaptive_persona_strength ?? preset.strength;\n const empathy = input.adaptive_empathy ?? preset.empathy;\n const expressiveness = input.adaptive_expressiveness ?? preset.expressiveness;\n const verbosity = input.adaptive_verbosity ?? preset.verbosity;\n if (input.is_default) db.prepare(\"UPDATE agent_configs SET is_default=0\").run();\n // harness_id: explicit `undefined` means \"keep existing\"; explicit `null`\n // means \"use the global default\". Empty string is normalised to null too,\n // matching how the AgentEditor sends \"\" for the inherit option.\n const harnessId =\n input.harness_id === undefined\n ? (existing?.harness_id ?? null)\n : (input.harness_id && input.harness_id.length > 0 ? input.harness_id : null);\n // delegate_targets: undefined = keep existing; explicit empty array clears.\n const delegateTargets = input.delegate_targets === undefined\n ? (existing?.delegate_targets ?? null)\n : JSON.stringify(Array.from(new Set(input.delegate_targets.filter((id) => id && id !== input.id))));\n // context_tier_proportions: undefined = keep existing; null = clear and\n // inherit from the model; object = serialise as JSON. Negative values are\n // clamped to 0 so the upsert can't poison the column with bad data.\n const tierProportions =\n input.context_tier_proportions === undefined\n ? (existing?.context_tier_proportions ?? null)\n : input.context_tier_proportions === null\n ? null\n : JSON.stringify({\n hot: Math.max(0, Number(input.context_tier_proportions.hot) || 0),\n warm: Math.max(0, Number(input.context_tier_proportions.warm) || 0),\n facts: Math.max(0, Number(input.context_tier_proportions.facts) || 0),\n });\n // Anti-hallucination override: `undefined` keeps existing; `null` clears\n // the override (inherits env). Empty-string model is normalised to null\n // so the editor can ship \"\" for the inherit option.\n const antiHallucMode =\n input.anti_hallucination_mode === undefined\n ? (existing?.anti_hallucination_mode ?? null)\n : input.anti_hallucination_mode === null\n ? null\n : (input.anti_hallucination_mode === \"off\" || input.anti_hallucination_mode === \"regex\" || input.anti_hallucination_mode === \"model\")\n ? input.anti_hallucination_mode\n : null;\n const antiHallucModel =\n input.anti_hallucination_model_config === undefined\n ? (existing?.anti_hallucination_model_config ?? null)\n : input.anti_hallucination_model_config && input.anti_hallucination_model_config.trim().length > 0\n ? input.anti_hallucination_model_config.trim()\n : null;\n const requireSourceLinks =\n input.require_source_links === undefined\n ? (existing?.require_source_links ?? 0)\n : (input.require_source_links ? 1 : 0);\n db.prepare(\n `INSERT OR REPLACE INTO agent_configs\n (id, name, icon, identity, instructions, tools, model_config_name, is_default,\n history_limit, history_window_hours, never_reply,\n adaptive_persona_enabled, adaptive_persona_strength, adaptive_empathy, adaptive_expressiveness, adaptive_verbosity, adaptive_mbti,\n voice_enabled, voice_model, voice_name, voice_stt_model, voice_auto_speak,\n harness_id, delegate_targets, context_tier_proportions,\n anti_hallucination_mode, anti_hallucination_model_config, require_source_links,\n created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n input.id,\n input.name,\n input.icon ?? null,\n input.identity,\n input.instructions,\n JSON.stringify(input.tools),\n input.model_config_name ?? null,\n input.is_default ? 1 : (existing?.is_default ?? 0),\n input.history_limit ?? existing?.history_limit ?? 50,\n input.history_window_hours ?? existing?.history_window_hours ?? 8,\n // never_reply is a boolean toggle — explicit `undefined` means \"keep existing\"\n // (important for PATCH-style updates that omit the field).\n input.never_reply === undefined\n ? (existing?.never_reply ?? 0)\n : (input.never_reply ? 1 : 0),\n input.adaptive_persona_enabled === undefined\n ? (existing?.adaptive_persona_enabled ?? 0)\n : (input.adaptive_persona_enabled ? 1 : 0),\n clampPercent(strength, existing?.adaptive_persona_strength ?? 50),\n clampPercent(empathy, existing?.adaptive_empathy ?? 50),\n clampPercent(expressiveness, existing?.adaptive_expressiveness ?? 50),\n clampPercent(verbosity, existing?.adaptive_verbosity ?? 50),\n mbti,\n input.voice_enabled === undefined\n ? (existing?.voice_enabled ?? 0)\n : (input.voice_enabled ? 1 : 0),\n (input.voice_model ?? existing?.voice_model ?? \"gemini-2.5-flash-preview-tts\").trim() ||\n \"gemini-2.5-flash-preview-tts\",\n (input.voice_name ?? existing?.voice_name ?? \"Kore\").trim() || \"Kore\",\n (input.voice_stt_model ?? existing?.voice_stt_model ?? \"gemini-2.5-flash\").trim() ||\n \"gemini-2.5-flash\",\n input.voice_auto_speak === undefined\n ? (existing?.voice_auto_speak ?? 1)\n : (input.voice_auto_speak ? 1 : 0),\n harnessId,\n delegateTargets,\n tierProportions,\n antiHallucMode,\n antiHallucModel,\n requireSourceLinks,\n created_at,\n t,\n );\n return getAgentConfig(input.id)!;\n}\n\nfunction clampPercent(next: number | undefined, fallback: number): number {\n const n = Number.isFinite(next) ? Number(next) : fallback;\n return Math.max(0, Math.min(100, Math.round(n)));\n}\n\nfunction toMbti(v: string | null | undefined): MbtiType | null {\n if (!v) return null;\n return (v in MBTI_PRESETS ? v : null) as MbtiType | null;\n}\n\nexport function deleteAgentConfig(id: string): boolean {\n return (\n (getDb().prepare(\"DELETE FROM agent_configs WHERE id=?\").run(id) as { changes: number }).changes > 0\n );\n}\n\nexport function generateAgentId(name: string): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 40);\n const suffix = Math.random().toString(36).slice(2, 6);\n return slug ? `${slug}-${suffix}` : `agent-${suffix}`;\n}\n\n// ── ADR-0022: per-agent message-channel display filters ─────────────────\n// Canonical channel keys mirrored in `hooks/useMessageFilters.ts`. Kept\n// in sync there by importing this constant — single source of truth.\nexport const DISPLAY_FILTER_KEYS = [\n \"scheduled_task\",\n \"watcher\",\n \"bridge\",\n \"synthetic\",\n \"tool_use\",\n \"thinking\",\n] as const;\nexport type DisplayFilterKey = (typeof DISPLAY_FILTER_KEYS)[number];\nexport type DisplayFilters = Record<DisplayFilterKey, boolean>;\n\nexport const DISPLAY_FILTER_DEFAULTS: DisplayFilters = {\n scheduled_task: true,\n watcher: true,\n bridge: true,\n synthetic: true,\n tool_use: true,\n thinking: true,\n};\n\nfunction parseDisplayFilters(raw: string | null | undefined): DisplayFilters {\n if (!raw) return { ...DISPLAY_FILTER_DEFAULTS };\n try {\n const parsed = JSON.parse(raw) as Partial<DisplayFilters>;\n // Merge over defaults so newly-added channels stay visible on old rows.\n return { ...DISPLAY_FILTER_DEFAULTS, ...parsed };\n } catch {\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n}\n\nexport function getAgentDisplayFilters(id: string): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n return parseDisplayFilters(row.display_filters);\n}\n\n/**\n * Merge a partial filter map into the agent's stored prefs. Pass `null` to\n * reset to defaults (clears the column). Safe against concurrent toggles\n * from multiple browser tabs because the merge happens server-side.\n */\nexport function updateAgentDisplayFilters(\n id: string,\n patch: Partial<DisplayFilters> | null,\n): DisplayFilters | null {\n const row = getAgentConfig(id);\n if (!row) return null;\n if (patch === null) {\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=NULL, updated_at=? WHERE id=?\")\n .run(now(), id);\n return { ...DISPLAY_FILTER_DEFAULTS };\n }\n const current = parseDisplayFilters(row.display_filters);\n const next: DisplayFilters = { ...current };\n for (const k of DISPLAY_FILTER_KEYS) {\n if (k in patch && typeof patch[k] === \"boolean\") next[k] = patch[k] as boolean;\n }\n getDb()\n .prepare(\"UPDATE agent_configs SET display_filters=?, updated_at=? WHERE id=?\")\n .run(JSON.stringify(next), now(), id);\n return next;\n}\n","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","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\");","// Tiny in-process pub/sub for app-level events the UI wants to surface as\n// browser notifications. Run completions and scheduled-task firings both\n// publish here; the frontend subscribes via a single SSE endpoint.\n\nimport { getConfig } from \"@/lib/env/config\";\n\nexport type NotificationEvent =\n | {\n type: \"run_completed\";\n thread_id: string;\n agent_id: string | null;\n status: \"done\" | \"error\";\n preview: string; // first ~100 chars of assistant reply\n ts: number;\n }\n | {\n type: \"task_completed\";\n task_id: string;\n agent_id: string;\n prompt: string;\n thread_id: string;\n // \"skipped\" is emitted when a silent scheduled task ran but the agent\n // chose not to surface a reply (NO_REPLY sentinel or empty). The chat\n // already stays quiet via messages.hidden; downstream notification\n // sinks can drop the ping too.\n status: \"done\" | \"error\" | \"skipped\";\n preview: string;\n error?: string;\n ts: number;\n }\n | {\n // Bridge replied to an inbound message on a configured route.\n type: \"bridge_message_received\";\n bridge_id: string;\n remote_jid: string;\n push_name: string | null;\n is_group: boolean;\n thread_id: string;\n agent_id: string;\n preview: string; // first ~120 chars of assistant reply\n ts: number;\n }\n | {\n // Bridge received a message from a chat that has no route configured.\n // Advisory only — surfaced in the UI as a \"Add route\" hint so the user\n // can copy the JID into a new route. The message itself is dropped.\n type: \"bridge_unrouted\";\n bridge_id: string;\n remote_jid: string;\n push_name: string | null;\n is_group: boolean;\n preview: string;\n ts: number;\n }\n | {\n // Bridge connection lifecycle: disconnected | pairing | connected | error.\n // Lets the UI flip status pills and surface QR data URLs live without\n // polling.\n type: \"bridge_status\";\n bridge_id: string;\n status: \"disconnected\" | \"pairing\" | \"connected\" | \"error\";\n error: string | null;\n paired_id: string | null;\n ts: number;\n }\n | {\n // A new message landed in a thread without an active LLM run firing —\n // currently published by the browser-extension page-capture route so\n // the open chat view re-fetches without waiting for the next run.\n type: \"thread_message_added\";\n thread_id: string;\n agent_id: string;\n source: \"page_capture\";\n ts: number;\n }\n | {\n // Background health probe detected a broken or recovered integration\n // / LLM key. The runner only publishes on state transitions or on\n // the long re-alert interval, so the UI can treat every alert as\n // worth surfacing. See lib/health/runner.ts.\n type: \"health_alert\";\n probe: string; // e.g. \"atlassian\", \"gmail\", \"anthropic\"\n label: string; // human label, e.g. \"Atlassian (Jira + Confluence)\"\n category: \"integration\" | \"llm\";\n status: \"auth_failed\" | \"transient\" | \"error\" | \"recovered\";\n error: string | null; // null when status=\"recovered\"\n ts: number;\n };\n\nimport { getOrCreateGlobal } from \"@/lib/utils/global-state\";\n\ntype Listener = (ev: NotificationEvent) => void;\n// JARELA_NOTIFICATION_RING_SIZE overrides this. Captured at module init —\n// changes require restart.\nconst RECENT_LIMIT = getConfig().notificationRingSize;\n\ninterface BusState {\n listeners: Set<Listener>;\n recent: NotificationEvent[];\n}\nconst busState = getOrCreateGlobal<BusState>(\"__jarela_notif_bus\", () => ({\n listeners: new Set<Listener>(),\n recent: [],\n}));\nconst listeners = busState.listeners;\nconst recent = busState.recent;\n\nexport function publish(ev: NotificationEvent): void {\n recent.push(ev);\n if (recent.length > RECENT_LIMIT) recent.shift();\n for (const l of listeners) {\n try { l(ev); } catch { /* listener errored, ignore */ }\n }\n}\n\nexport function subscribe(fn: Listener): () => void {\n listeners.add(fn);\n return () => { listeners.delete(fn); };\n}\n\n// Replay events newer than `sinceTs` (used when a client reconnects).\nexport function recentSince(sinceTs: number): NotificationEvent[] {\n return recent.filter((e) => e.ts > sinceTs);\n}\n","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\");","import { getDb } from \"@/lib/db\";\n\nconst now = () => new Date().toISOString();\n\nexport interface WhitelistEntry {\n identity: string;\n display_name: string | null;\n added_at: string;\n last_seen_at: string | null;\n}\n\nexport function listWhitelist(): WhitelistEntry[] {\n return getDb()\n .prepare(\"SELECT * FROM access_whitelist ORDER BY added_at ASC\")\n .all() as unknown as WhitelistEntry[];\n}\n\nexport function addToWhitelist(identity: string, displayName?: string | null): WhitelistEntry {\n const trimmed = identity.trim();\n if (!trimmed) throw new Error(\"identity is required\");\n getDb()\n .prepare(\n `INSERT INTO access_whitelist (identity, display_name, added_at, last_seen_at)\n VALUES (?, ?, ?, NULL)\n ON CONFLICT(identity) DO UPDATE SET display_name=excluded.display_name`,\n )\n .run(trimmed, displayName?.trim() || null, now());\n return getDb()\n .prepare(\"SELECT * FROM access_whitelist WHERE identity=?\")\n .get(trimmed) as unknown as WhitelistEntry;\n}\n\nexport function removeFromWhitelist(identity: string): void {\n getDb().prepare(\"DELETE FROM access_whitelist WHERE identity=?\").run(identity);\n}\n\nexport function isWhitelisted(identity: string): boolean {\n const row = getDb()\n .prepare(\"SELECT 1 FROM access_whitelist WHERE identity=?\")\n .get(identity);\n return !!row;\n}\n\nexport function touchLastSeen(identity: string): void {\n try {\n getDb()\n .prepare(\"UPDATE access_whitelist SET last_seen_at=? WHERE identity=?\")\n .run(now(), identity);\n } catch {\n // best-effort — never let this fail a request\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["getOrCreateGlobal","key","factory","g","globalThis","undefined","z","isLoopbackRequest","listThreadsByAgent","createThread","addMessage","getDefaultAgentConfig","listAgentConfigs","publish","MAX_TEXT_BYTES","Body","object","url","string","title","max","optional","selector","tagName","text","capturedAt","datetime","truncateUtf8","s","maxBytes","original","Buffer","byteLength","truncated","originalBytes","buf","from","subarray","toString","pickThread","def","agent","error","recent","id","length","thread_id","agent_id","agent_name","name","thread_title","created","t","composeBody","args","heading","lines","push","toLocaleString","join","handlePageCapture","req","Response","JSON","stringify","status","headers","raw","json","parsed","safeParse","success","issues","message","input","data","picked","messageBody","msg","type","source","ts","Date","now","msg_id","created_thread","get","handlePageCaptureOptions","POST","OPTIONS","isWhitelisted","touchLastSeen","LOOPBACK_HOST","LOOPBACK_IP","readHeader","lookup","toLowerCase","v","Array","isArray","requireAccess","host","remoteAddress","identity","trim","allowed","reason","test","SAFE_METHODS","Set","SAFE_FETCH_SITES","validateRequestOrigin","method","has","toUpperCase","secFetchSite","origin","originHost","URL","getDb","MBTI_PRESETS","toISOString","getAgentTierProportions","row","context_tier_proportions","parse","hot","Number","warm","facts","every","n","isFinite","prepare","all","getAgentConfig","getAgentTools","cfg","tools","filter","x","parseDelegateTargets","ids","upsertAgentConfig","db","existing","created_at","mbti","adaptive_mbti","toMbti","preset","strength","adaptive_persona_strength","empathy","adaptive_empathy","expressiveness","adaptive_expressiveness","verbosity","adaptive_verbosity","is_default","run","harnessId","harness_id","delegateTargets","delegate_targets","tierProportions","Math","antiHallucMode","anti_hallucination_mode","antiHallucModel","anti_hallucination_model_config","requireSourceLinks","require_source_links","icon","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","deleteAgentConfig","changes","generateAgentId","slug","replace","slice","suffix","random","DISPLAY_FILTER_KEYS","DISPLAY_FILTER_DEFAULTS","scheduled_task","watcher","bridge","synthetic","tool_use","thinking","parseDisplayFilters","getAgentDisplayFilters","display_filters","updateAgentDisplayFilters","patch","current","k","getConfig","RECENT_LIMIT","notificationRingSize","busState","listeners","ev","shift","l","subscribe","fn","add","delete","recentSince","sinceTs","e","randomUUID","embedOne","MSG_COLS_SQL","listThreads","limit","offset","getThread","updated_at","message_count","deleteThread","r","getMessages","getRecentMessagesWindow","sinceISO","params","sql","rows","reverse","getMessagesAfter","afterISO","getMessagesPage","beforeISO","has_more","messages","role","content","toolEvents","category","metadata","toolEventsJson","metadataJson","Object","keys","then","vec","catch","tool_events","setMessageMetadata","getOrCreateAgentThread","agentId","clearThreadMessages","threadId","touchThread","firstMsg","setThreadContextPin","hot_since","setThreadWarmSummary","summary","before","listWhitelist","addToWhitelist","displayName","trimmed","Error","removeFromWhitelist"],"sourceRoot":"","ignoreList":[0,4,7,11,21,28,39,41]}
|
|
@@ -256,13 +256,20 @@ var mcp_servers = __webpack_require__(42666);
|
|
|
256
256
|
// EXTERNAL MODULE: ./lib/mcp/client.ts
|
|
257
257
|
var client = __webpack_require__(30572);
|
|
258
258
|
;// ./lib/mcp/registry.ts
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
259
|
+
/**
|
|
260
|
+
* @public
|
|
261
|
+
*
|
|
262
|
+
* MCP server registry types + variable substitution.
|
|
263
|
+
*
|
|
264
|
+
* Discovery is online via the official MCP Registry (see
|
|
265
|
+
* `lib/mcp/upstream-registry.ts` and ADR-0013). Entries flow through this
|
|
266
|
+
* module's types so the picker UI, install action, and `applyVariables`
|
|
267
|
+
* substitution path stay decoupled from the upstream wire format.
|
|
268
|
+
*
|
|
269
|
+
* All exports in this file are part of the package's stable public
|
|
270
|
+
* surface (per `package.json#exports`). Removing or breaking them counts
|
|
271
|
+
* as a breaking change under the deprecation policy in CONTRIBUTING.md.
|
|
272
|
+
*/ // Substitute `${var}` placeholders in a spec object using user-supplied values.
|
|
266
273
|
// Walks objects and arrays recursively; leaves non-strings alone.
|
|
267
274
|
function applyVariables(spec, values) {
|
|
268
275
|
return walk(spec);
|