@circuitwall/jarela 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +2 -2
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  5. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  6. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  15. package/.next/standalone/.next/server/app/_not-found.rsc +1 -1
  16. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  17. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  20. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  22. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +37 -3
  23. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
  24. package/.next/standalone/.next/server/app/page.js +10 -2
  25. package/.next/standalone/.next/server/app/page.js.map +1 -1
  26. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  27. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  28. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  29. package/.next/standalone/.next/server/pages/404.html +1 -1
  30. package/.next/standalone/.next/server/pages/500.html +1 -1
  31. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  32. package/.next/standalone/.next/static/chunks/app/{page-2ab710949b62a638.js → page-74846c864241b96d.js} +11 -3
  33. package/.next/standalone/.next/static/chunks/app/page-74846c864241b96d.js.map +1 -0
  34. package/.next/standalone/package.json +2 -1
  35. package/CHANGELOG.md +24 -0
  36. package/README.md +51 -26
  37. package/components/chat/InputBar.tsx +10 -1
  38. package/lib/api/page-capture.test.ts +58 -0
  39. package/lib/api/page-capture.ts +31 -1
  40. package/package.json +2 -1
  41. package/.next/standalone/.next/static/chunks/app/page-2ab710949b62a638.js.map +0 -1
  42. /package/.next/standalone/.next/static/{ZKy7LJ3KXj2TIyKOg_fBH → AV5AO0yTRABo-NgwxhDe7}/_buildManifest.js +0 -0
  43. /package/.next/standalone/.next/static/{ZKy7LJ3KXj2TIyKOg_fBH → AV5AO0yTRABo-NgwxhDe7}/_ssgManifest.js +0 -0
@@ -418,6 +418,10 @@ var agent_turn = __webpack_require__(62032);
418
418
  // constraint; this cap exists to keep a runaway "<body>" pick from
419
419
  // trashing the conversation. See ADR-0018.
420
420
  const MAX_TEXT_BYTES = 100000;
421
+ // Hard cap on the inline element screenshot (base64 chars). 4 MB of
422
+ // base64 ≈ 3 MB decoded — generous for a single cropped element while
423
+ // still bounding the SQLite row and the LLM vision payload.
424
+ const MAX_SCREENSHOT_B64 = 4000000;
421
425
  // Preamble prepended to the LLM call for the silent observer run.
422
426
  // The captured content is already persisted in the DB — this wrapper
423
427
  // instructs the agent to observe without replying, matching bridge
@@ -430,7 +434,14 @@ const Body = schemas/* object */.Ik({
430
434
  selector: schemas/* string */.Yj().max(2000).optional(),
431
435
  tagName: schemas/* string */.Yj().max(64).optional(),
432
436
  text: schemas/* string */.Yj(),
433
- capturedAt: schemas/* string */.Yj().datetime()
437
+ capturedAt: schemas/* string */.Yj().datetime(),
438
+ // Optional base64-encoded PNG of just the picked element (no data: URL
439
+ // prefix). The content script crops `chrome.tabs.captureVisibleTab`
440
+ // to the element bounding box before sending. When present, it is
441
+ // attached to the persisted user message as an image ContentPart so
442
+ // the chat UI renders it inline and vision-capable agents can see it.
443
+ screenshot: schemas/* string */.Yj().regex(/^[A-Za-z0-9+/=]+$/).max(MAX_SCREENSHOT_B64).optional(),
444
+ screenshotMediaType: schemas/* string */.Yj().regex(/^image\/[a-z0-9.+-]+$/).max(64).optional()
434
445
  });
435
446
  function truncateUtf8(s, maxBytes) {
436
447
  const original = Buffer.byteLength(s, "utf8");
@@ -482,6 +493,7 @@ function composeBody(args) {
482
493
  heading
483
494
  ];
484
495
  if (args.selector) lines.push(`Element: \`${args.selector}\``);
496
+ if (args.hasScreenshot) lines.push("Screenshot attached.");
485
497
  if (args.truncated) {
486
498
  lines.push(`> ⚠ Truncated to ${MAX_TEXT_BYTES.toLocaleString()} bytes (original was ${args.originalBytes.toLocaleString()} bytes)`);
487
499
  }
@@ -543,9 +555,28 @@ async function handlePageCapture(req) {
543
555
  selector: input.selector,
544
556
  text,
545
557
  truncated,
546
- originalBytes
558
+ originalBytes,
559
+ hasScreenshot: Boolean(input.screenshot)
547
560
  });
548
- const msg = (0,threads/* addMessage */.tj)(thread_id, "user", messageBody, undefined, "page_capture");
561
+ // When a screenshot is included, persist the user turn as a multipart
562
+ // ContentPart[] (text + image) — that's the same shape the chat UI and
563
+ // agent runner expect for inline images, so the picture renders in the
564
+ // bubble on reload and vision-capable models can see it on the silent
565
+ // observer turn. Without a screenshot we keep the legacy string body
566
+ // to avoid touching messages that never had an image.
567
+ const screenshotPart = input.screenshot ? {
568
+ type: "image",
569
+ media_type: input.screenshotMediaType ?? "image/png",
570
+ data: input.screenshot
571
+ } : null;
572
+ const storedContent = screenshotPart ? JSON.stringify([
573
+ {
574
+ type: "text",
575
+ text: messageBody
576
+ },
577
+ screenshotPart
578
+ ]) : messageBody;
579
+ const msg = (0,threads/* addMessage */.tj)(thread_id, "user", storedContent, undefined, "page_capture");
549
580
  // Fire a silent observer run so the agent ingests the captured context
550
581
  // without being forced to reply — matching bridge silent/observer mode.
551
582
  // The user message is already persisted above; skip_persist_user_message
@@ -554,6 +585,9 @@ async function handlePageCapture(req) {
554
585
  thread_id,
555
586
  queue_source: "extension",
556
587
  message: `${SILENT_CAPTURE_PREAMBLE}\n\n${messageBody}`,
588
+ attachments: screenshotPart ? [
589
+ screenshotPart
590
+ ] : undefined,
557
591
  user_category: "page_capture",
558
592
  assistant_category: "page_capture",
559
593
  silent: true,
@@ -1 +1 @@
1
- {"version":3,"file":"../app/api/v1/page-capture/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;ACAmE;AAEnE,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,oEAAoE;AACpE,MAAME,gBAAgB;AACtB,MAAMC,cAAc;AAkBpB,SAASC,WACPC,OAAgC,EAChCC,IAAY;IAEZ,IAAI,OAAO,QAAuBC,GAAG,KAAK,YAAY;QACpD,OAAO,QAAuBA,GAAG,CAACD;IACpC;IACA,MAAME,SAASF,KAAK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;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;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CAA+C;AAC/C;AACA;AACA;AACA;AACA,CAAC,EAAC;AACF,iBAAiB,mBAAO,CAAC,KAAqB;AAC9C,sBAAsB,mBAAO,CAAC,KAAiB;AAC/C,eAAe,mBAAO,CAAC,KAAa;AACpC;AACA;AACA;AACA,IAAI,KAAmC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,gBAAgB,mBAAmB;AACnC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/./lib/auth/access.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/./lib/api/page-capture.ts","webpack://@circuitwall/jarela/./app/api/v1/page-capture/route.ts","webpack://@circuitwall/jarela/?bc23","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:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/./lib/stores/access.ts","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","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\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","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\";\nimport { runAgentTurn } from \"@/lib/agents/agent-turn\";\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\n// Preamble prepended to the LLM call for the silent observer run.\n// The captured content is already persisted in the DB — this wrapper\n// instructs the agent to observe without replying, matching bridge\n// silent/observer mode semantics. The user can ask about the content\n// in a later normal turn.\nconst SILENT_CAPTURE_PREAMBLE =\n \"[Silent page capture — observer mode] \" +\n \"A web page was just captured to your context by the user's browser extension. \" +\n \"Silently review it. You must NOT reply with content now — the user will ask questions later. \" +\n \"If nothing requires immediate attention, reply with exactly the single token NO_REPLY.\";\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, \"page_capture\");\n\n // Fire a silent observer run so the agent ingests the captured context\n // without being forced to reply — matching bridge silent/observer mode.\n // The user message is already persisted above; skip_persist_user_message\n // prevents a duplicate. Fire-and-forget so the HTTP response is instant.\n void runAgentTurn({\n thread_id,\n queue_source: \"extension\",\n message: `${SILENT_CAPTURE_PREAMBLE}\\n\\n${messageBody}`,\n user_category: \"page_capture\",\n assistant_category: \"page_capture\",\n silent: true,\n skip_persist_user_message: true,\n }).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n console.warn(\"[page-capture] silent observer run failed:\", m);\n });\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(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","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","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["isWhitelisted","touchLastSeen","LOOPBACK_HOST","LOOPBACK_IP","readHeader","headers","name","get","lookup","toLowerCase","v","Array","isArray","requireAccess","host","remoteAddress","identity","trim","allowed","reason","test","isLoopbackRequest","req","SAFE_METHODS","Set","SAFE_FETCH_SITES","validateRequestOrigin","method","has","toUpperCase","secFetchSite","origin","originHost","URL","z","listThreadsByAgent","createThread","addMessage","getDefaultAgentConfig","listAgentConfigs","publish","runAgentTurn","MAX_TEXT_BYTES","SILENT_CAPTURE_PREAMBLE","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","thread_title","created","t","composeBody","args","heading","lines","push","toLocaleString","join","handlePageCapture","Response","JSON","stringify","status","raw","json","parsed","safeParse","success","issues","message","input","data","picked","messageBody","msg","undefined","queue_source","user_category","assistant_category","silent","skip_persist_user_message","catch","err","m","Error","String","console","warn","type","source","ts","Date","now","msg_id","created_thread","handlePageCaptureOptions","POST","OPTIONS","getDb","toISOString","listWhitelist","prepare","all","addToWhitelist","displayName","trimmed","run","removeFromWhitelist","row"],"sourceRoot":"","ignoreList":[0,4,6,10,17,27,37,40]}
1
+ {"version":3,"file":"../app/api/v1/page-capture/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAs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A;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qB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A,CAAC,CAAC;AACF,qCAA+C;AAC/C;AACA;AACA;AACA;AACA,CAAC,EAAC;AACF,iBAAiB,mBAAO,CAAC,KAAqB;AAC9C,sBAAsB,mBAAO,CAAC,KAAiB;AAC/C,eAAe,mBAAO,CAAC,KAAa;AACpC;AACA;AACA;AACA,IAAI,KAAmC;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,gBAAgB,mBAAmB;AACnC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;;;;;;ACrEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/./lib/auth/access.ts","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/./lib/api/page-capture.ts","webpack://@circuitwall/jarela/./app/api/v1/page-capture/route.ts","webpack://@circuitwall/jarela/?bc23","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:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/./lib/stores/access.ts","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","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\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","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\";\nimport { runAgentTurn } from \"@/lib/agents/agent-turn\";\nimport type { ContentPart } from \"@/lib/tools/types\";\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\n// Hard cap on the inline element screenshot (base64 chars). 4 MB of\n// base64 ≈ 3 MB decoded — generous for a single cropped element while\n// still bounding the SQLite row and the LLM vision payload.\nexport const MAX_SCREENSHOT_B64 = 4_000_000;\n\n// Preamble prepended to the LLM call for the silent observer run.\n// The captured content is already persisted in the DB — this wrapper\n// instructs the agent to observe without replying, matching bridge\n// silent/observer mode semantics. The user can ask about the content\n// in a later normal turn.\nconst SILENT_CAPTURE_PREAMBLE =\n \"[Silent page capture — observer mode] \" +\n \"A web page was just captured to your context by the user's browser extension. \" +\n \"Silently review it. You must NOT reply with content now — the user will ask questions later. \" +\n \"If nothing requires immediate attention, reply with exactly the single token NO_REPLY.\";\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 // Optional base64-encoded PNG of just the picked element (no data: URL\n // prefix). The content script crops `chrome.tabs.captureVisibleTab`\n // to the element bounding box before sending. When present, it is\n // attached to the persisted user message as an image ContentPart so\n // the chat UI renders it inline and vision-capable agents can see it.\n screenshot: z.string().regex(/^[A-Za-z0-9+/=]+$/).max(MAX_SCREENSHOT_B64).optional(),\n screenshotMediaType: z.string().regex(/^image\\/[a-z0-9.+-]+$/).max(64).optional(),\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 hasScreenshot?: boolean;\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.hasScreenshot) lines.push(\"Screenshot attached.\");\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 hasScreenshot: Boolean(input.screenshot),\n });\n\n // When a screenshot is included, persist the user turn as a multipart\n // ContentPart[] (text + image) — that's the same shape the chat UI and\n // agent runner expect for inline images, so the picture renders in the\n // bubble on reload and vision-capable models can see it on the silent\n // observer turn. Without a screenshot we keep the legacy string body\n // to avoid touching messages that never had an image.\n const screenshotPart: ContentPart | null = input.screenshot\n ? { type: \"image\", media_type: input.screenshotMediaType ?? \"image/png\", data: input.screenshot }\n : null;\n const storedContent: string = screenshotPart\n ? JSON.stringify([{ type: \"text\", text: messageBody }, screenshotPart] satisfies ContentPart[])\n : messageBody;\n\n const msg = addMessage(thread_id, \"user\", storedContent, undefined, \"page_capture\");\n\n // Fire a silent observer run so the agent ingests the captured context\n // without being forced to reply — matching bridge silent/observer mode.\n // The user message is already persisted above; skip_persist_user_message\n // prevents a duplicate. Fire-and-forget so the HTTP response is instant.\n void runAgentTurn({\n thread_id,\n queue_source: \"extension\",\n message: `${SILENT_CAPTURE_PREAMBLE}\\n\\n${messageBody}`,\n attachments: screenshotPart ? [screenshotPart] : undefined,\n user_category: \"page_capture\",\n assistant_category: \"page_capture\",\n silent: true,\n skip_persist_user_message: true,\n }).catch((err: unknown) => {\n const m = err instanceof Error ? err.message : String(err);\n console.warn(\"[page-capture] silent observer run failed:\", m);\n });\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(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","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","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");"],"names":["isWhitelisted","touchLastSeen","LOOPBACK_HOST","LOOPBACK_IP","readHeader","headers","name","get","lookup","toLowerCase","v","Array","isArray","requireAccess","host","remoteAddress","identity","trim","allowed","reason","test","isLoopbackRequest","req","SAFE_METHODS","Set","SAFE_FETCH_SITES","validateRequestOrigin","method","has","toUpperCase","secFetchSite","origin","originHost","URL","z","listThreadsByAgent","createThread","addMessage","getDefaultAgentConfig","listAgentConfigs","publish","runAgentTurn","MAX_TEXT_BYTES","MAX_SCREENSHOT_B64","SILENT_CAPTURE_PREAMBLE","Body","object","url","string","title","max","optional","selector","tagName","text","capturedAt","datetime","screenshot","regex","screenshotMediaType","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","thread_title","created","t","composeBody","args","heading","lines","push","hasScreenshot","toLocaleString","join","handlePageCapture","Response","JSON","stringify","status","raw","json","parsed","safeParse","success","issues","message","input","data","picked","messageBody","Boolean","screenshotPart","type","media_type","storedContent","msg","undefined","queue_source","attachments","user_category","assistant_category","silent","skip_persist_user_message","catch","err","m","Error","String","console","warn","source","ts","Date","now","msg_id","created_thread","handlePageCaptureOptions","POST","OPTIONS","getDb","toISOString","listWhitelist","prepare","all","addToWhitelist","displayName","trimmed","run","removeFromWhitelist","row"],"sourceRoot":"","ignoreList":[0,4,6,10,17,27,37,40]}
@@ -3642,6 +3642,11 @@ function fileToContentPart(file) {
3642
3642
  }
3643
3643
  });
3644
3644
  }
3645
+ function attachmentKey(a, i) {
3646
+ if (a.type === "text") return `text:${i}:${a.text.length}`;
3647
+ const name = a.type === "file" ? a.name : "";
3648
+ return `${a.type}:${a.media_type}:${name}:${a.data.length}:${a.data.slice(0, 16)}`;
3649
+ }
3645
3650
  function InputBar({ attachments, onAttachmentsChange, onSubmit, onQueue, onStop, streaming, disabled, placeholder, voiceEnabled, agentId, onVoiceTranscript }) {
3646
3651
  // Text state is intentionally LOCAL. Lifting it to ChatView would re-render
3647
3652
  // the entire message list (every MessageBubble + ReactMarkdown pass) on
@@ -3846,7 +3851,10 @@ function InputBar({ attachments, onAttachmentsChange, onSubmit, onQueue, onStop,
3846
3851
  children: [
3847
3852
  attachments.length > 0 && /*#__PURE__*/ (0,react_jsx_runtime.jsx)("div", {
3848
3853
  className: "flex flex-wrap gap-2 mb-2",
3849
- children: attachments.map((a, i)=>/*#__PURE__*/ (0,react_jsx_runtime.jsxs)("div", {
3854
+ children: attachments.map((a, i)=>// Content-derived key — using the index reused DOM nodes when
3855
+ // earlier attachments were removed, flashing the wrong preview
3856
+ // (and the wrong filename) into the slot of the survivor.
3857
+ /*#__PURE__*/ (0,react_jsx_runtime.jsxs)("div", {
3850
3858
  className: "relative group shrink-0",
3851
3859
  children: [
3852
3860
  a.type === "image" ? // eslint-disable-next-line @next/next/no-img-element
@@ -3875,7 +3883,7 @@ function InputBar({ attachments, onAttachmentsChange, onSubmit, onQueue, onStop,
3875
3883
  })
3876
3884
  })
3877
3885
  ]
3878
- }, i))
3886
+ }, attachmentKey(a, i)))
3879
3887
  }),
3880
3888
  /*#__PURE__*/ (0,react_jsx_runtime.jsxs)("div", {
3881
3889
  className: "relative flex gap-2 items-end",